jeudi 5 novembre 2015

How to find similar records of one csv file into another csv file write all records into a result.csv file by python

I would like to search and then copy / merge two CSV files based on the common records of adv_id and user_id in both files based on conv_id, and store records in a new CSV file. That means I will take the records from both CSV files if the adv_id and user_id is same in both files. But when I use nested for loops for to search same adv_id and user_id of fileOne into fileTwo, it takes very long execution times. This is because, fileOne contains 8 Million records, fileTwo contain 50 million records. Below is an example of the files and expected result file. fileOne and fileTwo contain the fillowing columns. Your kind suggestions in highly appreciated.

fileOne: adv_id, conv_id, user_id, dwell, session, pv, elapsed, cvflg.

fileTwo: adv_id, user_id, dwell, session, pv, elapsed, cvflg

Image of fileOne, fileTwo, and Result file

Python "List assignment index out of range"

I am a novice student in Python (and programming in general).

I am supposed to make a python program that opens two files with random numbers in them and creates a new file with the numbers ordered from lowest to highest.

So I made this code that iterates using two for loops through all the numbers, searching for the lowest, very basic stuff, than stores the number and its position, appends to a Lmix list that will be saved on the final file and stores the numbers position to delete it from that list so it won't be found again.

The variables are in Portuguese, but I translated them in the comments, the rest are self-explanatory.

arq1 = open("nums1.txt","r")
arq2 = open("nums2.txt","r")

arqmix = open("numsord.txt","w")

L1 = arq1.readlines()
L2 = arq2.readlines()
Lmix = []

L1 = list(map(int,L1)) # converts lists into int
L2 = list(map(int,L2))

cont = 0

menor = L1[0]  # "Menor" is the variable that stores the lowest number it finds
menorpos = 0   # "Menorpos" is the position of that variable in the list, so it can delete later
listdec = 0    # "listdec" just stores which list the number was from to delete.

while cont != (len(L1)+len(L2)):   

# while loops that finds the lowest number, stores the number and position, appends to the Lmix and deletes from the list so it won't be found on next   iteration

    n = 0
    for n,x in enumarate(L1):
        m = 0
        for m,y in enumarate(L2):
            if x<menor:
                menor = x
                menorpos = n
                listdec = 0
            elif y<menor:
                menor = y
                menorpos = m
                listdec = 1
            m += 1
        n += 1

    Lmix.append(menor)
    if listdec == 0:
        del L1[menorpos]
    elif listdec == 1:
        del L2[menorpos]
    cont += 1

for x in Lmix:
    arqmix.write("%d\n"%x)

arq1.close()
arq2.close()
arqmix.close()

But everytime I run it, this error appears:

Traceback (most recent call last): File "C:/Users/Danzmann-Notebook/PycharmProjects/untitled/aula18.py", line 41, in del L2[menorpos] IndexError: list assignment index out of range

I know what it means but I just can't understand why it happens, and how can I solve it.

Any help would be appreciated.

Thanks in advance, sorry for any grammar error, english is not my native language.

C++ function prototyping input file into vector

create a function which reads a text file & returns its contents in a vector; its prototype is sdd::vector<std::string> SDI::readTextFile(const std::string );

The initial specification is to read a text file the name of the file is the parameter, which can include a path. The return value will be a vector of strings.

What is the second function asking me to do? Would std::ifstream File("textFile.txt");meet the prototype?

Getting information from a file

can anyone help me how this file created?

i want to get the data of this file.

is it compressed or encrypted?

the file is created in Delphi compiled program.

file composed of numbers and colors

Concantenate user input Strings to convert into a complete file path (Java)

I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:

    import java.io.*;
    import java.util.Scanner;
public class FilePractice {
  public static void main(String[] args) {

    //create a new File object
    File myFile = new File("/home/christopher/Desktop/myFile");

    try{
        System.out.println("Would you like to create a new file? Y or N: ");
        Scanner input = new Scanner(System.in);
        String choice = input.nextLine();
        if(choice.equalsIgnoreCase("Y"))
        {
            myFile.createNewFile();
        }
        else
        {
            //do nothing
        }
    }catch(IOException e) {
        System.out.println("Error while creating file " + e);
    }
    System.out.println("'myFile' " + myFile.getPath() + " created.");
  }
}

I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.

Perhaps my syntax is wrong?

If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).

Here is the expanded attempt:

try {
       System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
            String fileName = input.nextLine();
            input.nextLine();
            System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
            String userFilePath = input.nextLine();
            File userFile = new File(userFilePath, fileName);
            System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
            String userChoice = input.nextLine();

            if (userChoice.equalsIgnoreCase("Y")) {
                userFile.createNewFile();
                //print for debug 
                System.out.println(userFile.getPath());
               }
            }catch(IOException e) {
                System.out.println("Error while attempting to create file " + e);
            }
            System.out.println("File created successfully");

My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.

Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.

How to iterate through set of files based on file names?

I have a set of files named like this:

qd-p64-dZP-d64-z8-8nn.q         
qd-p8-dPZ-d8-z1-1nn.q             qq-p8-dZP-d8-z1-2nn.q
qd-p8-dPZ-d8-z1-2nn.q             qq-p8-dZP-d8-z1-4nn.q
qd-p8-dPZ-d8-z1-4nn.q             qq-p8-dZP-d8-z16-1nn.q
qd-p8-dPZ-d8-z16-1nn.q            qq-p8-dZP-d8-z16-2nn.q
qd-p8-dPZ-d8-z16-2nn.q            qq-p8-dZP-d8-z16-4nn.q
qd-p8-dPZ-d8-z16-4nn.q            qq-p8-dZP-d8-z16-8nn.q
qd-p8-dPZ-d8-z16-8nn.q            qq-p8-dZP-d8-z1-8nn.q
qd-p8-dPZ-d8-z1-8nn.q             qq-p8-dZP-d8-z2-1nn.q
qd-p8-dPZ-d8-z2-1nn.q             qq-p8-dZP-d8-z2-2nn.q
qd-p8-dPZ-d8-z2-2nn.q             qq-p8-dZP-d8-z2-4nn.q 
qd-p8-dPZ-d8-z2-4nn.q             qq-p8-dZP-d8-z2-8nn.q
qd-p8-dPZ-d8-z2-8nn.q             qq-p8-dZP-d8-z32-1nn.q
qd-p8-dPZ-d8-z32-1nn.q            qq-p8-dZP-d8-z32-2nn.q
qd-p8-dPZ-d8-z32-2nn.q            qq-p8-dZP-d8-z32-4nn.q
qd-p8-dPZ-d8-z32-4nn.q            qq-p8-dZP-d8-z32-8nn.q
qd-p8-dPZ-d8-z32-8nn.q            qq-p8-dZP-d8-z4-1nn.q
qd-p8-dPZ-d8-z4-1nn.q             qq-p8-dZP-d8-z4-2nn.q
qd-p8-dPZ-d8-z4-2nn.q             qq-p8-dZP-d8-z4-4nn.q

The information to iterate is given in the file names, for example:

Fix

dZP, 1nn, z2,  

and vary

d 

with values

{d8, d16, d32 d64}

Then, increase z value to get

dZP, 1nn, z4

and vary d again

{d8, d16, d32 d64}   

Once I'm able to iterate like this I need to do some information processing from the files.

Clojure lazily read random line from file

I have a sample data set in a txt file. The data file is extremely large so loading it in memory is not an option. I need to be able to read the file lazily. Furthermore, I need the lines to be read in a random order. And there might be cases where I don't need to read all the lines. This is what I found so far -

(defn read-lazy [in-file]
        (letfn [(helper [rdr]
                            (if-let [line (.readLine rdr)]
                                (cons line (helper rdr))
                                (do (.close rdr) nil)))]
            (helper (io/reader in-file))))

which returns a lazy-seq of the file. How can I loop through random lines in the lazy-seq when I need to? I think using a go block could help here. Go blocks could put a random line in a channel and await for something to consume it. Once the data gets read it puts another line in the channel awaits for the next read. How can I implement that?

Here's how I've worked it out (not random) -

(def lazy-ch (chan))
(defn async-fetch-set [in-file]
    (go
        (with-open [reader (io/reader in-file)]
            (doseq [line (line-seq reader)]
                (>! lazy-ch line)))
        (close! lazy-ch)))

(println "got: " (<!! lazy-ch))

Is this a good way to approach the problem? Is there a better solution? I might not need to read all the lines so I'd like to be able to close the reader if whenever I need to.

Having trouble sorting the data from a file

I am opening and reading a .txt file and trying to save values in the format 0.x or 0.xy or 0.xyz.

x must be a digit 1-9

y cannot be 0 or a odd number

z cannot be 0 or a even number

My current code is only saving the variables in the format 0.x but is skipping over the 0.xy and 0.xyz.

For text file has 16000 elements and contains ints, floats, and strings:

.03243234

234.234

.223

0.2

MWFE

etc.

list = []

with open("exam2data.txt") as f:
    for line in f:
        line = f.readline()
        xCounter = 0
        yCounter = 0
        zCounter = 0

        try:
            lineFloat = float(line)
            if lineFloat < 1:
                if len(line) == 4:
                    if line[3] == 0:
                        pass
                    else:
                        list.append(lineFloat)
                        xCounter += 1

                elif len(line) == 5:
                    if line[3] == 0:
                        pass
                    else:
                        if line[2] == 0:
                            pass
                        else:
                            y = float(line[4])
                            if (y % 2 == 0):
                                list.append(lineFloat)
                                yCounter += 1
                            else:
                                pass

                elif len(line) == 6:
                     if line[4] == 0:
                        pass
                     else:
                        if line[5] == 0:
                            pass
                        else:
                            if line[3] == 0:
                                pass
                            else:
                                y = float(line[4])
                                z = float(line[5])
                                if (y % 2 == 0):
                                    if (z % 2 == 1):
                                        list.append(lineFloat)
                                        zCounter += 1
                                    else:
                                        pass
                                else:
                                    pass


        except:
            pass

print(len(list))
print(', '.join(map(str, list)))

How to return the contents of the file as a list of messages

The parameter represents a message file that is already open for reading, and which contains one message per line.

Read and return the contents of the file as a list of messages, in the order in which they appear in the file. Strip the newline from each line.

def read_messages(file):
    """
    """
    message = []
    for line in file:
        new_line = line.strip()
        message.append(new_line)
    return message

well, I know this is not the correct answer but I have no idea how can I fix it.

Ruby File.open strange behaviour

I found a very strange behaviour of File

[3] pry():1> File.zero?(file.path)
=> true
[4] pry():1> file.size
=> 3894
[5] pry():1> File.zero?(file.path)
=> false

The real file sizes from [3] and [5] can be confirmed by checking them in bash.

Is there an explanation for this behaviour? One thing to mention before is that file.class might be File or Tempfile and it happens in both cases.

Loading an int and an encrypted String from txt file

I am working on the password login portion of a class project. Nothing fancy. User, or role will be an int and password is a String. I am just using a simple encryption for now. The problem I am having is while reading the file I am getting an input mismatch. I have done something similar in the past that required me to read ints and Strings and did not have any problems. But I just cannot figure out what is going wrong in this case. Any help as to why I am getting this error would be greatly appreciated. I am using while(inputStream.hasNextLine()) then read the int and then the String I have tried hasNextInt and hasNext and keep getting the same error.

public void readFile(){
    Scanner inputStream = null;
    try {
        inputStream = new Scanner (new FileInputStream("login.txt"));
    }catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    if(inputStream != null){
    while (inputStream.hasNextLine()){
        int luser = inputStream.nextInt();
        String lpass = inputStream.nextLine();
        newFile[count] = new accessNode(luser, lpass);
        count ++;
    }
    inputStream.close();
    }    
}

The best way to create local file for a program [on hold]

I am planning a new software. This software will have a central database, SQL. However, I want each terminal that this software is installed on to have a backup plan, in case the database server is disconnected for whatever reason. What is the best way to go about this? Should we just create a local file? We want a certain table to be always available to the terminal in case the sql server is disconnected. Also, how do we update this file when new items are inserted into the database? send over TCP/IP or retrieve by software on terminal? The issue with retrieve, let's assume we have 100 terminals, it would be a hassle to do each on individually.

Thanks in advance.

Read json file in and write without indentation

The following code take a folder of json files (saved with indentation) open it, get content and serialize to json and write to file a new file. Same code task in python works, so it is not the data. But the rust version you see in here:

extern crate rustc_serialize;
use rustc_serialize::json;
use std::io::Read;
use std::fs::read_dir;
use std::fs::File;
use std::io::Write;
use std::io;
use std::str;


fn write_data(filepath: &str, data: json::Json) -> io::Result<()> {

    let mut ofile = try!(File::create(filepath));
    let encoded: String = json::encode(&data).unwrap();
    try!(ofile.write(encoded.as_bytes()));
    Ok(())
}


fn main() {

    let root = "/Users/bling/github/data/".to_string();
    let folder_path = root + &"texts";
    let paths = read_dir(folder_path).unwrap();

    for path in paths {
        let input_filename = format!("{}", path.unwrap().path().display());
        let output_filename = str::replace(&input_filename, "texts", "texts2");

        let mut data = String::new();
        let mut f = File::open(input_filename).unwrap();
        f.read_to_string(&mut data).unwrap();
        let json = json::Json::from_str(&data).unwrap();

        write_data(&output_filename, json).unwrap();
    }
}

Do you have spot an Error in my code already or did I get some language concepts wrong. Is the rustc-serialize cargo wrongly used. At the end it does not work as expected - to outperform python.

± % cargo run --release --verbose                                                                                                                                            
       Fresh rustc-serialize v0.3.16
       Fresh fileprocessing v0.1.0 (file:///Users/bling/github/rust/fileprocessing)
     Running `target/release/fileprocessing`
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: SyntaxError("unescaped control character in string", 759, 55)', ../src/libcore/result.rs:736
Process didn't exit successfully: `target/release/fileprocessing` (exit code: 101)

How to count all lines, words, and characters in a file

I'm trying to write a program that counts all of the lines, words, and characters in a .txt file. I have the lines coming out but I don't know how to do the words or characters.

"""Write a function stats() that takes one input argument: the name of a text file. The function should print, on the screen, the number of lines, words, and characters in the file; your function should open the file only once.

stats( 'example.txt') line count: 3 word count: 20 character count: 98"""

def stats(inF):

inFile=open(inF,'r')  
text=inFile.readlines() 
textLen=len(text)  
print(textLen) 

 wordCount=0
 charCount=0

 for word in inFile.read().split():
    if word in inFile:
         wordCount = +1
      else:
          wordCount = 1
   print(wordCount)

print(stats("n.txt"))

How to read specific line of file in python

Is there a concise way to read a specific (e.g. line #5) of a file object in python? Saying file.readline() only reads me the first line, and I only know how to use a for loop to read every single line of the file. Thanks!

Best option for handling files in C++ [on hold]

I am currently writing a program (console application), which allows users to create an account, and then, in their accounts, to create and save notes that bind to that account.

My program uses a 2 binary search tree structures to handle all the accounts and notes, but I also want to save all the account data (usernames, password, what notes belong to it, etc..) and all the note note data into external files, so that it is not lost when the user closes the program.

The only way I know for handling files with c++ would be to use the "fstream" library. I was wondering if there is a better way for me to write my program, using something different than the fstream library, and if yes - what is it?

Thanks for any relevant replies in advance :)

Rename Function?

I've tried using this code to move a file to another place.

#include <stdio.h>

    int main()
    {
      rename("C:\\Users\\Mohammed Mehdi\\Documents\\Visual Studio 2012\\Projects\\Kyle", "C:\\Users\\Mohammed Mehdi\\Documents\\Visual Studio 2012");
      return 0;
    }

The problem is that when I actually check all my computer files, nothing's happened. I've checked the return codes and it's returning 0 so it should be fine. I also have no errors.

I've looked at this question, but my code has no errors while I'm running it. Rename function doesn't work, Visual Studio 2013 RC

How can one count randomly white-spaced delimited values from a file in Fortran?

If one has a file containing, for example:

1 2 3   4    5
6  7  8  9  10
   11    12   13
14 15
16             17
        18
  19  20

How can one get the correct number of integers (in the given example, 20) from counting them in the file in Fortran?

PHP open and show most recent file from an folder via FTP

I would like to connect to a FTP Server via PHP and take the most recent file from a certain directory and show it in that PHP file.

So I can go to http://ift.tt/1mfppjW and see what's in that file. These files have the following name "Filename_20150721-085620_138.csv", so the second values 20150721 is the date. Also these files only contain CSV Text.

Is there any way in doing that?

POST Request Receive Files

I'm using Oboe for a client POST request to a server. The server returns a zip file with an attachment disposition, but when testing it nothing happens when it receives the response. Here's the Oboe request:

promiseOboe({
  url: configuration.rootApiUrl + 'pdffile/download/separated',
  method: 'POST',
  body: { pdfs: appState.pdfs }
}).then(function(data) {
  // Should I do something here?
}).catch(function(err){console.log(err)});

Here's the response header:

Access-Control-Allow-Origin: *
Cache-Control:no-cache
Content-Disposition:attachment; filename=Filename.zip
Content-Length:22
Content-Type:application/octet-stream
Date:Thu, 05 Nov 2015 19:27:38 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcc2NvdHRoXERvY3VtZW50c1xBbGxfQ29kZVxFZGl0UGRmU2VydmVyXEVkaXRQZGZTZXJ2ZXJcYXBpXHBkZmZpbGVcZG93bmxvYWRcc2VwYXJhdGVk?=

Am I missing something? Should I do something in the .then() fucntion? Why doesn't the browser receive the files in its standard way of downloading them?

PHP does not copy the file properly

im copying a file from another domain. It does not give me any errors but the files does not get recognized and its different size from the original file. Its the same extension i checked. so im kinda clueless.

if (!copy('http://ift.tt/1kx0w6N - Juvenile and Infant/1440.jpg', $_SERVER['DOCUMENT_ROOT'].'/resources/categories/tttt6.jpg')) {
echo "failed";
}

any ideas?

How to change headers of a CSV file using Ruby

I am trying to change the headers of a CSV file using a ruby script, however I am only able to change the rows of data, and not the headers. I have tried looking at other examples, however they did not work. I have been looking at some of the Ruby documentation here, however it is still no working. Here is how I ma trying to do it right now:

input = File.open TestFile, 'r' #read
output = File.open TestFile, 'w' #write
CSV.filter input, output, :headers => true, :write_headers => true, :return_headers => true do |csv|
  csv << ["Test"] if row.header_row?
end

CakePHP File API not working

I'm trying to open a file using CakePHP's File API, but it is not working. When I put in the file path is throws a warning saying that it expects a string, which I am passing. Here is my code:

//more code before this...
}elseif(is_uploaded_file( $file_tmp_name)){
    $filePath = $dir.DS.$filename;    // I store the file path
    move_uploaded_file.($file_tmp_name,$filePath); 
    $this->insertToDB($filePath);      //I pass the path as a parameter
 }

public function insertToDB($path){      //lee el archivo recien subido para agregarlo a la BD
    $query = $this->connect();      //conectar a base de datos
    echo $path;
    echo gettype($path);
    $file = new File($path);
}

When I try to run it, it throws an error saying that $path is an array, and taht it expects a string. I have already printed $path and its type and everything seems to be in order. Any ideas? Thank you in advance.

Better Way to Display new Image Document in Picturebox

I'm using WinForms. In my Form i have a picturebox. This program looks in "C:\image\" directory to find a specified image document, in my case a tif file. There is always only one picture in "C:\image\" directory.

After it locates the file, the program displays the image document in the picturebox.

When i was running this i saw that the CPU usage was high. My Goal is to make performance better or find out if there is a better way of coding this.

What i have to do: I have to manually go into my C:\image\ directory and delete the current image document then place a new image document in there so my picturebox will show the new image document.

In short, i have to delete the old image document and replace it with the new one, so i can view the new image document in my picturebox.

   int picWidth, picHeight;

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1_Tick(sender, e);
    }

    private void File_Length()
    {
        try
        {
            string path = @"C:\image\";
            string[] filename = Directory.GetFiles(path, "*.tif"); //gets a specific image doc.

            FileInfo fi = new FileInfo(filename[0]);
            byte[] buff = new byte[fi.Length];
            using (FileStream fs = File.OpenRead(filename[0]))
            {
                fs.Read(buff, 0, (int)fi.Length);
            }
            MemoryStream ms = new MemoryStream(buff);
            Bitmap img1 = new Bitmap(ms);
            //opened = true; // the files was opened.
            pictureBox1.Image = img1;

            pictureBox1.Width = img1.Width;
            pictureBox1.Height = img1.Height;
            picWidth = pictureBox1.Width;
            picHeight = pictureBox1.Height;
        }
        catch(Exception)
        {
            //MessageBox.Show(ex.Message);
        }
    }

    public void InitTimer()
    {
        timer1 = new Timer(); 
        timer1.Tick += new EventHandler(timer1_Tick); //calls method
        timer1.Interval = 2000; // in miliseconds (1 second = 1000 millisecond)
        timer1.Start(); //starts timer
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        File_Length(); //checking the file length every 2000 miliseconds
    }

Cannot upload a MP4 file to Plone 3.1.1

I have an MP4 file that I have been trying to upload for four days. It is a 48 minute long video of a webinar training conducted, so I need to put it on Plone so that it can be accessed by staff. When I try to upload it, a small box in the lower corner shows Updating X%, but it keeps running from 0 to 100% over and over again. I left it running overnight and it still never uploaded. It's stuck in some type of loop. I am able to upload other files, including other MP4 files. I originally thought it was the video, so I reproduced it in my video editing software. Same results. It does not matter how I save the video (different resolutions, different fps, different bitrates, different extensions), this video will not upload. I have tried from my office, a co-worker's office, and my home to see if it was a network issue. I have used different user accounts and had others try to upload it. We have used multiple browsers. I cannot find an error messages to tell em what is going on. We even rebooted the server. Has anyone else ran into this? Is there a hidden place for error messages? I am frustrated with this. If additional information is needed, please contact me. Due to confidentiality, I cannot provide the video itself.

Why cant I change the the file extension of a desired file in java?

I cant understand why my code refuses to change the file extension of my txt file to java.

Here's my code:

public static void main(String[] arg) {

 File file  = new File("file.txt"); //File I want to change to .java
 File file2 = new File("file.java"); 

 boolean success = file.renameTo(file2); //boolean to check if successful


 if (success == true)
 {
     System.out.println("file extension change successful");

 }else
 {
     System.out.println("File extension change failed");
 }

}// main

It always prints "file extension failed" each time and I honestly do not understand why. I'm starting to suspect it might be the permissions on my computer. The compiler I use is Eclipse.

FIXED:

THE CAUSE OF THE PROBLEM: I had placed the file I wanted to change, file.txt, in the package folder inside my project folder. C:\Users\Acer\workspace\MyProjectName\src\MyPackageName. As a consequence the file could not be found by the system.

THE SOLUTION: I simply moved the file, file.txt, into the main project folder; C:\Users\Acer\workspace\MyProjectName and this fixed the problem. When I run my program it returns

file extension change successful

.

Thank you all for your help. I really appreciate it.

Attach hidden options to a file in C#

So I want to attach some secret info to my files in a program, and VS2013 throws an exception stating:

An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll

Additional information: The specified path format is not supported.

For the lines:

string metafile = filename + ":key";
StreamWriter metadata = new StreamWriter(metafile);

How can I solve this? I need it, because this way I can check it with console with the command: "notepad file.txt:key".

Can't use URL for File

My old version works, but if I try to export to runnable Jar File, it doesn't load the txt file.

public String jarLocation = getClass().getProtectionDomain()
        .getCodeSource().getLocation().getPath();
public File txt = new File(jarLocation + "/images/gewinne.txt");

After that I tried with get Resource, but the File can't load the URL part :/ I am lost

public URL urlGewinne = Kalender.class.getResource("/images/gewinne.txt");
public File txt = new File(urlGewinne); // ERROR

public void txtLesen() throws IOException {
    try {
        BufferedReader br = new BufferedReader(new FileReader(txt));
        String line = null;
        while ((line = br.readLine()) != null) {
            gewinne.add(line);
        }

        br.close();
    } catch (FileNotFoundException ex) {

    }
}

$.fileDownload completion action missing

I'm using jquery.fileDownload plugin, and everything works fine, apart of the fact that .done function never gets triggered. File gets downloaded, and nothing happens after

This is my code:

$.fileDownload(self.resourceUrl + '/Export?' + querystring)
.done(function () {
alert('File download a success!');
})
.fail(function () {
alert('File download failed!');
});

This is my controller method (ASP.NET Web API)

public HttpResponseMessage GetExport([FromUri]MyObject myobject)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(...);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/excel");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = myobject.Title + ".xls"
};
return response;
}

Is it because I'm using API nothing happens after file being downloaded?

Reading data from files from a user input

So I have a text file that I've made up with a persons name followed by a comma and then a place where they could live. Yes I know its random but I need a way to understand this :)

So here is the text file (called "namesAndPlaces.txt"):

Bob,Bangkok
Ellie,London
Anthony,Beijing
Michael,Boston
Fred,Texas
Alisha,California

So I want the user to be able to enter a name into the program and then the program looks at the text file to see where they live and then prints it out to the user.

How can I do this? Thanks Michael

C# Monogame error due to directories

I've recently started learning code on my free time with a few friends, and we just recently started on a tohou-esque game together. Instead of coding on seperate computers, we usually take turns on one laptop with Visual Studio on it. However, when I downloaded the program of drive, I got this wierd error which I have no idea how to solve, and I cant find any help on google or programming forums.

What we use: Visual studio with Monogame.

The Error:

Severity Code Description Project File Line Error The source file "c:\users\boman\documents\visual studio 2015\Projects\TouhouPara\TouhouPara\Content\bin\Windows\" is actually a directory. The "Copy" task does not support copying directories.

Is it thread-safe to copy a file to different destinations with one thread each

I need to load the content of a file on different computers at the same time. Because a StreamReader will occupy the file, I want to copy it to a temporary folder before opening it. (The title is more general as there should be no difference between two threads running on one computer and two computers running one thread each.)

Question: will two threads copying a file at the same time affect each other even when the copy destinations are eparated?

Error: The file "Info.plist" couldn't be opened xcode swift

enter image description here

I get this error without doing anything. I just made a Lable on Main.storyboard - First Scene. Then i tried to take a look at it and the message "build failed" came. Since then this error is shown.

Redmine can't access uploaded file with accent

I'm having the same issue with two redmine installations, I've made a short vidéo to illustrate the problem : https://youtu.be/u6W9uEPQNHk

I can't consult/download uploaded files with accent. Redmine returns a 404 error.

The log corresponding at the 404 error :

Started GET "//attachments/download/64/Test file with space and accént.jpg" for 2.9.10.148 at 2015-11-05 15:21:34 +0000
Processing by AttachmentsController#download as HTML
  Parameters: {"id"=>"64", "filename"=>"Test file with space and acc\xC3\xA9nt.jpg"}
  Current user: david (id=2)
  Rendered common/error.html.erb within layouts/base (0.2ms)
Filter chain halted as :find_attachment rendered or redirected
Completed 404 Not Found in 94ms (Views: 41.2ms | ActiveRecord: 37.1ms)

Here informations about redmine installations, 1st one (used for the video) :

Environment:
  Redmine version                3.0.3.stable
  Ruby version                   1.9.3-p194 (2012-04-20) [x86_64-linux]
  Rails version                  4.2.1
  Environment                    production
  Database adapter               PostgreSQL
SCM:
  Git                            1.9.1
  Filesystem                     
Redmine plugins:
  redmine_agile                  1.3.8

2nd one :

Environment:
  Redmine version                3.1.1.stable
  Ruby version                   2.0.0-p247 (2013-06-27) [x86_64-linux]
  Rails version                  4.2.4
  Environment                    production
  Database adapter               Mysql2
SCM:
  Subversion                     1.6.6
  Cvs                            1.12.13
  Git                            1.7.0.4
  Filesystem                     
Redmine plugins:
  redmine_agile                  1.3.11
  redmine_contacts               4.0.2
  redmine_contacts_helpdesk      3.0.1

Do not hesite to ask for other details.

Thanks for your support, David

Null pointer exception using an external file

I get a NullPointerException when I try to execute a script file using another file to find the script.

Here is the code used to execute the connection to MySql DB using the file DB.conf. If the DB doesn't exists, using the DB.conf file, the code should extract the path of the script (the path of the script is the same of the DB.conf).

Here is my code :

public class MySqlConnection {

/**
 * campo per la connessione al database
 */
protected Connection connessione;

/**
 * campo statement
 */
protected Statement stat;

/**
 * campo per i risultati della query
 */
  protected ResultSet res;

    /**
 * campo di preparazione statement
 */
   protected PreparedStatement prepStat;

   protected boolean connect() throws ClassNotFoundException, SQLException,
        IOException {
    connessione = null;
    boolean connection = false;


    InputStream input = getClass().getResourceAsStream("/DB.conf");
    BufferedReader br = new BufferedReader(new InputStreamReader(input));
    new Driver();
    String src = br.readLine().toString();
    String db = br.readLine().toString();
    String user = br.readLine().toString();
    String password = br.readLine().toString();

    try {
        String jdbc = (new StringBuilder("jdbc:mysql://")).append(src)
                .append("/").append(db).toString();
        connessione = DriverManager.getConnection(jdbc, user, password);

    } catch (SQLException e) {
        if (e.getErrorCode() == 1049) {
            JOptionPane
                    .showMessageDialog(null,
                            "Database 'Carloan' non esistente! \nInstallazione del db in corso...");
            String jdbc = (new StringBuilder("jdbc:mysql://")).append(src)
                    .toString();
            connessione = DriverManager.getConnection(jdbc, user, password);
            //HERE I EXTRACT THE PATH OF THE SCRIPT FROM THE FILE DB.CONF
            //AND THAN I GET THE NULLPOINTER
            String sqlScriptPath = br.readLine().toString();
            InputStream input2 = getClass().getResourceAsStream(sqlScriptPath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(input2));
            ScriptRunner sr = new ScriptRunner(connessione, false, false);
            sr.runScript(reader);

            JOptionPane
                    .showMessageDialog(null, "Installazione completata!");
        } else {
            if (e.getErrorCode() == 1045) {
                JOptionPane
                        .showMessageDialog(
                                null,
                                "Username o password del DB errati! \n Controllare il file di configurazione e riprovare.");
            } else {
                JOptionPane
                        .showMessageDialog(
                                null,
                                "Errore nella connessione al database! \n       Contattare l'amministratore di sistema.\nIl sistema verrà chiuso ora.");
            }
        }
    }
    br.close();
    input.close();
    connection = true;
    return connection;
  }

 protected boolean close() throws SQLException {
    boolean chiuso = false;
    connessione.close();
    chiuso = true;
    return chiuso;
}

}

This is the content of the DB.conf file

localhost:3306
CarLoan
root
root
CarLoan.sql

How to read from a file in my application on android?

I created a file on my pc, and I want my app to read from it.

How do I read from that file in my app?

Thanks

adding txt files on installation android apps

I'm writing an app, and I would like to save to External Storage a few txt files, once the app is installed.

Not on the onCreate of the main activity or anything like that, Just saving the files once to the External storage when the app gets installed on the phone. Is that possible?

Thanks

android read text file so slow

I'm programming an android application. In my application I use FileInputStream to read a text file, which is less than 100 kb in size, and showing its content in the application. The main problem is that although the file is not so big it takes around 3-4 seconds for my device to open the file. Considering the fact the my device has 1gb ram and a four-core CPU I want to know what's wrong with the way I read the text file and is there any better way to make the process faster???

String aBuffer = "";
    try {
        File myFile = new File(input);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(
                fIn));
        String aDataRow = "";

        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow + "\n";
        }
        // Toast.makeText(getBaseContext(), aBuffer,
        // Toast.LENGTH_SHORT).show();
        myReader.close();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
                .show();
    }

    return aBuffer;

How can I upload file on nodejs server with Java? (REST API)

Here's my java code to upload file to nodejs server.

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
    public static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost("http://127.0.0.1/upload");
        File file = new File("/Users/KHC/test.txt");

        MultipartEntity mpEntity = new MultipartEntity();

        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("userfile", cbFile);



        httppost.setEntity(mpEntity);
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        }if (resEntity != null) {
            resEntity.consumeContent();
        }

        httpclient.getConnectionManager().shutdown();
    }
}

And this is nodejs code. I am using express framework on nodejs server.

var fs = require('fs');


module.exports = function(app) {


app.get('/',function(req,res){
    res.end("Node-File-Upload");

});
app.post('/upload', function(req, res) {
    console.log(req.files);
    //console.log(req.files.userfile.originalFilename);
    //console.log(req.files.userfile.path);
    fs.readFile(req.files.userfile.path, function (err, data){
    var dirname = "/workspace/museek-server";
    var newPath = dirname + "/uploads/" +   req.files.image.originalFilename;
    fs.writeFile(newPath, data, function (err) {
    if(err){
    res.json({'response':"Error"});
    }else {
    res.json({'response':"Saved"});
}
});
});
});
};

When I execute java code, the nodejs server cannot read req.files because req.files is undefined. I think there is another way to read multipart file.. But I cannot find it on the Internet. Can anyone give answer for this?

How do I format an inputted file in C

Basically I have written a code in C to read a file inputted by the user and it will print this out when running. However, I am trying to get some help on how I can format the text. For example if the text file contained :

my cat has a huge stomach
maybe because 
she is pregnant 
or just fat.  

I want to format this text so that it outputs the line that can contain 60 characters, and if the word cannot fit into that 60 character line it should start on a new line like so:

my cat has a huge stomach maybe because she is pregnant or 
just fat.

.

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


int main()
{
char ch, file_name[25];
FILE *fp;

printf("Enter the name of file you wish to see\n");
gets(file_name);

fp = fopen(file_name,"r"); // read mode

if( fp == NULL )
{
  perror("Error while opening the file.\n");
  exit(EXIT_FAILURE);
}

printf("The contents of %s file are :\n", file_name);

while( ( ch = fgetc(fp) ) != EOF )
  printf("%c",ch);

fclose(fp);
return 0;
}

Also I heard that you shouldn't really use "gets" to retrieve a file. Similarly, I'm not necessarily saying someone should write the code for me, any advice or websites that can help me out would be appreciated.

os.path.getsize unable to get size of subdirectories

I tried to make a script which will move all subdirectories if they are smaller than 400mb. I wrote this piece of code :

import os
import string
import re
import sys
import glob
import fileinput
import shutil

src = raw_input("Enter source disk location: ")
src = os.path.dirname(src) 
for dir,_,_ in os.walk(src): 
file_path = glob.glob(os.path.join(dir,"*.txt")) 
for file in file_path: 
    f = open(file, 'r')
    object_name = f.readlines()
    f.close()
part = os.path.dirname(os.path.dirname(file)) 
    part_file1 = os.path.basename(part)
    part_file2 = os.path.split(part)[0] 
    part_file3 = os.path.split(part)[1]
    source = os.path.join(part_file2, part_file3)
    path_small = os.path.join(part_file2, "small")
    file_source = glob.glob(os.path.join(source,dir))
    for element in file_source: 

        final_file_source = element
        #print "element", element
    if not os.path.exists(path_small):
        os.makedirs(path_small)
    print"element", element
    try:
        print (os.path.getsize(element))
    except Exeption, e:
        print str(e)
        pass

    if os.path.getsize(element) > 4000: #problem start here 
    # do sth 
    else:
        shutil.move(element,path_small)

The problem is that os.path.getsize give me a size of the file that describes that directory. How to get a size of sub-directories ? I checked on other answers and i found this example os.path.getsize Returns Incorrect Value? but i dont know how to aplly this on my code. :(

How to open a .p file with fopen in Matlab

I have an third-party file with the extension .p and I try if it is possible to open it using the function fopen:

fopen(title.p)

This returns 3, which is a file identifier according to the help function:

help fopen

fopen - Open file, or obtain information about open files

This MATLAB function opens the file, filename, for binary read access, and returns an integer file identifier equal to or greater than 3.

What should I do to see (if possible) the content of the file?

Getting specified path does not exist while it is exist

Something weird is happening, I can see the file and its size but when try to open it I get this crazy error that it is not exist and try again!

Storing a file object in application cache using javascript

<input type="file" onchange="angular.element(this).scope().file_changed(this)">

I want to give user the ability to rename a file one has selected. Input type 'file' provides a file object, but the path of the file object is not one of the properties. Also, changing properties of this file is not permitted. (Ref. a lot of answers on stackoverflow)

"{"webkitRelativePath":"","lastModified":1446544642000,"lastModifiedDate":"2015-11-03T09:57:22.000Z","name":"pdf-sample.pdf","type":"application/pdf","size":7945}"

But it is achievable with files chosen using some plugins e.g. camera or image-picker. And I think the trick lies in : copying the file to application cache and then edit properties.

I would like to know how can I copy a file to application cache if I don't have it's path (preferably using core plugins). I'm also open to any better approach.

Thanks for your help!

File sharing on android device

I am doing an application with android studio. I want the user to be able to put files in my app and the access it when using my app.

Something like itunes with apple devices but for an android device. to be more clear I was using this with apple:

    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsDirectory = [paths objectAtIndex:0];
    pathe = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];

I don't know where and how the user put files and how to access it in my code. Is this possible? Is Android File Transfer doing it?

Playing PCM audio files during a live call in android such that other end can listen it

I am trying to play a predefined audio file from my application when a incoming or outing call occurs such that the other end can hear this. I know this is not possible using android API but what is the other way to achieve this. I already rooted a device and trying to find a solution to achieve this but no luck. Any help on this will be greatly appreciated.

What is role of effective and real user or group id in perl language?

In perl language when talking about special cases of filehandling File Test= -r,-w,-x are READ,WRITE AND EXECUTE options for effective user File Test= -R,-W,-X are READ,WRITE AND EXECUTE options for real user. Where does the concept of real user and effective user imply in perl?

Show/delete individual file in dialog box from multiple input file jquery

DEMO

I want to show/delete individual files in a dialog box.

In my demo user can add multiple files in the input type file then after clicking upload the information of the files are appended in the table. I want to show the file in a dialog box, or delete/remove it from the input file. In the table user can see view/delete when the user click on view the that file should show in the dialog box when user click delete that file should be removed from the input file.

any idea is appreciated.

P.S.

I didn't use the snippet here in SO because I don't know how to add external file

JS

var div = $("<div id='showfile'>");
$("body").prepend(div);
$("#showfile").dialog({
    autoOpen: false,
    resizable: false,
    modal: true,
    //title: "Modal",
    height: 800,
    width: 800,
    buttons: {
        "Close": function () {
            $(this).dialog('close');
        }
        //    "No": function () {
        //    $(this).dialog('close');
        //}
    }
});
$('#add').click(function (e) {
    e.preventDefault();
    var file = $('#file')[0].files;

    $("#table").find("tr:gt(0)").remove();
    for (var i = 0; i < file.length; i++) {
        var id = Math.random();
        var newRow = "<tr>" +
            "<td id='' name='nameoffile'>" + file[i].name + "</td>" +
            "<td id='' name='size'>" + file[i].size + "</td>" +
            "<td id='' name='type'>" + file[i].type + "</td>" +
            "<td>" + "<a href='#' id='" + id + "' class='view'>View</a>" + "/" + "<a href='#' id='" + id + "' class='delete'>Delete</a>" + "</td>" +
            "</tr>";
        $("#table > tbody > tr:last").after(newRow);
    }
});
$('#file').change(function () {
    console.log($('#showfile').files);
})
$(document).on('click', '.view', function (e) {
    e.preventDefault();
    e.stopPropagation();
    readURL($('#file').files);
    console.log($('#file'))
});


function readURL(input) {
    console.log(input);
    $("#showfile").dialog({
        title: "Show File"
    });


    for (var i = 0; i < input.files.length; i++) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                //$('#blah').attr('src', e.target.result);
                $('#showfile').append('<img src=' + e.target.result + ' />')

            };


            reader.readAsDataURL(input.files[i]);
        }

    }
    $("#showfile").dialog("open");
}

html

<input type="file" id="file" name="" multiple/>
<input type="button" value="Upload " id="add" id="" />
<table id="table" class="">
    <tr id="">
        <th>Name of File</th>
        <th>Size</th>
        <th>Type</th>
        <th>Action</th>
    </tr>
</table>

PHP Uploading Module restricts filesize > 2 KB

I have my Upload File page written in HTML/PHP. The file's content gets stored in a Blob column of an Oracle table. The problem is that it only uploads file that is less than 2 KB and not the greator ones. The code is:

HTML:

Please specify your file: 

<input type="file" name="datafile" id = "datafile"/>
<br></br>
<input type="submit" id = "save" name = "save" value="Upload"/>

PHP:

if(isset($_POST['save']) && $_FILES['datafile']['size'] > 0)
{
$fileName = $_FILES['datafile']['name'];
$fileSize = $_FILES['datafile']['size'];
$tmpName  = $_FILES['datafile']['tmp_name'];
$fileType = $_FILES['datafile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp); 
$conn = OCILOGON("myDB","myDB","MYSERVER");
$qry = "INSERT INTO FilesTable (date_input,file_name,File_CONTENT) VALUES (SYSDATE,'$fileName',utl_raw.cast_to_raw('$content'))";


$stmt = OCIparse($conn,$qry);
ociexecute($stmt);

$result = oci_num_rows($stmt);

Problem:

Code only works for FileSize < 2 KB. Although I have upload_max_filesize = 2M in my phpinfo();

change the behaviour of browse button

Assume that you have a html page with browse button if you click the browse button it ll open folder in your computer or laptop right from their you can select the file what you want to upload but what my question is instead of opening a folder in our computer/laptop it ll open cloud server like one drive, google drive, etc., from their i want to select the files and upload it to my computer/laptop how to do that, actually i did some research about this but i didn't get any worthy website to learn about this.

Java - Reading in salaries and getting total

So basically I'm reading in some salaries from a text file and then printing them out with a "while" loop, and then I'm adding them together with another "while" loop.

My problem is that when running the code, I get the salaries read out into the console, but I don't the total salary from the second "while" loop.

The code looks like this -

package Week15;
import java.util.*;
import java.io.*;

public class h {
    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(new File("salaries.txt"));
        double items = 0;
        double total = 0;
        double salaries;

        while (scan.hasNext()){
            salaries = scan.nextDouble();
            System.out.println(salaries);
        }   

        while (scan.hasNextDouble()) {
            // add the next salary to the total
            total += scan.nextDouble();
            // increase the number of encountered salaries by 1
            items++;
        }
        double salary = total+items;
        System.out.println("Total salary = " + salary);

        scan.close();
    }
}

The console looks like this -

14390.75
12345.99
27512.08

Here is the what the "salaries.txt" file I'm using looks like -

14390.75
12345.99
27512.08

Looking for the activity generator in file system (under OS X)

I need to test a file system monitor. We need some kind of simulator activity on the file system. For example, to be able to specify a folder, type of operation, max/min file size, etc. After starting the generator should start creating folders, write to the files, delete files, change files, etc. After completion it is desirable to report on its activities. Thus I will be able to compare the results of both programs and to understand the monitor of file system correctly works.

We need a generator for OS X. But the interesting programs, and for other operating systems.

Call a PHP on the same file

I have a question: is there a way to call a php query from the same file?

Here is my code :

<?php 
function aggiungiPagine(){

    global $conn;

    header('Access-Control-Allow-Origin: *');

    $nomePagina = $_POST['nomePagina'];
    $descrizionePagina = $_POST['descrizione'];

    $comando = "select * from Pagine where Nome='$nomePagina'";

    $query = mysqli_query($conn, $comando); //trova tutti i risultati con quelle carateristiche
    $raws = mysqli_num_rows($query); //individua il numero di record trovati ed inseriti nella matrice $query

    if($raws == 0){ // controllo che non sia stato trovato l'utente
        $comando = "INSERT INTO Pagine (ID_Pagina,Tipo,Nome,Descrizione,Contenuto) VALUES (NULL,'Principale','$nomePagina','$descrizionePagina','')";
        $result=mysqli_query($conn, $comando)or die(mysqli_error());
        $error ="pagina inserita";
    }
    else{
        $error="Pagina con lo stesso nome gia trovata";
    }
    mysqli_close($conn); //chiudo la connessione col db
} ?>

and the js script in the same file :

<script>
$(document).on('click', "#btnAggPagPrinc", function(event) {
     $.post(aggiungiPagine(), $("#aggPagPrinc :input").serializeArray(), function(info){
        tappoOverlay();
        caricaPagPrinc();
    });
});

I use jQuery to post the data.

Sorry for bad English, I'm Italian

Save URL to Blob and Blob to hard disk

Using HTML5/ JavaScript, is their an oppertunity to save a browser-URL to a blob and next to save that blob with the pointer of the URL on hard disk.

So after that it should be able to open the file and thereby the embedded URL?!.

Or somebody know maybe a better way to implement?

thanking you in anticipation

Delete temporary locked files

At some point of my process i have to delete a specific file, because the file is used as "flag" that something was corrupted (Part of a Backup Logic).

Sometimes the file is locked by a virus scanner or anything else, but this lock is temporary. In any case the specific file has to be deleted, otherwise the next process may be broken. I also thought about creating a second file flag that the first flag is corrupt, but in the end you could create hundreds of flags, so this is not a solution.

I tried to delete the file wihtin a loop and keep waiting for some millis, before trying to fire the next delete command.

    for (int i = 0; i < 10; i++) {
        if (FileUtils.deleteQuietly(file)) {
            break;
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            break;
        }
    }

  1. Do you see a Utility class out there this scenario is already implemented?
  2. How do you handle create/delete commands if a virus scanner is locking you files?

Doxygen not updating comments for duplicate files

I am using doxygen to provide comments to some .c and .h files (file level comments only). There are some files which are duplicated (same name) and are present in different subfolders. So, when I provide comments for these files, doxygen is not updating it in the generated html file.

I read doxygen command description provided at below link and tried providing the path for such files to make them unique but that also not working.

http://ift.tt/1ksbivf

The options I tried till now are as below. Consider, Nm.h is the file having multiple copies:

1. /*! \file Nm.h * \brief Header file */ 2. /*! \file \sgdcc\checkdrive\test\Nm.h * \brief Header file */ 3. /*! \file sgdcc\checkdrive\test\Nm.h * \brief Header file */

Comments are not getting updated even for a single file. I tried providing short path as well as full path but nothing is working.

I am compliling doxygen through ClearCase and the doxygen version used in it is 1.8.2

Please help me in resolving this issue.

SharePoint 2013 File Performance

Anyone know the file performance and fast site collection creation for SharePoint 2013?

Kindly thanks for your help.

Splitting a text file where the information are separated in different lines

So, I have a text file where the information are separated by the enter key (I don't know how to explain, I will paste the code and some stuff).

cha-cha
Fruzsina
Ede
salsa
Szilvia
Imre

Here's how the text file looks like, and I need to split it into three parts, the first being the type of the dance, and then dancer 1 and dancer 2.

using System;
using System.Collections.Generic;
using System.IO;

namespace tanciskola
{
    struct tanc
    {
        public string tancnev;
        public string tancos1;
        public string tancos2;
    }
    class Program
    {

        static void Main(string[] args)
        {
            #region 1.feladat
            StreamReader sr = new StreamReader("tancrend.txt");
            tanc[] tanc = new tanc[140];
            string[] elv;
            int i = 0;
            while (sr.Peek() != 0)
            {
                elv = sr.ReadLine().Split('I don't know what goes here');
                tanc[i].tancnev = elv[0];
                tanc[i].tancos1 = elv[1];
                tanc[i].tancos2 = elv[2];
                i++;
            }
            #endregion
            Console.ReadKey();
        }
    }
}

Here is how I tried to solve it, although I don't really get how I should do it. The task is would be to display the first dance and the last dance, but for that I need to split it somehow.

Pick a random line from text file in C++

I'm trying to read a random line from a text file.

My code so far picks the first line, but I need a random line.

How would I get a random line?

string line;
if(infile.good()){
    getline(infile, line);
}

reading txt files in Persian language in android

I'm coding an application in which I import some text files. when I try to import txt files in Persian language into my app I see that the imported files are not understandable. like text in below:

.æÞÊí Çæä ÞÓãÊ Ñæ ãíþÎæäí Èå ãä äÇå ä˜ä

In fact I want to know how to convert my imported text to unicode to be understandable in my app.

why I can not permanently remove a file from linux?

Today,I encounter a very tough problem which cost me nearly 6 hours.

When I remove a file called ha_wan.conf using rm -rf ha_wan.conf command under /etc directory,Success.When I use ls -al command to see the result,The file disappear.

But when I reboot the linux system,same file named ha_wan.conf come back,located under /etc/ directory.

I tried to delete it many many times,It is the same result.

What should I do,I want to permanently remove that file.Thanks.

How to know which files were pulled by AJAX

Is there a way to detect which local file was pulled by a AJAX request, i.e. pulled by JQuery? Can a listener detect the pulling? Can this work without a server?

mercredi 4 novembre 2015

Android Gallery shows thumbnail even after file is deleted

In my app I am using DownloadManager to download video files from internet and store them in a directory (getExternalStorageDirectory()+"/myvideos").When file is downloaded it is shown automatically in Gallery app. When user select delete option in app for any video I delete file like this

File fd=new File(fileFullPath);
if (fd.exists()){
    fd.delete(); //this returns true and file is deleted
}

It is confirmed that file is deleted from storage because on traversing the root directory again the file is not present.

But the issue is that Gallery app still shows the thumbnail of video after it is deleted and when tap on that thumbnail it shows black screen with broken thumbnail in middle. I have tried several methods mentioned on stackoverflow and on other internet resources but none seems to work...thumbnail still shows

Saving a application/octet-stream to disk from javascript in IE9

I provide a method on my WebApi to download a file:

public HttpResponseMessage Get(int id)
    {
            MemoryStream file = RetrieveFile(id);
            if (file != null)
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(file);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "dummy.txt"
                };

                return response;
            }


        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }

This works fine and i can consume it with a WebClient.

I also tied to implement the javascript front-end using FileSaver.js :

$http({
            url: myUrl,
            method: 'GET',
            params: {
                id: 1
            },
            headers: {
                'Content-type': 'application/json'
            }
        }).success(function (data, status, headers, config) {
            var file = new Blob([data], {
                type: 'application/octet-stream'
            });
            saveAs(file, "test.txt");

        }).error(function (data, status, headers, config) {

        });

This works great but it fails on IE9 since FileSaver and Blop is not supported. I have tried opening the url in a new window but can't find a decent working solution for IE9

What is Php's equivalent of Java's newInputStreamSupplier?

I have been trying to implement a functionality that is written in Java, for uploading a file via PUT HTTP request.

Here is my sample Java code:

import com.google.common.io.Files;

public void uploadFile() {
        final makeRestRequest makeUploadRequest = makeRequestTo(upload_file_location)
                .method("PUT")
                .addHeader(new HttpHeader("Accept", "application/json"))
                .addHeader(new HttpHeader("Content-Type", "application/zip"))
                .body(Files.newInputStreamSupplier(new java.io.File("/sample_file.zip")))
                .build();

        final getRestResponse uploadResponse = makeUploadRequest.fetchResponse();
}

I am looking for a similar variant of the php code, that can make a HTTP PUT call to upload a file, but i am not sure what to use for the newInputStreamSupplier. Here is my sample php code, that makes a PUT call to upload file using CURL, but fails to get a response:

<?php
$url = upload_file_location; 
$localfile = "sample_file.zip";

$fp = fopen ($localfile, "rb"); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_PUT, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$headers = array();
$headers[] = 'Content-Type: application/zip';
$headers[] = 'Accept: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_INFILE, $fp); 
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile)); 
$http_result = curl_exec($ch);
?>

I get an error saying: "File content is empty". Does anyone have an idea of what i am doing wrong?

Is it possible to set file permission according to the user privilege? If yes how?

I want to set a file permission according to user privilege level (like Administrator, Operator, User, etc.,). I want to assign root permissions to user's that who have administrator privilege. If possible how to set. Thanks in advance.

Concantenate user input Strings to convert into a complete file path (Java)

I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:

    import java.io.*;
    import java.util.Scanner;
public class FilePractice {
  public static void main(String[] args) {

    //create a new File object
    File myFile = new File("/home/christopher/Desktop/myFile");

    try{
        System.out.println("Would you like to create a new file? Y or N: ");
        Scanner input = new Scanner(System.in);
        String choice = input.nextLine();
        if(choice.equalsIgnoreCase("Y"))
        {
            myFile.createNewFile();
        }
        else
        {
            //do nothing
        }
    }catch(IOException e) {
        System.out.println("Error while creating file " + e);
    }
    System.out.println("'myFile' " + myFile.getPath() + " created.");
  }
}

I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.

Perhaps my syntax is wrong?

If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).

Here is the expanded attempt:

try {
       System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
            String fileName = input.nextLine();
            input.nextLine();
            System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
            String userFilePath = input.nextLine();
            File userFile = new File(userFilePath, fileName);
            System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
            String userChoice = input.nextLine();

            if (userChoice.equalsIgnoreCase("Y")) {
                userFile.createNewFile();
                //print for debug 
                System.out.println(userFile.getPath());
               }
            }catch(IOException e) {
                System.out.println("Error while attempting to create file " + e);
            }
            System.out.println("File created successfully");

My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.

Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.

Array Index out of bounds for Java using terminal

I am having trouble with a ticketing system that I am trying to create using java. I am trying to utilize two files to read and write my inputs. I am testing with just salesSell method at the moment. I am passing the args using terminal. The problem that I am having is an arrayoutofbounds exception that gets thrown. the two array parameters that I am passing are parsed from the same line in my current events file. an example of a line in the file is : "testevent1__________0003". I cannot seem to figure out where I am having this problem. Any type of guidance would be much appreciated.

package cisc_327_frontend;
import java.io.*;
import java.util.*;

public class Frontend_try1 {

private static File fileOutput;
private static List<StringBuilder> eventTrans = new ArrayList<>();


public static void consoleInput(String[] namesArray, int[] ticketArray,File fileCurrentEvents){
    System.out.println("Enter command:");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();


    boolean correct = true;

        do{

            if(inputString.toUpperCase().equals( "LOGIN")) {
                //enter login mode
                login(namesArray, ticketArray,fileCurrentEvents);
                correct = true;

                }
            if(inputString.toUpperCase().equals("LOGOUT")){
                logout(namesArray, ticketArray,fileCurrentEvents);
                correct=true;
            }
                if (!"LOGIN".toUpperCase().equals(inputString) || !"LOGOUT".toUpperCase().equals(inputString)){
                    System.out.println("Incorrect command, please enter command:");
                    input = new Scanner(System.in);
                    inputString = input.nextLine();
                    correct = false;
                }

        }while(!correct);



    }

public static void login(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    System.out.println("Sales or Admin?");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();


    boolean correct = true ;

    do {
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout(null, null, null);

        }
        else if(inputString.toUpperCase().equals("SALES")) {
            //enter sales mode
            sales(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("ADMIN")) {
            //enter admin mode
            admin(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("LOGOUT")) {
            //enter logout mode
            logout( namesArray, ticketArray, fileCurrentEvents);
            correct = true;
        } else  {
            //ask again
            System.out.println("Invalid Input");
            System.out.println("Sales or Admin?");
            input = new Scanner(System.in);
            inputString = input.nextLine();
            correct = false;
        }

    }while(!correct);

}

public static void sales(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    //System.out.println("SALES");
    System.out.println("Sales Mode");
    System.out.println("Enter Command:");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();


    boolean correct = true ;

    do {
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout( namesArray, ticketArray, fileCurrentEvents);

        }
        else if(inputString.toUpperCase().equals("SELL")) {
            //enter sales Sell mode
            salesSell(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("RETURN")) {
            //enter sales Return mode
            salesReturn(namesArray, ticketArray,fileCurrentEvents);
            correct = true;
        } else if (inputString.toUpperCase().equals("LOGOUT")) {
            //enter Logout mode
            logout( namesArray, ticketArray, fileCurrentEvents);
            correct = true;
        } else {
            //ask again
            System.out.println("Invalid Input");
            System.out.println("Enter Command:");
            input = new Scanner(System.in);
            inputString = input.nextLine();
            correct = false;
        }

    }while(!correct);



}


public static void salesSell(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    int index = 0;
    String eventName = null;
    int numberTickets = 0;
    System.out.println("Sales Sell Mode");

    System.out.println("What is the name of your event?");
    Scanner input = new Scanner(System.in);
    String inputString = input.nextLine();

    if(inputString.toUpperCase().equals("LOGOUT")){
        logout( namesArray, ticketArray, fileCurrentEvents);

    }

    try{

        for(int i = 0; i < namesArray.length; i++) {
            if(namesArray[i].equals(inputString)){
                index = i;
            }
        }
         eventName= namesArray[index];
          numberTickets=ticketArray[index] ;

    } catch (Exception e) {
        System.out.println("Error: Event not found within file");
        System.exit(1);
    }

    int event = inputString.length();
    boolean charnumber = true;

    do{
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout( namesArray, ticketArray, fileCurrentEvents);

        }
    if(event< 0 || event >20){

        System.out.println("No more than 20 characters allowed for name!");
        System.out.println("Enter name:");
        input = new Scanner(System.in);
        inputString = input.nextLine();
        event=inputString.length();
        charnumber = false;
    }
    else{
        charnumber = true;

    }

    } while(!charnumber);


    System.out.println("How many tickets?");
    input = new Scanner(System.in);
    inputString = input.nextLine();
    int digit;


    while(true){
    try {
        digit = Integer.parseInt(inputString);

    break;
    }
    catch(NumberFormatException e){


    }


    System.out.println("Please type a number!");    
    inputString = input.nextLine(); 
    }

if( numberTickets - digit <0){
    System.out.println("Illegal amount of tickets! Buy less ticket please.");

}
else{
    int tickets = numberTickets - digit;

    ticketArray[index]=tickets;


}
    boolean dignumber = true;

    do{
        if(inputString.toUpperCase().equals("LOGOUT")){
            logout( namesArray, ticketArray, fileCurrentEvents);

        }
    if(digit<0 || digit>8){

        System.out.println("Only 8 tickets allowed to be sold!");
        inputString = input.nextLine();
        event=inputString.length();

        dignumber = false;
        digit= Integer.parseInt(inputString);
    }
    else{
        dignumber= true;

    }
    }while(!dignumber);

}




public static boolean logout(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
    FileWriter logoutFileWriter;
    FileWriter currEventsFileWriter;
    int numSpaces = 0;

    try{
        currEventsFileWriter = new FileWriter(fileCurrentEvents, true);

            for(int i = 0; i < namesArray.length; i++ ) {
                currEventsFileWriter.write(namesArray[i]);
                numSpaces = 20 - (namesArray[i].length() + 4);
                for(int j = 0; j < numSpaces; j++) {
                    currEventsFileWriter.write("_");
                }
                currEventsFileWriter.write(ticketArray[i]);
                currEventsFileWriter.write(String.format("%n"));
            }       

    } catch(IOException e) {
        System.out.println("Rewriting Current Events File Error");
        System.exit(1);
    }

    try {
        logoutFileWriter = new FileWriter(fileOutput, true);

        //Cycle through event trans file and write via filewriter
        for(int i = 0; i < eventTrans.size(); i++ ) {
            String transact = eventTrans.get(i).toString();
            logoutFileWriter.write(transact);
            logoutFileWriter.write(String.format("%n"));
        }
        // Signify end of file
        logoutFileWriter.write("00                       000000 00000");
        logoutFileWriter.write(String.format("%n"));
        logoutFileWriter.close();
        fileOutput.createNewFile();

    } catch(IOException e) {
        System.out.println("Output File Error");
        System.exit(1);
    }
    return true;

    /*
    for( int i = 0; i < 20; i++ ) {
        System.out.println("");
    }
    System.out.println("Logged Out");
    consoleInput();
*/
}



public static void main(String[] args){

    try {
        File fileCurrentEvents = new File(args[0]);
        fileOutput = new File(args[1]);

        // Read current events file for events & dates
        FileReader fileRead = new FileReader(fileCurrentEvents);
        BufferedReader buffRead = new BufferedReader(fileRead);

        // Create strings for data in current events file
        String currentLine;
        String eventName;
        Integer numberTickets;
        List<Integer> numticket = new ArrayList<Integer>();
        List<String> list = new ArrayList<String>();
        int[] numarray= new int[numticket.size()];
        String[] linesArray = list.toArray(new String[list.size()]);
        // Cycle through current events file line by line
        while((currentLine = buffRead.readLine()) != null) {
            if (currentLine.equals("END_________________00000")){
                break; // End of file
            }

            //Parse for event name & number of tickets
            eventName = currentLine.substring(0, currentLine.lastIndexOf("_")).trim();
            numberTickets = Integer.parseInt(currentLine.substring(currentLine.lastIndexOf
                    ("_") + 1));



            // Place event name and # tickets into data structure
            // Add event name to event array list with same index as # tickets
            // Parse int to get # tickets & add to arraylist for tickets with same index


             while((eventName = buffRead.readLine()) != null){
                   list.add(eventName);
                }


                for (int i =0 ; i< list.size();i++){

                    linesArray[i]= list.get(i);

                }




                 while((eventName = buffRead.readLine()) != null){
                       numticket.add(numberTickets);
                    }


                    for (int i =0 ; i< numticket.size();i++){

                        numarray[i]= numticket.get(i);

                    }

        }

        while(true) {
            consoleInput(linesArray, numarray, fileCurrentEvents);
        }
    } catch (IOException e) {
        System.out.println("File I/O Error"); //Print to console to signify error
        e.printStackTrace();
        System.exit(1);
    }



}

}

I Can't print out a file that I wrote on

I have created a function to write some data on a text file, and it works fine. I created another function to read in all the content of the file, and print it out for me! But, it is not working for some reason. Could any one help please?

This is my function:

void myClass::displayFile() {
  char line[LINE]; //to hold the current line

  file.open("data.txt", ios::app);

  //keep reading information from the file while the file is open and has data
  while (!file.fail() && !file.eof()) {
    int lineSize; //to loope through each line

    file.getline(line, MAX_SIZE);
    lineSize = strlen(line);

    //loop through the line to print it without delimiters
    for (int i = 0; i < lineSize; ++i) {
      if (line[i] == ';') {
        cout << " || ";
      } else {
        cout << line[i];
      }
    }
  }
  file.close();
  file.clear();

  if (file.fail()) {
    cerr << "Something went wrong with the file!";
  }
}

Note: The function compiles and the loop is accessible, but the line string is empty.

This is the writing function:

void myClass::fileWriter() {
  file.open("talent.txt", ios::app);
  file << name << ";" << age << ";" << "\n";
  file.close();
  file.clear();
}

File Descriptors and File Handles (and C)

Can someone explain to me precisely the difference between a file descriptor and a file handle (separate from Windows' definition for the term; I'm curious about their definition, but that would require a much longer answer)?

From what I have gathered from Wikipedia, a file descriptor is an index in a file descriptor table, which points to a file name in a file table, which in turn points to an inode in an inode table. File handle is a type of data structure that stores a file descriptor.

  • Is a file descriptor simply an index in the file descriptor table (i.e., the index value simply is the file descriptor)?
  • Or does the file descriptor table element, identified by its index, store the file descriptor (making them likely two different numbers, assuming the index is a number)?
  • Is "file handle" simply a term for the FILE data structure in C which stores file descriptors? Or does file handle refer to some other data structure, which stores a file descriptor, separate from the C data structure (FILE)? What else can anyone tell me about the nature of file handle data structures?

Why cant I change the the file extension of a desired file in java?

I cant understand why my code refuses to change the file extension of my txt file to java.

Here's my code:

public static void main(String[] arg) {

 File file  = new File("file.txt"); //File I want to change to .java
 File file2 = new File("file.java"); 

 boolean success = file.renameTo(file2); //boolean to check if successful


 if (success == true)
 {
     System.out.println("file extension change successful");

 }else
 {
     System.out.println("File extension change failed");
 }

}// main

It always prints "file extension failed" each time and I honestly do not understand why. I'm starting to suspect it might be the permissions on my computer. The compiler I use is Eclipse.

Looking fo jquery plugin in for sliding pdf file

I am looking for code js,jquery for slider pdf file from top page to end page.It take me 2 days but I doesn't find nay solution.Thank you

append every 8 lines of a file to a new file conditionally

I have a file with a set of lines in it. Every 8 lines contains a sample that I need to test with an 'if' statement. If the 8 lines is accepted I need it to send that text to an 'accepted file'- 'else' the 8 lines are sent to another 'notaccepted file': for line in range(0,len(outfile),8):#outfile=variable storing file lines if avergm or avergt <30: not_accepted=open("unacceptable.txt", "a") not_accepted.append(outfile[0:7]) else:
accepted=open("accepted_samples.txt", "a") accepted.append(oufile[0:7]) My problem is that with the 'accepted.append(oufile[0:7])' only the first 8 lines are appended to the 'accepted/notaccepted file' and I need this to iterate through all of the 8 line entities in 'outfile' and append them in accordingly. Any help?

Checking User Input Against List Python 3.x

I have to take numbers from a text file, put them in a list, and ask the user for a number and tell them whether it's in the list or not.

this is what I have:

#read numbers to list
infile = open('charge_accounts.txt','r')
lines = infile.read().strip()
list1 = [lines]
infile.close()

#ask user for #
inp = str(input('Enter an account number: '))

#determine if input is in list
#display invalid/valid
if inp in list1:
    print('valid number')
else:
    while inp not in list1:
        print('invalid entry')
        inp = input('try another number: ')
        if inp in list1:
            print('valid number')
             break

The problem is it thinks all inputs are invalid. I assume I either messed up converting the file to a list or with the while loop but I don't know what to fix.

How can one count randomly white-spaced delimited values from a file in Fortran?

If one has a file containing, for example:

1 2 3   4    5
6  7  8  9  10
   11    12   13
14 15
16             17
        18
  19  20

How can one get the correct number of integers (in the given example, 20) from counting them in the file in Fortran?

Reading numbers from file and normalizing

Hello Everyone, I want to load the data I have in a file, which looks like:

21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1,............... 

Now, I want to load this from the file and compute the normalization. I do:

f = open("Input.txt", "r") 
data = [line.strip() for line in f]
print data
norm = [float(i)/sum(data) for i in data]
print norm

But, I am getting the error:

ValueError: invalid literal for float()

Although, I do the process directly into python 2.7 console in linux like,

a = [21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1]
norm = [float(i)/sum(a) for i in a]
print norm

This works fine. I don't know what I am doing wrong. Please help me and I am new to programming. Thanks in advance!

C++ - A library that allows easy importing of text files into classes?

Say I want to have 100 classes, and I want their data to be stored in a file. This might be what the class looks like:

class MyClass
{
    std::string name;
    std::vector<std::string> friends;
};

Is there a library that can be used to easily create and read these files without creating your own format/syntax? What I'm really looking for is a library that will, for example, automatically parse the first line as the 'name', then everything between the next two braces as 'friends', and repeat that.

I know it's quite trivial to program, but if I had 10 different types of class I would like an easier way than to manually create and parse 10 different formats.

Thanks

Generate file new to jar

I have a jar with my application that should create a file next to it. So in folder I will have this :

Source 
 |_ MyApplication.jar
 |_ generatedFile.txt

Easy thing I thought... nope.. I am lost... I have a code like this:

URL location = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
        String path = location.getFile().substring(0, location.getFile().lastIndexOf("/MyContext"));
        File file = new File(fileName + ".txt");
        File file1 = new File(path + "/MyFileName.txt");
        File file2 = new File(path.substring(1) + "/MyFileName.txt");

I tried different combinations, googled alot and I am lost... if I get for example

file1.getPath();
file2.getAbsolutePath();

and so on, the paths are correct... but the file isn't generated... Only working case is the first one, but that is located inside the jar and I don't want that.

I also tried to moving the existing file outside using

Paths.move(...

but that hasn't helped me at all..

Can someone help me with this ? And explain to me why isn't the examples above working ? Thanks..

Deleting a particular file in php

I am practicing uploading and deleting files in php and I've encountered a problem.

I have this code:

if($files)
                {
                    foreach($files as $file)
                    {
                        echo '<a href="files_storage/'.$file.'" download>'.$file.'</a><br>';
                    }
                }
                else
                {
                    echo 'There are currently no files.';
                }

It displays all files from a directory. I want to add a delete button for every file. Something like this:

enter image description here

Should I create different form for every file? If I do so, how would I identify which file to be deleted when a form is submitted? Any suggestions?

IF statement evaluation while reading characters from textfile

Been looking everywhere but couldn't find a good example to fit my needs. Basically I have a textfile that has information with formatting commands.

Textfile:

 .sp 2
 .ce
 Textfile with information and formatting commands.

So this textfile has formatting commands such as ".sp 2" and ".ce".

Now I want the program to detect if a formatting command is in the textfile.

Code so far:

 int main(void) {
 FILE *f = fopen("textfile.txt", "r");
if(!f) {
printf("File not found.\n");
return 1;
}

char c;

int cCount = 0;

while((c = fgetc(f)) != EOF) {
if(c == '\r') continue;
if(c == '\n') c = ' ';

if(c == '.'){ //Now every formatting command starts with a .
  /*
  Need a way to evaluate the next character after "." To check if it's a 
  formatting command or a full stop.
 if(charafter(.)==c){ //pseudocode
 if(charafter(s)==e){
 //Do formatting command linked with ".ce"
 }
 }
  */

}

printf("%c",c);
if((cCount++ > 55) && (c == ' ')) {
  printf("\n");
  cCount = 0;
}
}

  fclose(f);
  return 0;


  }

So essential, what my goal is how to directly evaluate the next character.

I'm sorry if this is a silly question very new C programmer.

Splitting a `.bed` file based on chromosomes into `chromosomeName.bed` with perl

I am trying to use perl to split a .bed file into multiple ones based on chromosome. For example, my input file is example.bed:

chr1    12190   12227
chr1    12595   12721
chr2    876522  876688
chr2    887378  887521
...

And my ideal output is two .bed files:

chr1.bed

chr1    12190   12227
chr1    12595   12721

chr2.bed

chr2    876522  876688
chr2    887378  887521

I know using awk to do this is easier, but I am hoping to figure out how to do this using a perl script.

Trying to count words in a file using Python

I am attempting to count the number of 'difficult words' in a file, which requires me to count the number of letters in each word. For now, I am only trying to get single words, one at a time, from a file. I've written the following:

file = open('infile.txt', 'r+')
fileinput = file.read()

for line in fileinput:
    for word in line.split():
        print(word)

Output:

t
h
e

o
r
i
g
i
n

.
.
.

It seems to be printing one character at a time instead of one word at a time. I'd really like to know more about what is actually happening here. Any suggestions?

How can I plot different file in a single plot?

I'm working on R 3.1.1 GUI 1.65 Mavericks build (6784) and I would like to say that I have 3 textual files (file1, file2, file3) which exactly have these format:

-6.302229035036262 -20.0 -1.020941553137966 
-4.04318422254186 -3.583695163352756 -3.6530481033374245 
-2.077324334243253 -20.0 -20.0 
-6.302229035036262 -20.0 -1.020941553137966 
-6.4977283774856875 -10.964877298563136 -1.1022927689594357 
-6.291583374531307 -16.450926383021542 -1.176625625964833 
-6.223879288477839 -12.115100317368787 -1.5212364609954971 

The separator is a blank space, there are not neither column names nor row names, and what is crucial is that the last character is an other blank space separator (" "). Unfortunately the last separator of the row is unremovable since those files are previously generated by an external software.

Here are my steps: 1) I set my working directory where files are located

setwd(“working directory”)

2) I create a matrix from a file (Note that I'm using read.csv even if it has no extension even though it's readable from any kind of editor) I finally save it in a variable

data <- as.matrix(read.csv(“file1″, header=FALSE, sep=” “));

A new [Nx4] matrix is created where R interpret as:

            V1         V2         V3 V4
[1,] -6.302229 -20.000000  -1.020942 NA
[2,] -4.043184  -3.583695  -3.653048 NA
[3,] -2.077324 -20.000000 -20.000000 NA
[4,] -6.302229 -20.000000  -1.020942 NA
[5,] -6.497728 -10.964877  -1.102293 NA
[6,] -6.291583 -16.450926  -1.176626 NA
[7,] -6.223879 -12.115100  -1.521236 NA

The problem now is that I would like to have an Nx3 matrix instead of Nx4, and that problem is caused by the last blank separator. How can I tell R to interpret that the last character/separator should be removed? I would like to get something like this as a result:

            V1         V2         V3
[1,] -6.302229 -20.000000  -1.020942
[2,] -4.043184  -3.583695  -3.653048
[3,] -2.077324 -20.000000 -20.000000
[4,] -6.302229 -20.000000  -1.020942
[5,] -6.497728 -10.964877  -1.102293
[6,] -6.291583 -16.450926  -1.176626
[7,] -6.223879 -12.115100  -1.521236

At that time, I don't know how to plot it in order to change column name with for example: f1, f2 and f3.

Having done the plot, I would like to plot the other 2 files in the same plot, thus the final plot could contain 3 different output.

Thank you all for collaboration.

Fast and efficient way of writing an array of structs to a text file

I have a binary file. I am reading a block of data from that file into an array of structs using fread method. My struct looks like below.

struct Num {
    uint64_t key;
    uint64_t val
};

My main goal is to write the array into a different text file with space separated key and value pairs in each line as shown below.

Key1 Val1
Key2 Val2
Key3 Val3

I have written a simple function to do this.

Num *buffer = new Num[buffer_size];
// Read a block of data from the binary file into the buffer array.
ofstream out_file(OUT_FILE, ios::out);
for(size_t i=0; i<buffer_size; i++)
    out_file << buffer[i].key << ' ' << buffer[i].val << '\n';

The code works. But it's slow. One more approach would be to create the entire string first and write to file only once at the end.

But I want to know if there are any best ways to do this. I found some info about ostream_iterator. But I am not sure how it works.

Reading data from files from a user input

So I have a text file that I've made up with a persons name followed by a comma and then a place where they could live. Yes I know its random but I need a way to understand this :)

So here is the text file (called "namesAndPlaces.txt"):

Bob,Bangkok
Ellie,London
Anthony,Beijing
Michael,Boston
Fred,Texas
Alisha,California

So I want the user to be able to enter a name into the program and then the program looks at the text file to see where they live and then prints it out to the user.

How can I do this? Thanks Michael

How to pass a file to an .exe in console

i am currently learning C by reading "The C proggraming Language". I have issues with exercices that implies input and output with getchar()/putchar()/EOF. It seems that the programs made with the exercies are supposed to be used on files. But once i have my .exe i only know how to start the "raw" .exe, i would like to do something like: myProgram.exe file.txt This way the program could read the file as input. Unfortunatly the way i try to do this doesn't work, could you tell me how to do this properly?

Program i want to use on a file:

#include <stdio.h>

main()
{
    int c;
    while((c = getchar()) != EOF)
    {
         putchar(c);
    }
}

python code to append after a particular line

I have a configuration file and I want to append a new entry after a specific line. Say my file is: new.conf.1="testing1" new.conf.2="testcode2" new.conf.3="test3"

My python code: (i got from stackflow) import fileinput

def fileappend(filename,searchstr,appendstr):
    for line in fileinput.input(file, inplace=1):
        if searchstr in line:
            line = line.replace(searchstr,searchstr+'\n'+replacestr)
        sys.stdout.write(line)

fileappend("filename.txt", "new.conf.3="test3"", "new.conf.4="sample4"

This works to some extent. But I see this is not the optimum way. Can we frame it in a much better way.

How can I use Java to read a file

So I have this piece of code in which I want to allow the user to enter in a String of any length and it encrypts the code. To make this more than a basic project, I thought it would be cool to have a 'save' feature where the user can pickup from later on.
The problem arises here. I was going through Youtube and through a youtuber I learnt how to create a file and write to the file. When I went to the part where I read the file (load) I saw that I need to create a variable for every single character in the file. As I will not know how many variables to make, I am stuck.
In his code (I will display it) he uses a while loop to loop through the contents of the file and using a variables he prints out its contents. My code is as follows:

import java.util.*;  
public class Sep {
    private Formatter x;
    public void openfile () {
        try {
            x = new Formatter("Gogo.txt");
        }
        catch (Exception e) {
            System.out.println("You have an error mate!!");
        }
    }
    public void addStuff() {
        x.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
        }
    public void closeFile () {
        x.close();
    }
}

As the user will be entering whatever he wants, I have no bloody clue on how many variables to make. The youtuber has this:

import java.util.*;


public class Sep {
    private Formatter g;
    private Scanner x;
    public void openfile () {
        try {
            g = new Formatter("Gogo.txt");
            x = new Scanner(new File("gogo.txt"));
        }
        catch (Exception e) {
            System.out.println("You have an error mate!!");
        }
    }
    public void addStuff() {
        g.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
        }
    public void readFile() {
        while(x.hasNext()) {
            String a = x.next();
            String b = x.next();
            String c = x.next();
            System.out.printf("%s %s %s\n", a,b,c);
        }
    public void closeFile () {
        x.close();
    }
}