Programs & Examples On #File

A block of arbitrary information, or resource for storing information, accessible by the string-based name or path. Files are available to computer programs and are usually based on some kind of persistent storage.

How to find encoding of a file via script on Linux?

It is really hard to determine if it is iso-8859-1. If you have a text with only 7 bit characters that could also be iso-8859-1 but you don't know. If you have 8 bit characters then the upper region characters exist in order encodings as well. Therefor you would have to use a dictionary to get a better guess which word it is and determine from there which letter it must be. Finally if you detect that it might be utf-8 than you are sure it is not iso-8859-1

Encoding is one of the hardest things to do because you never know if nothing is telling you

VS 2012: Scroll Solution Explorer to current file

If you have ReSharper installed clicking Shift+Alt+L will move focus to the current file in Solution Explorer.

Active Item Tracking will also need to be enabled as described in the accepted answer

Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer

Get Line Number of certain phrase in file Python

f = open('some_file.txt','r')
line_num = 0
search_phrase = "the dog barked"
for line in f.readlines():
    line_num += 1
    if line.find(search_phrase) >= 0:
        print line_num

EDIT 1.5 years later (after seeing it get another upvote): I'm leaving this as is; but if I was writing today would write something closer to Ash/suzanshakya's solution:

def line_num_for_phrase_in_file(phrase='the dog barked', filename='file.txt')
    with open(filename,'r') as f:
        for (i, line) in enumerate(f):
            if phrase in line:
                return i
    return -1
  • Using with to open files is the pythonic idiom -- it ensures the file will be properly closed when the block using the file ends.
  • Iterating through a file using for line in f is much better than for line in f.readlines(). The former is pythonic (e.g., would work if f is any generic iterable; not necessarily a file object that implements readlines), and more efficient f.readlines() creates an list with the entire file in memory and then iterates through it. * if search_phrase in line is more pythonic than if line.find(search_phrase) >= 0, as it doesn't require line to implement find, reads more easily to see what's intended, and isn't easily screwed up (e.g., if line.find(search_phrase) and if line.find(search_phrase) > 0 both will not work for all cases as find returns the index of the first match or -1).
  • Its simpler/cleaner to wrap an iterated item in enumerate like for i, line in enumerate(f) than to initialize line_num = 0 before the loop and then manually increment in the loop. (Though arguably, this is more difficult to read for people unfamiliar with enumerate.)

See code like pythonista

What’s the best way to check if a file exists in C++? (cross platform)

I would reconsider trying to find out if a file exists. Instead, you should try to open it (in Standard C or C++) in the same mode you intend to use it. What use is knowing that the file exists if, say, it isn't writable when you need to use it?

In C# check that filename is *possibly* valid (not that it exists)

This will get you the drives on the machine:

System.IO.DriveInfo.GetDrives()

These two methods will get you the bad characters to check:

System.IO.Path.GetInvalidFileNameChars();
System.IO.Path.GetInvalidPathChars();

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

You can catch that exception and return whatever you want from there.

open(target, 'a').close()
scores = {};
try:
    with open(target, "rb") as file:
        unpickler = pickle.Unpickler(file);
        scores = unpickler.load();
        if not isinstance(scores, dict):
            scores = {};
except EOFError:
    return {}

Convert file: Uri to File in Android

I made this like the following way:

try {
    readImageInformation(new File(contentUri.getPath()));

} catch (IOException e) {
    readImageInformation(new File(getRealPathFromURI(context,
                contentUri)));
}

public static String getRealPathFromURI(Context context, Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj,
                null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
}

So basically first I try to use a file i.e. picture taken by camera and saved on SD card. This don't work for image returned by: Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); That case there is a need to convert Uri to real path by getRealPathFromURI() function. So the conclusion is that it depends on what type of Uri you want to convert to File.

How to read a text file directly from Internet using Java?

Use an URL instead of File for any access that is not on your local computer.

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());

Actually, URL is even more generally useful, also for local access (use a file: URL), jar files, and about everything that one can retrieve somehow.

The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.


About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).

Here with some sample exception-handling:

try {
   URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
   Scanner s = new Scanner(url.openStream());
   // read from your scanner
}
catch(IOException ex) {
   // there was some connection problem, or the file did not exist on the server,
   // or your URL was not in the right format.
   // think about what to do now, and put it here.
   ex.printStackTrace(); // for now, simply output it.
}

Writing data into CSV file in C#

I use a two parse solution as it's very easy to maintain

// Prepare the values
var allLines = (from trade in proposedTrades
                select new object[] 
                { 
                    trade.TradeType.ToString(), 
                    trade.AccountReference, 
                    trade.SecurityCodeType.ToString(), 
                    trade.SecurityCode, 
                    trade.ClientReference, 
                    trade.TradeCurrency, 
                    trade.AmountDenomination.ToString(), 
                    trade.Amount, 
                    trade.Units, 
                    trade.Percentage, 
                    trade.SettlementCurrency, 
                    trade.FOP, 
                    trade.ClientSettlementAccount, 
                    string.Format("\"{0}\"", trade.Notes),                             
                }).ToList();

// Build the file content
var csv = new StringBuilder();
allLines.ForEach(line => 
{
    csv.AppendLine(string.Join(",", line));            
});

File.WriteAllText(filePath, csv.ToString());

PHP list of specific files in a directory

You can extend the RecursiveFilterIterator class like this:

class ExtensionFilter extends RecursiveFilterIterator
{
  /**
  * Hold the extensions pass to the class constructor 
  */
  protected $extensions;

  /**
   * ExtensionFilter constructor.
   *  
   * @param RecursiveIterator $iterator
   * @param string|array $extensions Extension to filter as an array ['php'] or
   * as string with commas in between 'php, exe, ini'
   */
  public function __construct(RecursiveIterator $iterator, $extensions)
  {
     parent::__construct($iterator);
     $this->extensions = is_array($extensions) ? $extensions :  array_map('trim', explode(',', $extensions));
  }

  public function accept()
  {
      if ($this->hasChildren()) {
         return true;
      }

      return $this->current()->isFile() &&
         in_array(strtolower($this->current()->getExtension()), $this->extensions);
  }

  public function getChildren()
  {
     return new self($this->getInnerIterator()->getChildren(), $this->extensions);
  }

Now you can instantiate RecursiveDirectoryIterator with path as an argument like this:

 $iterator = new RecursiveDirectoryIterator('\path\to\dir');
 $iterator = new ExtensionFilter($iterator, 'xml, php, ini');

 foreach($iterator as $file)
 {
   echo $file . '<br />';
 }

This will list files under the current folder only.

To get the files in subdirectories also, pass the $iterator ( ExtensionFIlter Iterator) to RecursiveIteratorIterator as argument:

$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

Now run the foreach loop on this iterator. You will get the files with specified extension

Note:-- Also make sure to run the ExtensionFilter before RecursiveIteratorIterator, otherwise you will get all the files

How to open every file in a folder

The code below reads for any text files available in the directory which contains the script we are running. Then it opens every text file and stores the words of the text line into a list. After store the words we print each word line by line

import os, fnmatch

listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
        _fileName = open(entry,"r")
        if _fileName.mode == "r":
            content = _fileName.read()
            contentList = content.split(" ")
            for i in contentList:
                if i != '\n' and i != "\r\n":
                    store.append(i)

for i in store:
    print(i)

Ant task to run an Ant target only if a file exists?

I think its worth referencing this similar answer: https://stackoverflow.com/a/5288804/64313

Here is a another quick solution. There are other variations possible on this using the <available> tag:

# exit with failure if no files are found
<property name="file" value="${some.path}/some.txt" />
<fail message="FILE NOT FOUND: ${file}">
    <condition><not>
        <available file="${file}" />
    </not></condition>
</fail>

Reading string by char till end of line C/C++

If you are using C function fgetc then you should check a next character whether it is equal to the new line character or to EOF. For example

unsigned int count = 0;
while ( 1 )
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
      if ( c == EOF ) break;
   }
   else
   {
      ++count;
   }
}    

or maybe it would be better to rewrite the code using do-while loop. For example

unsigned int count = 0;
do
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
   }
   else
   {
      ++count;
   }
} while ( c != EOF );

Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc to read lines of a file.

But if the program is written in C++ then it would be much better if you would use std::ifstream and std::string classes and function std::getline to read a whole line.

Excel VBA Check if directory exists error

To be certain that a folder exists (and not a file) I use this function:

Public Function FolderExists(strFolderPath As String) As Boolean
    On Error Resume Next
    FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory)
    On Error GoTo 0
End Function

It works both, with \ at the end and without.

The system cannot find the file specified in java

When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.

I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].

How do I save a String to a text file using Java?

Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.

Counting the number of files in a directory using Java

Since Java 8, you can do that in three lines:

try (Stream<Path> files = Files.list(Paths.get("your/path/here"))) {
    long count = files.count();
}

Regarding the 5000 child nodes and inode aspects:

This method will iterate over the entries but as Varkhan suggested you probably can't do better besides playing with JNI or direct system commands calls, but even then, you can never be sure these methods don't do the same thing!

However, let's dig into this a little:

Looking at JDK8 source, Files.list exposes a stream that uses an Iterable from Files.newDirectoryStream that delegates to FileSystemProvider.newDirectoryStream.

On UNIX systems (decompiled sun.nio.fs.UnixFileSystemProvider.class), it loads an iterator: A sun.nio.fs.UnixSecureDirectoryStream is used (with file locks while iterating through the directory).

So, there is an iterator that will loop through the entries here.

Now, let's look to the counting mechanism.

The actual count is performed by the count/sum reducing API exposed by Java 8 streams. In theory, this API can perform parallel operations without much effort (with multihtreading). However the stream is created with parallelism disabled so it's a no go...

The good side of this approach is that it won't load the array in memory as the entries will be counted by an iterator as they are read by the underlying (Filesystem) API.

Finally, for the information, conceptually in a filesystem, a directory node is not required to hold the number of the files that it contains, it can just contain the list of it's child nodes (list of inodes). I'm not an expert on filesystems, but I believe that UNIX filesystems work just like that. So you can't assume there is a way to have this information directly (i.e: there can always be some list of child nodes hidden somewhere).

Python: read all text file lines in loop

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

SQLite3 database or disk is full / the database disk image is malformed

To avoid getting "database or disk is full" in the first place, try this if you have lots of RAM:

sqlite> pragma temp_store = 2;

That tells SQLite to put temp files in memory. (The "database or disk is full" message does not mean either that the database is full or that the disk is full! It means the temp directory is full.) I have 256G of RAM but only 2G of /tmp, so this works great for me. The more RAM you have, the bigger db files you can work with.

If you haven't got a lot of ram, try this:

sqlite> pragma temp_store = 1;
sqlite> pragma temp_store_directory = '/directory/with/lots/of/space';

temp_store_directory is deprecated (which is silly, since temp_store is not deprecated and requires temp_store_directory), so be wary of using this in code.

How to create a file in memory for user to download, but not through server?

If the file contains text data, a technique I use is to put the text into a textarea element and have the user select it (click in textarea then ctrl-A) then copy followed by a paste to a text editor.

How I can delete in VIM all text from current line to end of file?

Just add another way , in normal mode , type ctrl+v then G, select the rest, then D, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.

How to do something to each file in a directory with a batch script

Command line usage:

for /f %f in ('dir /b c:\') do echo %f

Batch file usage:

for /f %%f in ('dir /b c:\') do echo %%f

Update: if the directory contains files with space in the names, you need to change the delimiter the for /f command is using. for example, you can use the pipe char.

for /f "delims=|" %%f in ('dir /b c:\') do echo %%f

Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq option on the for:

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f

And if you need to use output redirection or command piping, use the escape char (^):

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f

PHP, get file name without file extension

There is no need to write lots of code. Even it can be done just by one line of code. See here

Below is the one line code that returns the filename only and removes extension name:

<?php
 echo pathinfo('logo.png')['filename'];
?>

It will print

logo

Source: Remove extension and return only file name in PHP

How do I watch a file for changes?

I'd try something like this.

    try:
            f = open(filePath)
    except IOError:
            print "No such file: %s" % filePath
            raw_input("Press Enter to close window")
    try:
            lines = f.readlines()
            while True:
                    line = f.readline()
                    try:
                            if not line:
                                    time.sleep(1)
                            else:
                                    functionThatAnalisesTheLine(line)
                    except Exception, e:
                            # handle the exception somehow (for example, log the trace) and raise the same exception again
                            raw_input("Press Enter to close window")
                            raise e
    finally:
            f.close()

The loop checks if there is a new line(s) since last time file was read - if there is, it's read and passed to the functionThatAnalisesTheLine function. If not, script waits 1 second and retries the process.

download file using an ajax request

It is possible. You can have the download started from inside an ajax function, for example, just after the .csv file is created.

I have an ajax function that exports a database of contacts to a .csv file, and just after it finishes, it automatically starts the .csv file download. So, after I get the responseText and everything is Ok, I redirect browser like this:

window.location="download.php?filename=export.csv";

My download.php file looks like this:

<?php

    $file = $_GET['filename'];

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=".$file."");
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: binary/octet-stream");
    readfile($file);

?>

There is no page refresh whatsoever and the file automatically starts downloading.

NOTE - Tested in the following browsers:

Chrome v37.0.2062.120 
Firefox v32.0.1
Opera v12.17
Internet Explorer v11

Getting files by creation date in .NET

@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"

I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally

GetFiles  done 437834 in00:00:20.4812480
process files  done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2)  done 437834 in00:00:20.7412646

Limit file format when using <input type="file">?

Use input tag with accept attribute

<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />

Click here for the latest browser compatibility table

Live demo here

To select only image files, you can use this accept="image/*"

<input type="file" name="my-image" id="image" accept="image/*" />

Live demo here

Only gif, jpg and png will be shown, screen grab from Chrome version 44 Only gif, jpg and png will be shown, screen grab from Chrome version 44

How to create a file in Android?

I used the following code to create a temporary file for writing bytes. And its working fine.

File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
     OutputStream fo = new FileOutputStream(file);              
     fo.write(data1);
     fo.close();
     System.out.println("file created: "+file);
}               

//deleting the file             
file.delete();
System.out.println("file deleted");

How can I clear the content of a file?

You can use the File.WriteAllText method.

System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);

How do I check if a given string is a legal/valid file name under Windows?

Also CON, PRN, AUX, NUL, COM# and a few others are never legal filenames in any directory with any extension.

Using curl to upload POST data with files

I got it worked with this command curl -F 'filename=@/home/yourhomedirextory/file.txt' http://yourserver/upload

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

Reading a huge .csv file

what worked for me was and is superfast is

import pandas as pd
import dask.dataframe as dd
import time
t=time.clock()
df_train = dd.read_csv('../data/train.csv', usecols=[col1, col2])
df_train=df_train.compute()
print("load train: " , time.clock()-t)

Another working solution is:

import pandas as pd 
from tqdm import tqdm

PATH = '../data/train.csv'
chunksize = 500000 
traintypes = {
'col1':'category',
'col2':'str'}

cols = list(traintypes.keys())

df_list = [] # list to hold the batch dataframe

for df_chunk in tqdm(pd.read_csv(PATH, usecols=cols, dtype=traintypes, chunksize=chunksize)):
    # Can process each chunk of dataframe here
    # clean_data(), feature_engineer(),fit()

    # Alternatively, append the chunk to list and merge all
    df_list.append(df_chunk) 

# Merge all dataframes into one dataframe
X = pd.concat(df_list)

# Delete the dataframe list to release memory
del df_list
del df_chunk

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

see if two files have the same content in python

I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

  • Compare file sizes first, discarding all which doesn't match
  • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

Reading numbers from a text file into an array in C

Loop with %c to read the stream character by character instead of %d.

Encode a FileStream to base64 with c#

A simple Stream extension method would do the job:

public static class StreamExtensions
{
    public static string ConvertToBase64(this Stream stream)
    {
        var bytes = new Byte[(int)stream.Length];

        stream.Seek(0, SeekOrigin.Begin);
        stream.Read(bytes, 0, (int)stream.Length);

        return Convert.ToBase64String(bytes);
    }
}

The methods for Read (and also Write) and optimized for the respective class (whether is file stream, memory stream, etc.) and will do the work for you. For simple task like this, there is no need of readers, and etc.

The only drawback is that the stream is copied into byte array, but that is how the conversion to base64 via Convert.ToBase64String works unfortunately.

How to read the content of a file to a string in C?

Another, unfortunately highly OS-dependent, solution is memory mapping the file. The benefits generally include performance of the read, and reduced memory use as the applications view and operating systems file cache can actually share the physical memory.

POSIX code would look like this:

int fd = open("filename", O_RDONLY);
int len = lseek(fd, 0, SEEK_END);
void *data = mmap(0, len, PROT_READ, MAP_PRIVATE, fd, 0);

Windows on the other hand is little more tricky, and unfortunately I don't have a compiler in front of me to test, but the functionality is provided by CreateFileMapping() and MapViewOfFile().

Check line for unprintable characters while reading text file

How about below:

 FileReader fileReader = new FileReader(new File("test.txt"));

 BufferedReader br = new BufferedReader(fileReader);

 String line = null;
 // if no more lines the readLine() returns null
 while ((line = br.readLine()) != null) {
      // reading lines until the end of the file

 }

Source: http://devmain.blogspot.co.uk/2013/10/java-quick-way-to-read-or-write-to-file.html

How to force file download with PHP

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");

Open files in 'rt' and 'wt' modes

The t indicates text mode, meaning that \n characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.

Other than U, those mode flags come directly from the standard C library's fopen() function, a fact that is documented in the sixth paragraph of the python2 documentation for open().

As far as I know, t is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.

Java FileOutputStream Create File if not exists

You can create an empty file whether it exists or not ...

new FileOutputStream("score.txt", false).close();

if you want to leave the file if it exists ...

new FileOutputStream("score.txt", true).close();

You will only get a FileNotFoundException if you try to create the file in a directory which doesn't exist.

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):
    os.makedirs(path)

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
    temp_file.write(buff)

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

How to limit the maximum files chosen when using multiple file input

This should work and protect your form from being submitted if the number of files is greater then max_file_number.

$(function() {

  var // Define maximum number of files.
      max_file_number = 3,
      // Define your form id or class or just tag.
      $form = $('form'), 
      // Define your upload field class or id or tag.
      $file_upload = $('#image_upload', $form), 
      // Define your submit class or id or tag.
      $button = $('.submit', $form); 

  // Disable submit button on page ready.
  $button.prop('disabled', 'disabled');

  $file_upload.on('change', function () {
    var number_of_images = $(this)[0].files.length;
    if (number_of_images > max_file_number) {
      alert(`You can upload maximum ${max_file_number} files.`);
      $(this).val('');
      $button.prop('disabled', 'disabled');
    } else {
      $button.prop('disabled', false);
    }
  });
});

Call a function from another file?

Inside MathMethod.Py.

def Add(a,b):
   return a+b 

def subtract(a,b):
  return a-b

Inside Main.Py

import MathMethod as MM 
  print(MM.Add(200,1000))

Output:1200

How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

How to read a file in Groovy into a string?

Here you can Find some other way to do the same.

Read file.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();

Read Full file.

File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();

Read file Line Bye Line.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
 log.info file1.readLines().get(i)

}

Create a new file.

new File("C:\Temp\FileName.txt").createNewFile();

Creating a simple configuration file and parser in C++

Here is a simple work around for white space between the '=' sign and the data, in the config file. Assign to the istringstream from the location after the '=' sign and when reading from it, any leading white space is ignored.

Note: while using an istringstream in a loop, make sure you call clear() before assigning a new string to it.

//config.txt
//Input name = image1.png
//Num. of rows = 100
//Num. of cols = 150

std::string ipName;
int nR, nC;

std::ifstream fin("config.txt");
std::string line;
std::istringstream sin;

while (std::getline(fin, line)) {
 sin.str(line.substr(line.find("=")+1));
 if (line.find("Input name") != std::string::npos) {
  std::cout<<"Input name "<<sin.str()<<std::endl;
  sin >> ipName;
 }
 else if (line.find("Num. of rows") != std::string::npos) {
  sin >> nR;
 }
 else if (line.find("Num. of cols") != std::string::npos) {
  sin >> nC;
 }
 sin.clear();
}

Find a line in a file and remove it

package com.ncs.cache;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

    public void removeLineFromFile(String file, String lineToRemove) {

        try {

            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            // Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FileUtil util = new FileUtil();
        util.removeLineFromFile("test.txt", "bbbbb");
    }
}

src : http://www.javadb.com/remove-a-line-from-a-text-file/

Get the filePath from Filename using Java

I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:

System.out.println("File path: " + new File("Your file name").getAbsolutePath());

The File class has several more methods you might find useful.

Replace input type=file by an image

Working Code:

just hide input part and do like this.

<div class="ImageUpload">
   <label for="FileInput">
      <img src="../../img/Upload_Panel.png" style="width: 18px; margin-top: -316px; margin-left: 900px;"/>
   </label>

  <input id="FileInput" type="file" onchange="readURL(this,'Picture')" style="cursor: pointer;  display: none"/>
</div>

Write a file on iOS

Try making

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

as

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

How to iterate over the files of a certain directory, in Java?

I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles method and you can process each file.

You can find the information here: http://commons.apache.org/proper/commons-io/download_io.cgi

Here's an example:

Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
        while(it.hasNext()){
            System.out.println(((File) it.next()).getName());
        }

You can change null and put a list of extentions if you wanna filter. Example: {".xml",".java"}

Best method for reading newline delimited files and discarding the newlines?

What do you think about this approach?

with open(filename) as data:
    datalines = (line.rstrip('\r\n') for line in data)
    for line in datalines:
        ...do something awesome...

Generator expression avoids loading whole file into memory and with ensures closing the file

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

python requests file upload

Client Upload

If you want to upload a single file with Python requests library, then requests lib supports streaming uploads, which allow you to send large files or streams without reading into memory.

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

Server Side

Then store the file on the server.py side such that save the stream into file without loading into the memory. Following is an example with using Flask file uploads.

@app.route("/upload", methods=['POST'])
def upload_file():
    from werkzeug.datastructures import FileStorage
    FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'OK', 200

Or use werkzeug Form Data Parsing as mentioned in a fix for the issue of "large file uploads eating up memory" in order to avoid using memory inefficiently on large files upload (s.t. 22 GiB file in ~60 seconds. Memory usage is constant at about 13 MiB.).

@app.route("/upload", methods=['POST'])
def upload_file():
    def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
        import tempfile
        tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
        app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
        return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
    for fil in files.values():
        app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
        # Do whatever with stored file at `fil.stream.name`
    return 'OK', 200

How to write and read java serialized objects into a file

As others suggested, you can serialize and deserialize the whole list at once, which is simpler and seems to comply perfectly with what you intend to do.

In that case the serialization code becomes

ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
    fout = new FileOutputStream("G:\\address.ser", true);
    oos = new ObjectOutputStream(fout);
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    if(oos != null){
        oos.close();
    } 
}

And deserialization becomes (assuming that myClassList is a list and hoping you will use generics):

ObjectInputStream objectinputstream = null;
try {
    FileInputStream streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
    recordList.add(readCase);
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

You can also deserialize several objects from a file, as you intended to:

ObjectInputStream objectinputstream = null;
try {
    streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    MyClass readCase = null;
    do {
        readCase = (MyClass) objectinputstream.readObject();
        if(readCase != null){
            recordList.add(readCase);
        } 
    } while (readCase != null)        
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

Please do not forget to close stream objects in a finally clause (note: it can throw exception).

EDIT

As suggested in the comments, it should be preferable to use try with resources and the code should get quite simpler.

Here is the list serialization :

try(
    FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
){
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
}

How can I see the size of files and directories in linux?

ls -l --block-size=M will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB.

If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.

If you don't want the M suffix attached to the file size, you can use something like --block-size=1M. Thanks Stéphane Chazelas for suggesting this.

This is described in the man page for ls; man ls and search for SIZE. It allows for units other than MB/MiB as well, and from the looks of it (I didn't try that) arbitrary block sizes as well (so you could see the file size as number of 412-byte blocks, if you want to).

Note that the --block-size parameter is a GNU extension on top of the Open Group's ls, so this may not work if you don't have a GNU userland (which most Linux installations do). The ls from GNU coreutils 8.5 does support --block-size as described above.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Get the current script file name

When you want your include to know what file it is in (ie. what script name was actually requested), use:

basename($_SERVER["SCRIPT_FILENAME"], '.php')

Because when you are writing to a file you usually know its name.

Edit: As noted by Alec Teal, if you use symlinks it will show the symlink name instead.

create a text file using javascript

Try this:

<SCRIPT LANGUAGE="JavaScript">
 function WriteToFile(passForm) {

    set fso = CreateObject("Scripting.FileSystemObject");  
    set s = fso.CreateTextFile("C:\test.txt", True);
    s.writeline("HI");
    s.writeline("Bye");
    s.writeline("-----------------------------");
    s.Close();
 }
  </SCRIPT>

</head>

<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form> 

This will work only on IE

How do I get the path and name of the file that is currently executing?

import sys

print sys.path[0]

this would print the path of the currently executing script

VBA check if file exists

something like this

best to use a workbook variable to provide further control (if needed) of the opened workbook

updated to test that file name was an actual workbook - which also makes the initial check redundant, other than to message the user than the Textbox is blank

Dim strFile As String
Dim WB As Workbook
strFile = Trim(TextBox1.Value)
Dim DirFile As String
If Len(strFile) = 0 Then Exit Sub

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile
If Len(Dir(DirFile)) = 0 Then
  MsgBox "File does not exist"
Else
 On Error Resume Next
 Set WB = Workbooks.Open(DirFile)
 On Error GoTo 0
 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical
End If

Better way to check if a Path is a File or a Directory?

I use the following, it also tests the extension which means it can be used for testing if the path supplied is a file but a file that doesn't exist.

private static bool isDirectory(string path)
{
    bool result = true;
    System.IO.FileInfo fileTest = new System.IO.FileInfo(path);
    if (fileTest.Exists == true)
    {
        result = false;
    }
    else
    {
        if (fileTest.Extension != "")
        {
            result = false;
        }
    }
    return result;
}

How to limit file upload type file size in PHP?

Hope this helps :-)

if(isset($_POST['submit'])){
    ini_set("post_max_size", "30M");
    ini_set("upload_max_filesize", "30M");
    ini_set("memory_limit", "20000M"); 
    $fileName='product_demo.png';

    if($_FILES['imgproduct']['size'] > 0 && 
            (($_FILES["imgproduct"]["type"] == "image/gif") || 
                ($_FILES["imgproduct"]["type"] == "image/jpeg")|| 
                ($_FILES["imgproduct"]["type"] == "image/pjpeg") || 
                ($_FILES["imgproduct"]["type"] == "image/png") &&
                ($_FILES["imgproduct"]["size"] < 2097152))){

        if ($_FILES["imgproduct"]["error"] > 0){
            echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
        } else {    
            $rnd=rand(100,999);
            $rnd=$rnd."_";
            $fileName = $rnd.trim($_FILES['imgproduct']['name']);
            $tmpName  = $_FILES['imgproduct']['tmp_name'];
            $fileSize = $_FILES['imgproduct']['size'];
            $fileType = $_FILES['imgproduct']['type'];  
            $target = "upload/";
            echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ; 
            move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
        }
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
}

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

JavaScript: Create and save file

Javascript has a FileSystem API. If you can deal with having the feature only work in Chrome, a good starting point would be: http://www.html5rocks.com/en/tutorials/file/filesystem/.

Python list directory, subdirectory, and files

Here is a one-liner:

import os

[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text

The outer most val for sublist in ... loop flattens the list to be one dimensional. The j loop collects a list of every file basename and joins it to the current path. Finally, the i loop iterates over all directories and sub directories.

This example uses the hard-coded path ./ in the os.walk(...) call, you can supplement any path string you like.

Note: os.path.expanduser and/or os.path.expandvars can be used for paths strings like ~/

Extending this example:

Its easy to add in file basename tests and directoryname tests.

For Example, testing for *.jpg files:

... for j in i[2] if j.endswith('.jpg')] ...

Additionally, excluding the .git directory:

... for i in os.walk('./') if '.git' not in i[0].split('/')]

PHP: how can I get file creation date?

Use filectime. For Windows it will return the creation time, and for Unix the change time which is the best you can get because on Unix there is no creation time (in most filesystems).

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

What is the best way to generate a unique and short file name in Java

I use the timestamp

i.e

new File( simpleDateFormat.format( new Date() ) );

And have the simpleDateFormat initialized to something like as:

new SimpleDateFormat("File-ddMMyy-hhmmss.SSS.txt");

EDIT

What about

new File(String.format("%s.%s", sdf.format( new Date() ),
                                random.nextInt(9)));

Unless the number of files created in the same second is too high.

If that's the case and the name doesn't matters

 new File( "file."+count++ );

:P

How to read/write from/to file using Go?

[]byte is a slice (similar to a substring) of all or part of a byte array. Think of the slice as a value structure with a hidden pointer field for the system to locate and access all or part of an array (the slice), plus fields for the length and capacity of the slice, which you can access using the len() and cap() functions.

Here's a working starter kit for you, which reads and prints a binary file; you will need to change the inName literal value to refer to a small file on your system.

package main
import (
    "fmt";
    "os";
)
func main()
{
    inName := "file-rw.bin";
    inPerm :=  0666;
    inFile, inErr := os.Open(inName, os.O_RDONLY, inPerm);
    if inErr == nil {
        inBufLen := 16;
        inBuf := make([]byte, inBufLen);
        n, inErr := inFile.Read(inBuf);
        for inErr == nil {
            fmt.Println(n, inBuf[0:n]);
            n, inErr = inFile.Read(inBuf);
        }
    }
    inErr = inFile.Close();
}

How do you get a directory listing in C?

opendir/readdir are POSIX. If POSIX is not enough for the portability you want to achieve, check Apache Portable Runtime

Java NIO FileChannel versus FileOutputstream performance / usefulness

If you are not using the transferTo feature or non-blocking features you will not notice a difference between traditional IO and NIO(2) because the traditional IO maps to NIO.

But if you can use the NIO features like transferFrom/To or want to use Buffers, then of course NIO is the way to go.

What is simplest way to read a file into String?

Another alternative approach is:

How do I create a Java string from the contents of a file?

Other option is to use utilities provided open source libraries
http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html

Why java doesn't provide such a common util API ?
a) to keep the APIs generic so that encoding, buffering etc is handled by the programmer.
b) make programmers do some work and write/share opensource util libraries :D ;-)

Does Java have a path joining method?

This concerns Java versions 7 and earlier.

To quote a good answer to the same question:

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine (String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

How to check if a file exists before creating a new file

I just saw this test:

bool getFileExists(const TCHAR *file)
{ 
  return (GetFileAttributes(file) != 0xFFFFFFFF);
}

Error: "setFile(null,false) call failed" when using log4j

I had the exact same problem. Here is the solution that worked for me: simply put your properties file path in the cmd line this way :

-Dlog4j.configuration=<FILE_PATH>  (ex: log4j.properties)

Hope this will help you

Why should text files end with a newline?

There's also a practical programming issue with files lacking newlines at the end: The read Bash built-in (I don't know about other read implementations) doesn't work as expected:

printf $'foo\nbar' | while read line
do
    echo $line
done

This prints only foo! The reason is that when read encounters the last line, it writes the contents to $line but returns exit code 1 because it reached EOF. This breaks the while loop, so we never reach the echo $line part. If you want to handle this situation, you have to do the following:

while read line || [ -n "${line-}" ]
do
    echo $line
done < <(printf $'foo\nbar')

That is, do the echo if the read failed because of a non-empty line at end of file. Naturally, in this case there will be one extra newline in the output which was not in the input.

Read from file or stdin

Note that what you want is to know if stdin is connected to a terminal or not, not if it exists. It always exists but when you use the shell to pipe something into it or read a file, it is not connected to a terminal.

You can check that a file descriptor is connected to a terminal via the termios.h functions:

#include <termios.h>
#include <stdbool.h>

bool stdin_is_a_pipe(void)
{
    struct termios t;
    return (tcgetattr(STDIN_FILENO, &t) < 0);
}

This will try to fetch the terminal attributes of stdin. If it is not connected to a pipe, it is attached to a tty and the tcgetattr function call will succeed. In order to detect a pipe, we check for tcgetattr failure.

How do I delete files programmatically on Android?

I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):

System.out.println(new File(path).getAbsoluteFile().delete());

The System out can be ignored obviously, I put it for convenience of confirming the deletion.

How to write to a JSON file in the correct format

To make this work on Ubuntu Linux:

  1. I installed the Ubuntu package ruby-json:

    apt-get install ruby-json
    
  2. I wrote the script in ${HOME}/rubybin/jsonDEMO

  3. $HOME/.bashrc included:

    ${HOME}/rubybin:${PATH}
    

(On this occasion I also typed the above on the bash command line.)

Then it worked when I entered on the command line:

jsonDemo

c# open file with default application and parameters

Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default

How To: Create a New Setting at Design Time

Update: after comments below

  1. Right + Click on project
  2. Add New Item
  3. Under Visual C# Items -> General
  4. Select Settings File

How to browse for a file in java swing library?

I ended up using this quick piece of code that did exactly what I needed:

final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);

try {
    // Open an input stream
    Scanner reader = new Scanner(fc.getSelectedFile());
}

Append TimeStamp to a File Name

You can use below instead:

DateTime.Now.Ticks

How to construct a relative path in Java from two absolute paths (or URLs)?

I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:

public static String getRelativePath(String fromPath, String toPath) {

  // This weirdness is because a separator of '/' messes with String.split()
  String regexCharacter = File.separator;
  if (File.separatorChar == '\\') {
    regexCharacter = "\\\\";
  }

  String[] fromSplit = fromPath.split(regexCharacter);
  String[] toSplit = toPath.split(regexCharacter);

  // Find the common path
  int common = 0;
  while (fromSplit[common].equals(toSplit[common])) {
    common++;
  }

  StringBuffer result = new StringBuffer(".");

  // Work your way up the FROM path to common ground
  for (int i = common; i < fromSplit.length; i++) {
    result.append(File.separatorChar).append("..");
  }

  // Work your way down the TO path
  for (int i = common; i < toSplit.length; i++) {
    result.append(File.separatorChar).append(toSplit[i]);
  }

  return result.toString();
}

Batch files: How to read a file?

Under NT-style cmd.exe, you can loop through the lines of a text file with

FOR /F %i IN (file.txt) DO @echo %i

Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)

PHP filesize MB/KB conversion

A cleaner approach:

function Size($path)
{
    $bytes = sprintf('%u', filesize($path));

    if ($bytes > 0)
    {
        $unit = intval(log($bytes, 1024));
        $units = array('B', 'KB', 'MB', 'GB');

        if (array_key_exists($unit, $units) === true)
        {
            return sprintf('%d %s', $bytes / pow(1024, $unit), $units[$unit]);
        }
    }

    return $bytes;
}

How to scan a folder in Java?

import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

http://java.sun.com/javase/6/docs/api/java/io/File.html

Git undo changes in some files

git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index

Pick any kind of file via an Intent in Android

Samsung file explorer needs not only custom action (com.sec.android.app.myfiles.PICK_DATA), but also category part (Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.

Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);

You can also use this action for opening multiple files: com.sec.android.app.myfiles.PICK_DATA_MULTIPLE Anyway here is my solution which works on Samsung and other devices:

public void openFile(String mimeType) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(mimeType);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // special intent for Samsung file manager
        Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
         // if you want any file type, you can skip next line 
        sIntent.putExtra("CONTENT_TYPE", mimeType); 
        sIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent chooserIntent;
        if (getPackageManager().resolveActivity(sIntent, 0) != null){
            // it is device with Samsung file manager
            chooserIntent = Intent.createChooser(sIntent, "Open file");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
        } else {
            chooserIntent = Intent.createChooser(intent, "Open file");
        }

        try {
            startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
        }
    }

This solution works well for me, and maybe will be useful for someone else.

logger configuration to log to file and print to stdout

Logging to stdout and rotating file with different levels and formats:

import logging
import logging.handlers
import sys

if __name__ == "__main__":

    # Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.
    logging.getLogger().setLevel(logging.NOTSET)

    # Add stdout handler, with level INFO
    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.INFO)
    formater = logging.Formatter('%(name)-13s: %(levelname)-8s %(message)s')
    console.setFormatter(formater)
    logging.getLogger().addHandler(console)

    # Add file rotating handler, with level DEBUG
    rotatingHandler = logging.handlers.RotatingFileHandler(filename='rotating.log', maxBytes=1000, backupCount=5)
    rotatingHandler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    rotatingHandler.setFormatter(formatter)
    logging.getLogger().addHandler(rotatingHandler)

    log = logging.getLogger("app." + __name__)

    log.debug('Debug message, should only appear in the file.')
    log.info('Info message, should appear in file and stdout.')
    log.warning('Warning message, should appear in file and stdout.')
    log.error('Error message, should appear in file and stdout.')

Portable way to check if directory exists [Windows/Linux, C]

With C++17 you can use std::filesystem::is_directory function (https://en.cppreference.com/w/cpp/filesystem/is_directory). It accepts a std::filesystem::path object which can be constructed with a unicode path.

How can I catch all the exceptions that will be thrown through reading and writing a file?

Do you mean catch an Exception of any type that is thrown, as opposed to just specific Exceptions?

If so:

try {
   //...file IO...
} catch(Exception e) {
   //...do stuff with e, such as check its type or log it...
}

Get last n lines of a file, similar to tail

If reading the whole file is acceptable then use a deque.

from collections import deque
deque(f, maxlen=n)

Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.

import itertools
def maxque(items, size):
    items = iter(items)
    q = deque(itertools.islice(items, size))
    for item in items:
        del q[0]
        q.append(item)
    return q

If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.

def tail(f, n):
    assert n >= 0
    pos, lines = n+1, []
    while len(lines) <= n:
        try:
            f.seek(-pos, 2)
        except IOError:
            f.seek(0)
            break
        finally:
            lines = list(f)
        pos *= 2
    return lines[-n:]

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Use permission symbols instead of numbers

Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

#!/usr/bin/env python3

import os
import stat

os.chmod(
    'myfile',
    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |
    stat.S_IROTH
)

This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat.

Another advantage is the greater portability as mentioned in the docs:

Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

Tested in Ubuntu 16.04, Python 3.5.2.

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)

public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
    disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
    setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}

}

How to set up java logging using a properties file? (java.util.logging)

Okay, first intuition is here:

handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL

The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....

In the mean time, try:

handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL

Update

No, duh, needed more coffee. Nevermind.

While I think more, note that you can use the methods in Properties to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.


Another update

This line:

    FileInputStream configFile = new FileInputStream("/path/to/app.properties"));

has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are.

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

Business logic in MVC

The term business logic is in my opinion not a precise definition. Evans talks in his book, Domain Driven Design, about two types of business logic:

  • Domain logic.
  • Application logic.

This separation is in my opinion a lot clearer. And with the realization that there are different types of business rules also comes the realization that they don't all necessarily go the same place.

Domain logic is logic that corresponds to the actual domain. So if you are creating an accounting application, then domain rules would be rules regarding accounts, postings, taxation, etc. In an agile software planning tool, the rules would be stuff like calculating release dates based on velocity and story points in the backlog, etc.

For both these types of application, CSV import/export could be relevant, but the rules of CSV import/export has nothing to do with the actual domain. This kind of logic is application logic.

Domain logic most certainly goes into the model layer. The model would also correspond to the domain layer in DDD.

Application logic however does not necessarily have to be placed in the model layer. That could be placed in the controllers directly, or you could create a separate application layer hosting those rules. What is most logical in this case would depend on the actual application.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This appears to be a UTF-8 encoding issue that may have been caused by a double-UTF8-encoding of the database file contents.

This situation could happen due to factors such as the character set that was or was not selected (for instance when a database backup file was created) and the file format and encoding database file was saved with.

I have seen these strange UTF-8 characters in the following scenario (the description may not be entirely accurate as I no longer have access to the database in question):

  • As I recall, there the database and tables had a "uft8_general_ci" collation.
  • Backup is made of the database.
  • Backup file is opened on Windows in UNIX file format and with ANSI encoding.
  • Database is restored on a new MySQL server by copy-pasting the contents from the database backup file into phpMyAdmin.

Looking into the file contents:

  • Opening the SQL backup file in a text editor shows that the SQL backup file has strange characters such as "sÃ¥". On a side note, you may get different results if opening the same file in another editor. I use TextPad here but opening the same file in SublimeText said "sÃ¥" because SublimeText correctly UTF8-encoded the file -- still, this is a bit confusing when you start trying to fix the issue in PHP because you don't see the right data in SublimeText at first. Anyways, that can be resolved by taking note of which encoding your text editor is using when presenting the file contents.
  • The strange characters are double-encoded UTF-8 characters, so in my case the first "Ã" part equals "Ã" and "Â¥" = "¥" (this is my first "encoding"). THe "Ã¥" characters equals the UTF-8 character for "å" (this is my second encoding).

So, the issue is that "false" (UTF8-encoded twice) utf-8 needs to be converted back into "correct" utf-8 (only UTF8-encoded once).

Trying to fix this in PHP turns out to be a bit challenging:

utf8_decode() is not able to process the characters.

// Fails silently (as in - nothing is output)
$str = "så";

$str = utf8_decode($str);
printf("\n%s", $str);

$str = utf8_decode($str);
printf("\n%s", $str);

iconv() fails with "Notice: iconv(): Detected an illegal character in input string".

echo iconv("UTF-8", "ISO-8859-1", "så");

Another fine and possible solution fails silently too in this scenario

$str = "så";
echo html_entity_decode(htmlentities($str, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

mb_convert_encoding() silently: #

$str = "så";
echo mb_convert_encoding($str, 'ISO-8859-15', 'UTF-8');
// (No output)

Trying to fix the encoding in MySQL by converting the MySQL database characterset and collation to UTF-8 was unsuccessfully:

ALTER DATABASE myDatabase CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

I see a couple of ways to resolve this issue.

The first is to make a backup with correct encoding (the encoding needs to match the actual database and table encoding). You can verify the encoding by simply opening the resulting SQL file in a text editor.

The other is to replace double-UTF8-encoded characters with single-UTF8-encoded characters. This can be done manually in a text editor. To assist in this process, you can manually pick incorrect characters from Try UTF-8 Encoding Debugging Chart (it may be a matter of replacing 5-10 errors).

Finally, a script can assist in the process:

    $str = "så";
    // The two arrays can also be generated by double-encoding values in the first array and single-encoding values in the second array.
    $str = str_replace(["Ã","Â¥"], ["Ã","¥"], $str); 
    $str = utf8_decode($str);
    echo $str;
    // Output: "så" (correct)

HTML forms - input type submit problem with action=URL when URL contains index.aspx

This appears to be my "preferred" solution:

<form action="www.spufalcons.com/index.aspx?tab=gymnastics&path=gym" method="post">  <div>
<input type="submit" value="Gymnastics"></div>

Sorry for the presentation format - I'm still trying to learn how to use this forum....

I do have a follow-up question. In looking at my MySQL database of URL's it appears that ~30% of the URL's will need to use this post/div wrapper approach. This leaves ~70% that cannot accept the "post" attribute. For example:

<form action="http://www.google.com" method="post">
  <div>
    <input type="submit" value="Google"/>
  </div></form>

does not work. Do you have a recommendation for how to best handle this get/post condition test. Off the top of my head I'm guessing that using PHP to evaluate the existence of the "?" character in the URL may be my best approach, although I'm not sure how to structure the HTML form to accomplish this.

Thank YOU!

How to configure port for a Spring Boot application

You can add the port in below methods.

  1. Run -> Configurations section

  2. In application.xml add server.port=XXXX

Hiding table data using <div style="display:none">

Just apply the style attribute to the tr tag. In the case of multiple tr tags, you will have to apply the style to each element, or wrap them in a tbody tag:

<table>
  <tr><th>Test Table</th><tr>
  <tbody style="display:none">
    <tr><td>123456789</td><tr>
    <tr><td>123456789</td><tr>
    <tr><td>123456789</td><tr>
  </tbody>
</table>

conflicting types for 'outchar'

In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:

#include <stdio.h> #include <stdlib.h>  void outchar(char ch);  int main() {     outchar('A');     outchar('B');     outchar('C');     return 0; }  void outchar(char ch) {     printf("%c", ch); } 

Also, you should be specifying the return type of every function. I added that for you.

How Stuff and 'For Xml Path' work in SQL Server?

This article covers various ways of concatenating strings in SQL, including an improved version of your code which doesn't XML-encode the concatenated values.

SELECT ID, abc = STUFF
(
    (
        SELECT ',' + name
        FROM temp1 As T2
        -- You only want to combine rows for a single ID here:
        WHERE T2.ID = T1.ID
        ORDER BY name
        FOR XML PATH (''), TYPE
    ).value('.', 'varchar(max)')
, 1, 1, '')
FROM temp1 As T1
GROUP BY id

To understand what's happening, start with the inner query:

SELECT ',' + name
FROM temp1 As T2
WHERE T2.ID = 42 -- Pick a random ID from the table
ORDER BY name
FOR XML PATH (''), TYPE

Because you're specifying FOR XML, you'll get a single row containing an XML fragment representing all of the rows.

Because you haven't specified a column alias for the first column, each row would be wrapped in an XML element with the name specified in brackets after the FOR XML PATH. For example, if you had FOR XML PATH ('X'), you'd get an XML document that looked like:

<X>,aaa</X>
<X>,bbb</X>
...

But, since you haven't specified an element name, you just get a list of values:

,aaa,bbb,...

The .value('.', 'varchar(max)') simply retrieves the value from the resulting XML fragment, without XML-encoding any "special" characters. You now have a string that looks like:

',aaa,bbb,...'

The STUFF function then removes the leading comma, giving you a final result that looks like:

'aaa,bbb,...'

It looks quite confusing at first glance, but it does tend to perform quite well compared to some of the other options.

What is the best way to remove a table row with jQuery?

id is not a good selector now. You can define some properties on the rows. And you can use them as selector.

<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>

and you can use a func to select the row like this (ES6):

const rowRemover = (category,type)=>{
   $(`tr[category=${category}][type=${type}]`).remove();
}

rowRemover('petshop','fish');

Get keys of a Typescript interface as array of strings

Maybe it's too late, but in version 2.1 of TypeScript you can use key of like this:

interface Person {
    name: string;
    age: number;
    location: string;
}

type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[];  // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person };  // string

Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types

Append to the end of a Char array in C++

There's no built-in command for that because it's illegal. You can't modify the size of an array once declared.

What you're looking for is either std::vector to simulate a dynamic array, or better yet a std::string.

std::string first ("The dog jumps ");
std::string second ("over the log");
std::cout << first + second << std::endl;

JavaScript Array to Set

By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.

var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}


var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}

So, do not convert to set if you have repeated values in your array.

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

You need to modify the config-db.php and set your password to the password you gave to the user root, or else if he has no password leave as this ''.

How to disable a input in angular2

Disabled Select in angular 9.

one thing keep in mind disabled work with boolean values in this example, I am using the (change) event with the select option if the country is not selected region will be disabled.

find.component.ts file

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-find',
  templateUrl: './find.component.html',
  styleUrls: ['./find.component.css']
})
export class FindComponent implements OnInit {
  isCountrySelected:boolean;

  constructor() { }
  //onchange event disabled false
 onChangeCountry(id:number){
   this.isCountrySelected = false;
 }
  ngOnInit(): void {
    //initially disabled true
    this.isCountrySelected = true;
  }

}

find.component.html

//Country select option
<select  class="form-control"  (change)="onChangeCountry()" value="Choose Country">
                    <option value="">Choose a Country</option>
                    <option value="US">United States</option>
                     
</select>
//region disabled till country is not selected 
<select class="form-control" [disabled]="isCountrySelected">
                    <option value="">Choose a Region</option>
                    <option value="">Any regions.</option>
                    
                </select>

What is the difference between XML and XSD?

Basically an XSD file defines how the XML file is going to look like. It's a Schema file which defines the structure of the XML file. So it specifies what the possible fields are and what size they are going to be.

An XML file is an instance of XSD as it uses the rules defined in the XSD.

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

Here is my Approach based on DarKalimHero's Suggestion by selecting only on Explorer.exe processes

Function Get-RdpSessions 
{
    param(
        [string]$computername 
    )

    $processinfo = Get-WmiObject -Query "select * from win32_process where name='explorer.exe'" -ComputerName $computername

    $processinfo | ForEach-Object { $_.GetOwner().User } | Sort-Object -Unique | ForEach-Object { New-Object psobject -Property @{Computer=$computername;LoggedOn=$_} } | Select-Object Computer,LoggedOn
}

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Some security config and you are ready with swagger open to all

For Swagger V2

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

For Swagger V3

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/v3/api-docs",  
            "/swagger-resources/**", 
            "/swagger-ui/**",
             };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

How do AX, AH, AL map onto EAX?

no your ans is Wrong

Selection of Al and Ah is from AX not from EAX

e.g

EAX=0000 0000 0000 0000 0000 0000 0000 0111

So if we call AX it should return

0000 0000 0000 0111

if we call AH it should return

0000 0000

and when we call AL it should return

0000 0111

Example number 2

EAX: 22 33 55 77
AX: 55 77
AH: 55    
AL: 77

example 3

EAX: 1111 0000 0000 0000 0000 0000 0000 0111    
AX= 0000 0000 0000 0111
AH= 0000 0000
AL= 0000 0111  

Switch statement: must default be the last case?

The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.

Good Example :-

switch(5) {
  case 1:
    echo "1";
    break;
  case 2:
  default:
    echo "2, default";
    break;
  case 3;
    echo "3";
    break;
}


Outputs '2,default'

very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default

adb doesn't show nexus 5 device

This simple steps worked for me, I debug on my Nexus 5 and 5X devices on Windows 8.1.

The steps to follow are these:

1) Enable from Developers Options the Debug USB Mode

2) Unplug the device from the computer

3.1) Go to Settings ? Storage, in the ActionBar, click the option menu and choose USB computer connection.

3.2) If you didn't find the 3.1) option then go to Settings ? Developers Options ? Select USB Configuration.

4) Select Camera (PTP) connection.

5) Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.

6) If it doesn't work try to toggle the Debug USB Mode in the Developers Options Finally, you should see it now in the DDMS and voilà.

How can I sort generic list DESC and ASC?

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

django - get() returned more than one topic

get() returned more than one topic -- it returned 2!

The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get() such as

Model.objects.get(field_name=some_param)

To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.

So instead of using get() you should use filter() which will return multiple records. Such as

Model.objects.filter(field_name=some_param)

Please read about how to make queries in django here.

PHP code to get selected text of a combo box

if you fetching it from database then

<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>"; 
$q2=mysql_query($s2); 
while($rw2=mysql_fetch_array($q2)) { 
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>

How to fade changing background image

This may help

HTML

<div id="textcontainer">        
    <span id="sometext">This is some information </span>
    <div id="container">

    </div>
</div>

CSS

#textcontainer{
    position:relative;
    border:1px solid #000;
    width :300px;
    height:300px;
}
#container{
    background-image :url("http://dcooper.org/gallery/cf_appicon.jpg");
    width :100%;
    height:100%;
}
#sometext{
    position:absolute;
    top:50%;
    left:50%;
}

Js

$('#container').css('opacity','.1');

How to save final model using keras?

The model has a save method, which saves all the details necessary to reconstitute the model. An example from the keras documentation:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

classname::Staicfunction();

Non static functions have to be called using objects.

classname obj;
obj.Somefunction();

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

You can reverse the logic. Instead of deleting an invalid row after it has been inserted, write an INSTEAD OF trigger to insert only if you verify the row is valid.

CREATE TRIGGER mytrigger ON sometable
INSTEAD OF INSERT
AS BEGIN
  DECLARE @isnum TINYINT;

  SELECT @isnum = ISNUMERIC(somefield) FROM inserted;

  IF (@isnum = 1)
    INSERT INTO sometable SELECT * FROM inserted;
  ELSE
    RAISERROR('somefield must be numeric', 16, 1)
      WITH SETERROR;
END

If your application doesn't want to handle errors (as Joel says is the case in his app), then don't RAISERROR. Just make the trigger silently not do an insert that isn't valid.

I ran this on SQL Server Express 2005 and it works. Note that INSTEAD OF triggers do not cause recursion if you insert into the same table for which the trigger is defined.

Facebook Graph API error code list

I was looking for the same thing and I just found this list

https://developers.facebook.com/docs/reference/api/errors/

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

Using current time in UTC as default value in PostgreSQL

A function is not even needed. Just put parentheses around the default expression:

create temporary table test(
    id int, 
    ts timestamp without time zone default (now() at time zone 'utc')
);

How does Git handle symbolic links?

You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?

To find out, first, make a symbolic link:

$ ln -s /path/referenced/by/symlink symlink

Git doesn't know about this file yet. git ls-files lets you inspect your index (-s prints stat-like output):

$ git ls-files -s ./symlink
[nothing]

Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.

$ git add ./symlink

So, what was added?

$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0       symlink

The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file:

$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink

(Note 120000 is the mode listed in ls-files output. It would be something like 100644 for a regular file.)

But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks config. From man git-config:

core.symlinks

If false, symbolic links are checked out as small plain files that contain the link text.

So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks config.

Either way, the data referenced by the symlink is not stored in the repository.

get current page from url

A simple function like below will help :

public string GetCurrentPageName() 
{ 
    string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath); 
    string sRet = oInfo.Name; 
    return sRet; 
} 

How do I implement a callback in PHP?

create_function did not work for me inside a class. I had to use call_user_func.

<?php

class Dispatcher {
    //Added explicit callback declaration.
    var $callback;

    public function Dispatcher( $callback ){
         $this->callback = $callback;
    }

    public function asynchronous_method(){
       //do asynch stuff, like fwrite...then, fire callback.
       if ( isset( $this->callback ) ) {
            if (function_exists( $this->callback )) call_user_func( $this->callback, "File done!" );
        }
    }

}

Then, to use:

<?php 
include_once('Dispatcher.php');
$d = new Dispatcher( 'do_callback' );
$d->asynchronous_method();

function do_callback( $data ){
   print 'Data is: ' .  $data .  "\n";
}
?>

[Edit] Added a missing parenthesis. Also, added the callback declaration, I prefer it that way.

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

Can I send a ctrl-C (SIGINT) to an application on Windows?

Yes. The windows-kill project does exactly what you want:

windows-kill -SIGINT 1234

Deleting Elements in an Array if Element is a Certain value VBA

I know this is old, but here's the solution I came up with when I didn't like the ones I found.

-Loop through the array (Variant) adding each element and some divider to a string, unless it matches the one you want to remove -Then split the string on the divider

tmpString=""
For Each arrElem in GlobalArray
   If CStr(arrElem) = "removeThis" Then
      GoTo SkipElem
   Else
      tmpString =tmpString & ":-:" & CStr(arrElem)
   End If
SkipElem:
Next
GlobalArray = Split(tmpString, ":-:")

Obviously the use of strings creates some limitations, like needing to be sure of the information already in the array, and as-is this code makes the first array element blank, but it does what I need and with a little more work it could be more versatile.

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

CSS, Images, JS not loading in IIS

I had this same problem. For me, it was due to Cache-Control header being set at the server level in IIS to no-cache, no-store. So for my application I had to add in the below to my web.config:

<httpProtocol>
    <customHeaders>
        <remove name="Cache-Control" />
    </customHeaders>
</httpProtocol>

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

How to get a list of images on docker registry v2

Docker search registry v2 functionality is currently not supported at the time of this writing. See discussion since Feb 2015: "propose registry search functionality #206" https://github.com/docker/distribution/issues/206

I wrote a script, view-private-registry, that you can find: https://github.com/BradleyA/Search-docker-registry-v2-script.1.0 It is not pretty but it gets the information needed from the private registry.

Example of output from view-private-registry:

$ view-private-registry`
busybox:latest
gcr.io/google_containers/etcd:2.0.9
gcr.io/google_containers/hyperkube:v0.21.2
gcr.io/google_containers/pause:0.8.0
google/cadvisor:latest
jenkins:latest
logstash:latest
mongo:latest
nginx:latest
python:2.7
redis:latest
registry:2.1.1
stackengine/controller:latest
tomcat:7
tomcat:latest
ubuntu:14.04.2
Number of images:   16
Disk space used:    1.7G    /mnt/three/docker-registry/registry-data

How can I move all the files from one folder to another using the command line?

use move then move <file or folder> <destination directory>

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink], then it should be assigned a name of the property the value of which will be the route it should navigate the user to.

So to fix your issue, replace this routerLink="['/about']" with routerLink="/about" in your HTML.

There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:

<nav class="main-nav>
  <ul 
    class="main-nav__list" 
    ng-sticky 
    addClass="main-sticky-link" 
    [ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
    <li class="main-nav__item" routerLinkActive="active">
      <a class="main-nav__link" routerLink="/">Home</a>
    </li>
    <li class="main-nav__item" routerLinkActive="active"> 
      <a class="main-nav__link" routerLink="/about">About us</a>
    </li>
  </ul>
</nav>

It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>, either in your template provided above or in a parent component.

There's another issue with your AppRoutingModule. You need to export the RouterModule from there so that it is available to your AppModule when it imports it. To fix that, export it from your AppRoutingModule by adding it to the exports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'what', component: WhatwedoComponent },
  { path: 'contacts', component: FooterComponent },
  { path: 'projects', component: ProjectsComponent},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

How do I get LaTeX to hyphenate a word that contains a dash?

multi-disciplinary will not be hyphenated, as explained by kennytm. But multi-\-disciplinary has the same hyphenation opportunities that multidisciplinary has.

I admit that I don't know why this works. It is different from the behaviour described here (emphasis mine):

The command \- inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word.

PHP array delete by value (not key)

I know this is not efficient at all but is simple, intuitive and easy to read.
So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:

$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);

foreach($arr as $key =>$value){
    if ($value !== $del_value){
        $result[$key] = $value;
    }

    //if(!in_array($value, $del_values)){
    //    $result[$key] = $value;
    //}

    //if($this->validete($value)){
    //      $result[$key] = $value;
    //}
}

return $result

android - How to get view from context?

For example you can find any textView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);

How to set a primary key in MongoDB?

One way of achieving this behaviour is by setting the value to _id (which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id as the primary key then at the time of creating document in MongoDB; assign _id value same as that of employee_id.

Multiline string literal in C#

Add multiple lines : use @

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

Add String Values to the middle : use $

string text ="beer";
string query = $"SELECT foo {text} bar ";

Multiple line string Add Values to the middle: use $@

string text ="Customer";
string query = $@"SELECT foo, bar
FROM {text}Table
WHERE id = 42";

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I came across this problem when building QT. The instructions I read somewhere suggested that I configure nmake using VS command prompt.

I chose the x64 command prompt and performed configure without much hassle. When i tried nmake, it gave this error.

I think some of the components were pre-built for 32-bit. The error even reported which modules were built for x86.

I used the 32 bit default VS command prompt and it worked.

Get keys from HashMap in Java

As you would like to get argument (United) for which value is given (5) you might also consider using bidirectional map (e.g. provided by Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html).

How to do what head, tail, more, less, sed do in Powershell?

$Push_Pop = $ErrorActionPreference #Suppresses errors
$ErrorActionPreference = “SilentlyContinue” #Suppresses errors
#Script
    #gc .\output\*.csv -ReadCount 5 | %{$_;throw "pipeline end!"} # head
    #gc .\output\*.csv | %{$num=0;}{$num++;"$num $_"}             # cat -n
    gc .\output\*.csv | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
#End Script 
$ErrorActionPreference = $Push_Pop #Suppresses errors

You don't get all the errors with the pushpop code BTW, your code only works with the "sed" option. All the rest ignores anything but gc and path.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).

This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id on a OneToOne or ManyToOne. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn and also define a Basic Id mapping for the foreign key column.

Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?

You can obtain a similar result but using an Id on OneToOne or ManyToOne is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:

11.1.40 PrimaryKeyJoinColumn Annotation

The PrimaryKeyJoinColumn annotation specifies a primary key column that is used as a foreign key to join to another table.

The PrimaryKeyJoinColumn annotation is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108].

...

If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.

...

Example: Customer and ValuedCustomer subclass

@Entity
@Table(name="CUST")
@Inheritance(strategy=JOINED)
@DiscriminatorValue("CUST")
public class Customer { ... }

@Entity
@Table(name="VCUST")
@DiscriminatorValue("VCUST")
@PrimaryKeyJoinColumn(name="CUST_ID")
public class ValuedCustomer extends Customer { ... }

[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over PrimaryKeyJoinColumn for the OneToOne mapping case.

See also


This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?

The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.

For the record, support of Id on OneToOne and ManyToOne has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.

Safely limiting Ansible playbooks to a single machine?

We have some generic playbooks that are usable by a large number of teams. We also have environment specific inventory files, that contain multiple group declarations.

To force someone calling a playbook to specify a group to run against, we seed a dummy entry at the top of the playbook:

[ansible-dummy-group]
dummy-server

We then include the following check as a first step in the shared playbook:

- hosts: all
  gather_facts: False
  run_once: true
  tasks:
  - fail:
      msg: "Please specify a group to run this playbook against"
    when: '"dummy-server" in ansible_play_batch'

If the dummy-server shows up in the list of hosts this playbook is scheduled to run against (ansible_play_batch), then the caller didn't specify a group and the playbook execution will fail.

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

CakePHP find method with JOIN

        $services = $this->Service->find('all', array(
            'limit' =>4,
            'fields' => array('Service.*','ServiceImage.*'),
            'joins' => array(
                array(
                        'table' => 'services_images',
                        'alias' => 'ServiceImage',
                        'type' => 'INNER',
                        'conditions' => array(
                        'ServiceImage.service_id' =>'Service.id'
                        )
                    ),
                ),
            )
        );

It goges to array is null.

How to implement authenticated routes in React Router 4?

install react-router-dom

then create two components one for valid users and other for invalid users.

try this on app.js

import React from 'react';

import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';

import ValidUser from "./pages/validUser/validUser";
import InValidUser from "./pages/invalidUser/invalidUser";
const loggedin = false;

class App extends React.Component {
 render() {
    return ( 
      <Router>
      <div>
        <Route exact path="/" render={() =>(
          loggedin ? ( <Route  component={ValidUser} />)
          : (<Route component={InValidUser} />)
        )} />

        </div>
      </Router>
    )
  }
}
export default App;

How to build PDF file from binary string returned from a web-service using javascript

I work in PHP and use a function to decode the binary data sent back from the server. I extract the information an input to a simple file.php and view the file through my server and all browser display the pdf artefact.

<?php
   $data = 'dfjhdfjhdfjhdfjhjhdfjhdfjhdfjhdfdfjhdf==blah...blah...blah..'

   $data = base64_decode($data);
    header("Content-type: application/pdf");
    header("Content-Length:" . strlen($data ));
    header("Content-Disposition: inline; filename=label.pdf");
    print $data;
    exit(1);

?>

How to use WHERE IN with Doctrine 2

and for completion the string solution

$qb->andWhere('foo.field IN (:string)');
$qb->setParameter('string', array('foo', 'bar'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);

More elegant way of declaring multiple variables at the same time

I like the top voted answer; however, it has problems with list as shown.

  >> a, b = ([0]*5,)*2
  >> print b
  [0, 0, 0, 0, 0]
  >> a[0] = 1
  >> print b
  [1, 0, 0, 0, 0]

This is discussed in great details (here), but the gist is that a and b are the same object with a is b returning True (same for id(a) == id(b)). Therefore if you change an index, you are changing the index of both a and b, since they are linked. To solve this you can do (source)

>> a, b = ([0]*5 for i in range(2))
>> print b
[0, 0, 0, 0, 0]
>> a[0] = 1
>> print b
[0, 0, 0, 0, 0]

This can then be used as a variant of the top answer, which has the "desired" intuitive results

>> a, b, c, d, e, g, h, i = (True for i in range(9))
>> f = (False for i in range(1)) #to be pedantic

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

How to switch between hide and view password

It is really easy to achieve since the Support Library v24.2.0.

What you need to do is just:

  1. Add the design library to your dependecies

    dependencies {
         compile "com.android.support:design:24.2.0"
    }
    
  2. Use TextInputEditText in conjunction with TextInputLayout

    <android.support.design.widget.TextInputLayout
        android:id="@+id/etPasswordLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true"
        android:layout_marginBottom="@dimen/login_spacing_bottom">
    
        <android.support.design.widget.TextInputEditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/fragment_login_password_hint"
            android:inputType="textPassword"/>
    </android.support.design.widget.TextInputLayout>
    

The passwordToggleEnabled attribute will do the job!

  1. In your root layout don't forget to add xmlns:app="http://schemas.android.com/apk/res-auto"

  2. You can customize your password toggle by using:

app:passwordToggleDrawable - Drawable to use as the password input visibility toggle icon.
app:passwordToggleTint - Icon to use for the password input visibility toggle.
app:passwordToggleTintMode - Blending mode used to apply the background tint.

More details in TextInputLayout documentation.

enter image description here

For AndroidX

  • Replace android.support.design.widget.TextInputLayout with com.google.android.material.textfield.TextInputLayout

  • Replace android.support.design.widget.TextInputEditText with com.google.android.material.textfield.TextInputEditText

How to apply a function to two columns of Pandas dataframe

The method you are looking for is Series.combine. However, it seems some care has to be taken around datatypes. In your example, you would (as I did when testing the answer) naively call

df['col_3'] = df.col_1.combine(df.col_2, func=get_sublist)

However, this throws the error:

ValueError: setting an array element with a sequence.

My best guess is that it seems to expect the result to be of the same type as the series calling the method (df.col_1 here). However, the following works:

df['col_3'] = df.col_1.astype(object).combine(df.col_2, func=get_sublist)

df

   ID   col_1   col_2   col_3
0   1   0   1   [a, b]
1   2   2   4   [c, d, e]
2   3   3   5   [d, e, f]

mongodb how to get max value from collections

For max value, we can write sql query as

select age from table_name order by age desc limit 1

same way we can write in mongodb too.

db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age

Jenkins: Failed to connect to repository

In my case I resolved this issue by

  • clicking button Add which is next to the "Credentials" text
  • adding credentials (login and password)
  • selecting these credentials on the popup menu, which is on the left of the Add button
  • waiting for a couple of seconds

My environment was Jenkins installed in the Windows. The UI question was why the warning was placed before the tool to resolve it.

trying to align html button at the center of the my page

You can center a button without using text-align on the parent div by simple using margin:auto; display:block;

For example:

HTML

<div>
  <button>Submit</button>
</div>

CSS

button {
  margin:auto;
  display:block;
}

SEE IT IN ACTION: CodePen

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

The insert or replace query would insert a new record if id=1 does not already exist.

The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.

Best Way to read rss feed in .net Using C#

This is an old post, but to save people some time if you get here now like I did, I suggest you have a look at the CodeHollow.FeedReader package which supports a wider range of RSS versions, is easier to use and seems more robust. https://github.com/codehollow/FeedReader

Deserializing a JSON file with JavaScriptSerializer()

Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:

string s = //{ "user" : {    "id" : 12345,    "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);

You'll get back something, where you can do:

var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.

Look at result in the debugger to see, what's in there.

How to display multiple notifications in android

notificationManager.notify(0, notification);

Put this code instead of 0

new Random().nextInt() 

Like below it works for me

notificationManager.notify(new Random().nextInt(), notification);

How to perform Join between multiple tables in LINQ lambda

 public ActionResult Index()
    {
        List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();

       var  orderlist = (from a in db.OrderMasters
                         join b in db.Customers on a.CustomerId equals b.Id
                         join c in db.CustomerAddresses on b.Id equals c.CustomerId
                         where a.Status == "Pending"
                         select new
                         {
                             Customername = b.Customername,
                             Phone = b.Phone,
                             OrderId = a.OrderId,
                             OrderDate = a.OrderDate,
                             NoOfItems = a.NoOfItems,
                             Order_amt = a.Order_amt,
                             dis_amt = a.Dis_amt,
                             net_amt = a.Net_amt,
                             status=a.Status,  
                             address = c.address,
                             City = c.City,
                             State = c.State,
                             Pin = c.Pin

                         }) ;
       foreach (var item in orderlist)
       {

           CustomerOrder_Result clr = new CustomerOrder_Result();
           clr.Customername=item.Customername;
           clr.Phone = item.Phone;
           clr.OrderId = item.OrderId;
           clr.OrderDate = item.OrderDate;
           clr.NoOfItems = item.NoOfItems;
           clr.Order_amt = item.Order_amt;
           clr.net_amt = item.net_amt;
           clr.address = item.address;
           clr.City = item.City;
           clr.State = item.State;
           clr.Pin = item.Pin;
           clr.status = item.status;

           obj.Add(clr);



       }

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

JavaScript alert not working in Android WebView

You can try with this, it worked for me

WebView wb_previewSurvey=new WebView(this); 


       wb_previewSurvey.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            //Required functionality here
            return super.onJsAlert(view, url, message, result);
        }

    });

How do I put my website's logo to be the icon image in browser tabs?

This is the favicon and is explained in the link.

e.g. from W3C

  <link rel="icon" 
     type="image/png" 
     href="http://example.com/myicon.png">

Plus, of course the image file in the appropriate place.

iPad WebApp Full Screen in Safari

Looks like most of the answers on this thread have not kept up. iOS Safari on iPads have fullscreen support now and it's very easy to implement using javascript.

Here's my full article on how to implement fullscreen capability on your web app.

can't access mysql from command line mac

On OSX 10.11, you can sudo nano /etc/paths and add the path(s) you want here, one per line. Way simpler than figuring which of ~/.bashrc, /etc/profile, '~/.bash_profile` etc... you should add to. Besides, why export and append $PATH to itself when you can just go and modify PATH directly...?

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

I changed continue to continue 2 on line 1579 in shortcodeComon.php and it fixed my problem

   if(trim($custom_link[$i]) == ""){

           continue;

    }

Change to:

  if(trim($custom_link[$i]) == ""){

             continue 2;

   }

Can't operator == be applied to generic types in C#?

As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types.

Instead of calling Equals, it's better to use an IComparer<T> - and if you have no more information, EqualityComparer<T>.Default is a good choice:

public bool Compare<T>(T x, T y)
{
    return EqualityComparer<T>.Default.Equals(x, y);
}

Aside from anything else, this avoids boxing/casting.

How to Split Image Into Multiple Pieces in Python

As an alternative to other solutions, we will construct the tiles by generating a grid of coordinates using itertools.product. We will ignore partial tiles on the edges, only iterating through the Cartesian product between the two intervals, i.e. range(0, h-h%d, d) X range(0, w-w%d, d).

Given fp: the file name to the image, d: the tile size, opt.path: the path to the directory containing the images, and opt.out: is the directory where tiles will be outputted:

def tile(filename, dir_in, dir_out, d):
    name, ext = os.path.splitext(filename)
    img = Image.open(os.path.join(dir_in, fp))
    w, h = img.size
    
    grid = list(product(range(0, h-h%d, d), range(0, w-w%d, d)))
    for i, j in grid:
        box = (j, i, j+d, i+d)
        out = os.path.join(dir_out, f'{name}_{i}_{j}{ext}')
        img.crop(box).save(out)

enter image description here

Create ArrayList from array

According with the question the answer using java 1.7 is:

ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));

However it's better always use the interface:

List<Element> arraylist = Arrays.<Element>asList(array);

Codeigniter - multiple database connections

You should provide the second database information in `application/config/database.php´

Normally, you would set the default database group, like so:

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Notice that the login information and settings are provided in the array named $db['default'].

You can then add another database in a new array - let's call it 'otherdb'.

$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

Now, to actually use the second database, you have to send the connection to another variabel that you can use in your model:

function my_model_method()
{
  $otherdb = $this->load->database('otherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.

  $query = $otherdb->select('first_name, last_name')->get('person');
  var_dump($query);
}

That should do it. The documentation for connecting to multiple databases can be found here: http://codeigniter.com/user_guide/database/connecting.html

LaTeX table positioning

If you want to have two tables next to each other you can use: (with float package loaded)

\begin{table}[H]
 \begin{minipage}{.5\textwidth}
  %first table
 \end{minipage}
 \begin{minipage}{.5\textwidth}
  %second table
 \end{minipage}
\end{table}

Each one will have own caption and number. Another option is subfigure package.

Is it possible to install another version of Python to Virtualenv?

Pre-requisites:

  1. sudo easy_install virtualenv
  2. sudo pip install virtualenvwrapper

Installing virtualenv with Python2.6:

  1. You could manually download, build and install another version of Python to /usr/local or another location.

  2. If it's another location other than /usr/local, add it to your PATH.

  3. Reload your shell to pick up the updated PATH.

  4. From this point on, you should be able to call the following 2 python binaries from your shell python2.5 and python2.6

  5. Create a new instance of virtualenv with python2.6:

    mkvirtualenv --python=python2.6 yournewenv

JQuery DatePicker ReadOnly

<sj:datepicker id="datepickerid" name="datepickername" displayFormat="%{formatDateJsp}" readonly="true"/>

Works for me.

Comparing mongoose _id and strings

converting object id to string(using toString() method) will do the job.

How to execute my SQL query in CodeIgniter

If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:

$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");

Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.

Illegal mix of collations MySQL Error

I found that using cast() was the best solution for me:

cast(Format(amount, "Standard") AS CHAR CHARACTER SET utf8) AS Amount

There is also a convert() function. More details on it here

Another resource here

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

If you need only one upper case and special character then this should work:

@"^(?=.{8,}$)(?=[^A-Z]*[A-Z][^A-Z]*$)\w*\W\w*$"

Proxy with urllib2

proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

How to add a list item to an existing unordered list?

This is another one

$("#header ul li").last().html('<li> Menu 5 </li>');

How to store printStackTrace into a string

You have to use getStackTrace () method instead of printStackTrace(). Here is a good example:

import java.io.*;

/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {

  public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }

  /**
  * Defines a custom format for the stack trace as String.
  */
  public static String getCustomStackTrace(Throwable aThrowable) {
    //add the class name and any message passed to constructor
    final StringBuilder result = new StringBuilder( "BOO-BOO: " );
    result.append(aThrowable.toString());
    final String NEW_LINE = System.getProperty("line.separator");
    result.append(NEW_LINE);

    //add each element of the stack trace
    for (StackTraceElement element : aThrowable.getStackTrace() ){
      result.append( element );
      result.append( NEW_LINE );
    }
    return result.toString();
  }

  /** Demonstrate output.  */
  public static void main (String... aArguments){
    final Throwable throwable = new IllegalArgumentException("Blah");
    System.out.println( getStackTrace(throwable) );
    System.out.println( getCustomStackTrace(throwable) );
  }
} 

Get url parameters from a string in .NET

You can use the following workaround for it to work with the first parameter too:

var param1 =
    HttpUtility.ParseQueryString(url.Substring(
        new []{0, url.IndexOf('?')}.Max()
    )).Get("param1");

difference between primary key and unique key

Difference between Primary Key and Unique Key

+-----------------------------------------+-----------------------------------------------+
|                Primary Key              |                    Unique Key                 |
+-----------------------------------------+-----------------------------------------------+
| Primary Key can't accept null values.   | Unique key can accept only one null value.    |
+-----------------------------------------+-----------------------------------------------+
| By default, Primary key is clustered    | By default, Unique key is a unique            |
| index and data in the database table is | non-clustered index.                          |
| physically organized in the sequence of |                                               |
| clustered index.                        |                                               |
+-----------------------------------------+-----------------------------------------------+
| We can have only one Primary key in a   | We can have more than one unique key in a     |
| table.                                  | table.                                        |
+-----------------------------------------+-----------------------------------------------+
| Primary key can be made foreign key     | In SQL Server, Unique key can be made foreign |
| into another table.                     | key into another table.                       |
+-----------------------------------------+-----------------------------------------------+

You can find detailed information from:
http://www.dotnet-tricks.com/Tutorial/sqlserver/V2bS260912-Difference-between-Primary-Key-and-Unique-Key.html

Get value of Span Text

The accepted answer is close... but no cigar!

Use textContent instead of innerHTML if you strictly want a string to be returned to you.

innerHTML can have the side effect of giving you a node element if there's other dom elements in there. textContent will guard against this possibility.

No matching bean of type ... found for dependency

In my case it was the wrong dependecy for CrudRepository. My IDE added also follwing:

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.11.2.RELEASE</version>
    </dependency>

But I just needed:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>RELEASE</version>
    </dependency>

I removed the first one and everything was fine.

Parsing JSON object in PHP using json_decode

Seems like you forgot the ["value"] or ->value:

echo $data[0]->weather->weatherIconUrl[0]->value;

Creating a BAT file for python script

--- xxx.bat ---

@echo off
set NAME1="Marc"
set NAME2="Travis"
py -u "CheckFile.py" %NAME1% %NAME2%
echo %ERRORLEVEL%
pause

--- yyy.py ---

import sys
import os
def names(f1,f2):

    print (f1)
    print (f2)
    res= True
    if f1 == "Travis":
         res= False
    return res

if __name__ == "__main__":
     a = sys.argv[1]
     b = sys.argv[2]
     c = names(a, b) 
     if c:
        sys.exit(1)
    else:
        sys.exit(0)        

Get environment value in controller

In the book of Matt Stauffer he suggest to create an array in your config/app.php to add the variable and then anywhere you reference to it with:

$myvariable = new Namearray(config('fileWhichContainsVariable.array.ConfigKeyVariable'))

Have try this solution? is good ?

How to check if an element is off-screen

You could check the position of the div using $(div).position() and check if the left and top margin properties are less than 0 :

if($(div).position().left < 0 && $(div).position().top < 0){
    alert("off screen");
}

Java for loop syntax: "for (T obj : objects)"

Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.

for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }

Getting pids from ps -ef |grep keyword

To kill a process by a specific keyword you could create an alias in ~/.bashrc (linux) or ~/.bash_profile (mac).

alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"

Rotating a Div Element in jQuery

Cross-browser rotate for any element. Works in IE7 and IE8. In IE7 it looks like not working in JSFiddle but in my project worked also in IE7

http://jsfiddle.net/RgX86/24/

var elementToRotate = $('#rotateMe');
var degreeOfRotation = 33;

var deg = degreeOfRotation;
var deg2radians = Math.PI * 2 / 360;
var rad = deg * deg2radians ;
var costheta = Math.cos(rad);
var sintheta = Math.sin(rad);

var m11 = costheta;
var m12 = -sintheta;
var m21 = sintheta;
var m22 = costheta;
var matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;

elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
    .css('-moz-transform','rotate('+deg+'deg)')
    .css('-ms-transform','rotate('+deg+'deg)')
    .css('transform','rotate('+deg+'deg)')
    .css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
    .css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');

Edit 13/09/13 15:00 Wrapped in a nice and easy, chainable, jquery plugin.

Example of use

$.fn.rotateElement = function(angle) {
    var elementToRotate = this,
        deg = angle,
        deg2radians = Math.PI * 2 / 360,
        rad = deg * deg2radians ,
        costheta = Math.cos(rad),
        sintheta = Math.sin(rad),

        m11 = costheta,
        m12 = -sintheta,
        m21 = sintheta,
        m22 = costheta,
        matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;

    elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
        .css('-moz-transform','rotate('+deg+'deg)')
        .css('-ms-transform','rotate('+deg+'deg)')
        .css('transform','rotate('+deg+'deg)')
        .css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
        .css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');
    return elementToRotate;
}

$element.rotateElement(15);

JSFiddle: http://jsfiddle.net/RgX86/175/

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

jQuery "on create" event for dynamically-created elements

One way, which seems reliable (though tested only in Firefox and Chrome) is to use JavaScript to listen for the animationend (or its camelCased, and prefixed, sibling animationEnd) event, and apply a short-lived (in the demo 0.01 second) animation to the element-type you plan to add. This, of course, is not an onCreate event, but approximates (in compliant browsers) an onInsertion type of event; the following is a proof-of-concept:

$(document).on('webkitAnimationEnd animationend MSAnimationEnd oanimationend', function(e){
    var eTarget = e.target;
    console.log(eTarget.tagName.toLowerCase() + ' added to ' + eTarget.parentNode.tagName.toLowerCase());
    $(eTarget).draggable(); // or whatever other method you'd prefer
});

With the following HTML:

<div class="wrapper">
    <button class="add">add a div element</button>
</div>

And (abbreviated, prefixed-versions-removed though present in the Fiddle, below) CSS:

/* vendor-prefixed alternatives removed for brevity */
@keyframes added {
    0% {
        color: #fff;
    }
}

div {
    color: #000;
    /* vendor-prefixed properties removed for brevity */
    animation: added 0.01s linear;
    animation-iteration-count: 1;
}

JS Fiddle demo.

Obviously the CSS can be adjusted to suit the placement of the relevant elements, as well as the selector used in the jQuery (it should really be as close to the point of insertion as possible).

Documentation of the event-names:

Mozilla   |  animationend
Microsoft |  MSAnimationEnd
Opera     |  oanimationend
Webkit    |  webkitAnimationEnd
W3C       |  animationend

References:

Windows batch file file download from a URL

' Create an HTTP object
myURL = "http://www.google.com"
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )

' Download the specified URL
objHTTP.Open "GET", myURL, False
objHTTP.Send
intStatus = objHTTP.Status

If intStatus = 200 Then
  WScript.Echo " " & intStatus & " A OK " +myURL
Else
  WScript.Echo "OOPS" +myURL
End If

then

C:\>cscript geturl.vbs
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.

200 A OK http://www.google.com

or just double click it to test in windows

Node Version Manager install - nvm command not found

First add following lines in ~/.bashrc file

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

then open terminal and source the nvm.sh script

source ~/.nvm/nvm.sh

SQL Server Management Studio missing

Did you include "Management Tools" as a chosen option during setup?

enter image description here

Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.

Getting the last argument passed to a shell script

There is a much more concise way to do this. Arguments to a bash script can be brought into an array, which makes dealing with the elements much simpler. The script below will always print the last argument passed to a script.

  argArray=( "$@" )                        # Add all script arguments to argArray
  arrayLength=${#argArray[@]}              # Get the length of the array
  lastArg=$((arrayLength - 1))             # Arrays are zero based, so last arg is -1
  echo ${argArray[$lastArg]}

Sample output

$ ./lastarg.sh 1 2 buckle my shoe
shoe

no pg_hba.conf entry for host

In your pg_hba.conf file, I see some incorrect and confusing lines:

# fine, this allows all dbs, all users, to be trusted from 192.168.0.1/32
# not recommend because of the lax permissions
host    all        all         192.168.0.1/32        trust

# wrong, /128 is an invalid netmask for ipv4, this line should be removed
host    all        all         192.168.0.1/128       trust

# this conflicts with the first line
# it says that that the password should be md5 and not plaintext
# I think the first line should be removed
host    all        all         192.168.0.1/32        md5

# this is fine except is it unnecessary because of the previous line
# which allows any user and any database to connect with md5 password
host    chaosLRdb  postgres    192.168.0.1/32        md5

# wrong, on local lines, an IP cannot be specified
# remove the 4th column
local   all        all         192.168.0.1/32        trust

I suspect that if you md5'd the password, this might work if you trim the lines. To get the md5 you can use perl or the following shell script:

 echo -n 'chaos123' | md5sum
 > d6766c33ba6cf0bb249b37151b068f10  -

So then your connect line would like something like:

my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433",
    "chaosuser", "d6766c33ba6cf0bb249b37151b068f10");

For more information, here's the documentation of postgres 8.X's pg_hba.conf file.

MySql export schema without data

Add the --routines and --events options to also include stored routine and event definitions

mysqldump -u <user> -p --no-data --routines --events test > dump-defs.sql

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

FWIW, on Ubuntu 10.04.2 LTS installing the ca-certificates-java and the ca-certificates packages fixed this problem for me.

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.

iPad/iPhone hover problem causes the user to double click a link

Simply make a CSS media query which excludes tablets and mobile devices and put the hover in there. You don't really need jQuery or JavaScript for this.

@media screen and (min-device-width:1024px) {
    your-element:hover {
        /* Do whatever here */
    }
}

And be sure to add this to your html head to make sure that it calculates with the actual pixels and not the resolution.

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

You can uninstall package name "com.example" from the device in which you run the app after than you run the app . This worked for me

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

add the following to the "floating" view

position: 'absolute'

you may also need to add a top and left value for positioning

see this example: https://rnplay.org/apps/OjzcxQ/edit

Send data from activity to fragment in Android

My solution is to write a static method inside the fragment:

public TheFragment setData(TheData data) {
    TheFragment tf = new TheFragment();
    tf.data = data;
    return tf;
}

This way I am sure that all the data I need is inside the Fragment before any other possible operation which could need to work with it. Also it looks cleaner in my opinion.

Access key value from Web.config in Razor View-MVC3 ASP.NET

The preferred method is actually:

@System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"]

It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.

XAMPP on Windows - Apache not starting

I had my Apache service not start same as MySQL one. Please follow these steps if none of above tips works :

  1. Open regedit.exe on any windows this available . Run as administrator. (Only on windows 7 and later editions )
    1. Go to local machine/system/controlset001/services
    2. Find and delete folders of services apache and mysql .
    3. Uninstall xampp . Delete folder of xampp.
    4. Restart computer and reinstall Xampp . After that your Xampp apache and Mysql should work.

Note: Ports 80 and 443 must be unused by any program. 
      If it is in use . Just edit ports. There is a lot of tutorials about that .

VB.NET Switch Statement GoTo Case

Select Case parameter 
    ' does something here. 
    ' does something here. 
    Case "userID", "packageID", "mvrType" 
        If otherFactor Then 
            ' does something here. 
        Else 
            goto case default 
        End If 
    Case Else 
        ' does some processing... 
        Exit Select 
End Select

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

If you are having a code structure of something like:

SELECT 151
RETURN -151

Then use:

SELECT 151
ROLLBACK
RETURN -151

Android ADB doesn't see device

I had same issue, none of the solutions worked for me.

Open Settings Menu -> Developer Options -> USB Debugging should be on

How do I set the colour of a label (coloured text) in Java?

One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)

gui_en.properties:

title.text=<html>Text color: <font color='red'>red</font></html>

gui_fr.properties:

title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>

gui_ru.properties:

title.text=<html>???? ??????: <font color='red'>???????</font></html>

Bootstrap Accordion button toggle "data-parent" not working

As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:

$('#your-parent .collapse').on('show.bs.collapse', function (e) {
    var actives = $('#your-parent').find('.in, .collapsing');
    actives.each( function (index, element) {
        $(element).collapse('hide');
    })
})

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

JSON date to Java date?

If you need to support more than one format you will have to pattern match your input and parse accordingly.

final DateFormat fmt;
if (dateString.endsWith("Z")) {
    fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
} else {
    fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
}

I'd guess you're dealing with a bug in the API you're using which has quoted the Z timezone date pattern somewhere...

How do detect Android Tablets in general. Useragent?

Based on Agents strings on this site:

http://www.webapps-online.com/online-tools/user-agent-strings

This results came up:
First:

All Tablet Devices have:
1. Tablet
2. iPad

Second:

All Phone Devices have:
1. Mobile
2. Phone

Third:

Tablet and Phone Devices have:
1. Android

If you can detect level by level, I thing the result is 90 percent true. Like SharePoint Device Channels.

How to check if current thread is not main thread

You can check

if(Looper.myLooper() == Looper.getMainLooper()) {
   // You are on mainThread 
}else{
// you are on non-ui thread
}

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

// aspx.cs

// Load CheckBoxList selected items into ListBox

    int status = 1;
    foreach (ListItem  s in chklstStates.Items  )
    {
        if (s.Selected == true)
        {
            if (ListBox1.Items.Count == 0)
            {
                ListBox1.Items.Add(s.Text);

            }
            else
            {
                foreach (ListItem list in ListBox1.Items)
                {
                    if (list.Text == s.Text)
                    {
                        status = status * 0;

                    }
                    else
                    {
                        status = status * 1;
                    }
                }
                if (status == 0)
                { }
               else
                {
                    ListBox1.Items.Add(s.Text);
                }
                status = 1;
            }
        }
    }
}

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

If you are using the local server, run Django shell using python manage.py shell. It will take you to the Django python environment and you are good to go.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

Array versus List<T>: When to use which?

Since no one mention: In C#, an array is a list. MyClass[] and List<MyClass> both implement IList<MyClass>. (e.g. void Foo(IList<int> foo) can be called like Foo(new[] { 1, 2, 3 }) or Foo(new List<int> { 1, 2, 3 }) )

So, if you are writing a method that accepts a List<MyClass> as an argument, but uses only subset of features, you may want to declare as IList<MyClass> instead for callers' convenience.

Details:

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Even after enabling Intel Virtualization Technology (Intel VT-x), I got the error message ' dev/kvm not found ' in Android Studio.by making Hyper-V feature off in Windows 8.1 issue was fixed.

here is how to access Windows Hyper-V feature

Control Panel -> Programs and Features -> Turn Windows features on and off.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.

I'd prefer to use OneJar for this issue.

Is there a simple way to delete a list element by value?

If your elements are distinct, then a simple set difference will do.

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]

frequent issues arising in android view, Error parsing XML: unbound prefix

A couple of reasons that this can happen:

1) You see this error with an incorrect namespace, or a typo in the attribute. Like 'xmlns' is wrong, it should be xmlns:android

2) First node needs to contain: xmlns:android="http://schemas.android.com/apk/res/android"

3) If you are integrating AdMob, check custom parameters like ads:adSize, you need

xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"

4) If you are using LinearLayout you might have to define tools:

xmlns:tools="http://schemas.android.com/tools"

Delete element in a slice

... is syntax for variadic arguments.

I think it is implemented by the complier using slice ([]Type), just like the function append :

func append(slice []Type, elems ...Type) []Type

when you use "elems" in "append", actually it is a slice([]type). So "a = append(a[:0], a[1:]...)" means "a = append(a[0:0], a[1:])"

a[0:0] is a slice which has nothing

a[1:] is "Hello2 Hello3"

This is how it works

Open Redis port for remote connections

Bind & protected-mode both are the essential steps. But if ufw is enabled then you will have to make redis port allow in ufw.

  1. Check ufw status ufw status if Status: active then allow redis-port ufw allow 6379
  2. vi /etc/redis/redis.conf
  3. Change the bind 127.0.0.1 to bind 0.0.0.0
  4. change the protected-mode yes to protected-mode no

Android: checkbox listener

you may also go for a simple View.OnClickListener:

satView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(((CompoundButton) view).isChecked()){
            System.out.println("Checked");
        } else {
            System.out.println("Un-Checked");
        }
    }
});

What happens to a declared, uninitialized variable in C? Does it have a value?

The Value of num will be some garbage value from the main memory(RAM). its better if you initialize the variable just after creating.

Best C# API to create PDF

I used PdfSharp. It's free, open source and quite convenient to use, but I can't say whether it is the best or not, because I haven't really used anything else.

SQL Query Where Date = Today Minus 7 Days

Using dateadd to remove a week from the current date.

datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()

Ignoring SSL certificate in Apache HttpClient 4.3

If you are using PoolingHttpClientConnectionManager procedure above doesn't work, custom SSLContext is ignored. You have to pass socketFactoryRegistry in contructor when creating PoolingHttpClientConnectionManager.

SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
    @Override
    public boolean isTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        return true;
    }
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext, new X509HostnameVerifier() {
            @Override
            public void verify(String host, SSLSocket ssl)
                    throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert)
                    throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns,
                    String[] subjectAlts) throws SSLException {
            }

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });

Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
        .<ConnectionSocketFactory> create().register("https", sslsf)
        .build();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
        socketFactoryRegistry);
CloseableHttpClient httpclient = HttpClients.custom()
        .setConnectionManager(cm).build();

Hashmap with Streams in Java 8 Streams to collect value of Map

What you need to do is create a Stream out of the Map's .entrySet():

// Map<K, V> --> Set<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
map.entrySet().stream()

From the on, you can .filter() over these entries. For instance:

// Stream<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
.filter(entry -> entry.getKey() == 1)

And to obtain the values from it you .map():

// Stream<Map.Entry<K, V>> --> Stream<V>
.map(Map.Entry::getValue)

Finally, you need to collect into a List:

// Stream<V> --> List<V>
.collect(Collectors.toList())

If you have only one entry, use this instead (NOTE: this code assumes that there is a value; otherwise, use .orElse(); see the javadoc of Optional for more details):

// Stream<V> --> Optional<V> --> V
.findFirst().get()

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Find index of a value in an array

If you want to find the word you can use

var word = words.Where(item => item.IsKey).First();

This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()

To get both the item and the index you can use

KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();

Fatal error: Call to undefined function mysqli_connect()

Mine was a bit different for php7 on centos7.

In /etc/php.ini

; extension=mysqli

to

extension=mysqli

How to add some non-standard font to a website?

Typeface.js and Cufon are two other interesting options. They are JavaScript components that render special font data in JSON format (which you can convert from TrueType or OpenType formats on their web sites) via the new <canvas> element in all newer browsers except Internet Explorer and via VML in Internet Explorer.

The main problem with both (as of now) is that selecting text does not work or at least works only quite awkwardly.

Still, it is very nice for headlines. Body text... I don't know.

And it's surprisingly fast.

Call function with setInterval in jQuery?

To write the best code, you "should" use the latter approach, with a function reference:

var refreshId = setInterval(function() {}, 5000);

or

function test() {}
var refreshId = setInterval(test, 5000);

but your approach of

function test() {}
var refreshId = setInterval("test()", 5000);

is basically valid, too (as long as test() is global).

Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.

How to fix the height of a <div> element?

You can try max-height: 70px; See if that works.

html5 audio player - jquery toggle click play/pause?

I'm not sure why, but I needed to use the old skool document.getElementById();

<audio id="player" src="http://audio.micronemez.com:8000/micronemez-radio.ogg"> </audio>
<a id="button" title="button">play sound</a>

and the JS:

$(document).ready(function() {
  var playing = false;

  $('a#button').click(function() {
      $(this).toggleClass("down");

      if (playing == false) {
          document.getElementById('player').play();
          playing = true;
          $(this).text("stop sound");

      } else {
        document.getElementById('player').pause();
        playing = false;
        $(this).text("restart sound");
      }

  });
});

Check out an example: http://jsfiddle.net/HY9ns/1/

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

is will compare the memory location. It is used for object-level comparison.

== will compare the variables in the program. It is used for checking at a value level.

is checks for address level equivalence

== checks for value level equivalence

Finding the type of an object in C++

Your description is a little confusing.

Generally speaking, though some C++ implementations have mechanisms for it, you're not supposed to ask about the type. Instead, you are supposed to do a dynamic_cast on the pointer to A. What this will do is that at runtime, the actual contents of the pointer to A will be checked. If you have a B, you'll get your pointer to B. Otherwise, you'll get an exception or null.

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Is it acceptable and safe to run pip install under sudo?

Because I had the same problem, I want to stress that actually the first comment by Brian Cain is the solution to the "IOError: [Errno 13]"-problem:

If executed in the temp directory (cd /tmp), the IOError does not occur anymore if I run sudo pip install foo.

OS X: equivalent of Linux's wget

wget Precompiled Mac Binary

For those looking for a quick wget install on Mac, check out Quentin Stafford-Fraser's precompiled binary here, which has been around for over a decade:

https://statusq.org/archives/2008/07/30/1954/

MD5 for 2008 wget.zip: 24a35d499704eecedd09e0dd52175582
MD5 for 2005 wget.zip: c7b48ec3ff929d9bd28ddb87e1a76ffb

No make/install/port/brew/curl junk. Just download, install, and run. Works with Mac OS X 10.3-10.12+.

Submitting a form by pressing enter without a submit button

Just set the hidden attribute to true:

<form name="loginBox" target="#here" method="post">
    <input name="username" type="text" /><br />
    <input name="password" type="password" />
    <input type="submit" hidden="true" />
</form>

How do I delete from multiple tables using INNER JOIN in SQL server

Just wondering.. is that really possible in MySQL? it will delete t1 and t2? or I just misunderstood the question.

But if you just want to delete table1 with multiple join conditions, just don't alias the table you want to delete

this:

DELETE t1,t2 
FROM table1 AS t1 
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...

should be written like this to work in MSSQL:

DELETE table1
FROM table1 
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...

to contrast how the other two common RDBMS do a delete operation:

http://mssql-to-postgresql.blogspot.com/2007/12/deleting-duplicates-in-postgresql-ms.html

Jackson serialization: ignore empty values (or null)

You need to add import com.fasterxml.jackson.annotation.JsonInclude;

Add

@JsonInclude(JsonInclude.Include.NON_NULL)

on top of POJO

If you have nested POJO then

@JsonInclude(JsonInclude.Include.NON_NULL)

need to add on every values.

NOTE: JAXRS (Jersey) automatically handle this scenario 2.6 and above.

add elements to object array

You can use class System.Array for add new element:

Array.Resize(ref objArray, objArray.Length + 1);
objArray[objArray.Length - 1] = new Someobject();

PHP: Split string into array, like explode with no delimiter

str_split can do the trick. Note that strings in PHP can be accessed just like a chars array, in most cases, you won't need to split your string into a "new" array.

How to convert from java.sql.Timestamp to java.util.Date?

Class java.sql.TimeStamp extends from java.util.Date.

You can directly assign a TimeStamp object to Date reference:

TimeStamp timeStamp = //whatever value you have;
Date startDate = timestampValue;

C function that counts lines in file

while(!feof(fp))
{
  ch = fgetc(fp);
  if(ch == '\n')
  {
    lines++;
  }
}

But please note: Why is “while ( !feof (file) )” always wrong?.

How to connect Bitbucket to Jenkins properly

By iterating I learned that the Token field and the token in an endpoint can be the same. So I set them to be the same as the user token and it works! Also check that the user has privileges to make a job.

Anyway, you can check access.log and see if Bitbucket makes a try or not.

jenkins

P.S. Also a link to Bitbucket Documentation. May some day it will become more useful.

process.start() arguments

Not really a direct answer, but I'd highly recommend using LINQPad for this kind of "exploratory" C# programming.

I have the following as a saved "query" in LINQPad:

var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c echo Foo && echo Bar";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardOutput.ReadToEnd().Dump();

Feel free to adapt as needed.

How to push object into an array using AngularJS

A couple of answers that should work above but this is how i would write it.

Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.

add-text.tpl.html

<div ng-controller="myController">
    <form ng-submit="addText(myText)">
        <input type="text" placeholder="Let's Go" ng-model="myText">
        <button type="submit">Add</button>
    </form>
    <ul>
        <li ng-repeat="text in arrayText">{{ text }}</li>
    </ul>
</div>

app.js

(function() {

    function myController($scope) {
        $scope.arrayText = ['hello', 'world'];
        $scope.addText = function(myText) {
             $scope.arrayText.push(myText);     
        };
    }

    angular.module('app', [])
        .controller('myController', myController);

})();

Convert .pem to .crt and .key

This is what I did on windows.

  1. Download a zip file that contains the open ssl exe from Google
  2. Unpack the zip file and go into the bin folder.
  3. Go to the address bar in the bin folder and type cmd. This will open a command prompt at this folder.
  4. move/Put the .pem file into this bin folder.
  5. Run two commands. One creates the cert and the second the key file
openssl x509 -outform der -in yourPemFilename.pem -out certfileOutName.crt
openssl rsa -in yourPemFilename.pem -out keyfileOutName.key

Defining Z order of views of RelativeLayout in Android

Check if you have any elevation on one of the Views in XML. If so, add elevation to the other item or remove the elevation to solve the issue. From there, it's the order of the views that dictates what comes above the other.

Javascript to check whether a checkbox is being checked or unchecked

To toggle a checkbox or you can use

element.checked = !element.checked;

so you could use

if (attribute == elementName)
{
    arrChecks[i].checked = !arrChecks[i].checked;
} else {
    arrChecks[i].checked = false;
}

What are .iml files in Android Studio?

What are iml files in Android Studio project?

A Google search on iml file turns up:

IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.

(from this page)

why not to use gradle scripts to integrate with external modules that you add to your project.

You do "use gradle scripts to integrate with external modules", or your own modules.

However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml files and the metadata in .idea/ directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle. This is also why you don't bother putting .iml files or .idea/ in version control, as their contents will be regenerated.

If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?

To a large extent, you can't.

You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle, how to find files in that structure. However, other metadata (compileSdkVersion, dependencies, etc.) will not be nearly as easily replicated.

Other alternatives include:

  • Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio

  • Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts

  • Have everyone use one IDE

How do I get a UTC Timestamp in JavaScript?

You could also do it utilizing getTimezoneOffset and getTime,

_x000D_
_x000D_
x = new Date()_x000D_
var UTCseconds = (x.getTime() + x.getTimezoneOffset()*60*1000)/1000;_x000D_
_x000D_
console.log("UTCseconds", UTCseconds)
_x000D_
_x000D_
_x000D_

Combine [NgStyle] With Condition (if..else)

Trying to set background color based on condition:   

Consider variable x with some numeric value.    
<p [ngStyle]="{ backgroundColor: x > 4 ? 'lightblue' : 'transparent' }">
        This is a sample Text
</p>

Android: ScrollView vs NestedScrollView

NestedScrollView as the name suggests is used when there is a need for a scrolling view inside another scrolling view. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll.

This is where NestedScrollView comes in.

Collection was modified; enumeration operation may not execute in ArrayList

Here's an example (sorry for any typos)

var itemsToRemove = new ArrayList();  // should use generic List if you can

foreach (var item in originalArrayList) {
  if (...) {
    itemsToRemove.Add(item);
  }
}

foreach (var item in itemsToRemove) {
  originalArrayList.Remove(item);
}

OR if you're using 3.5, Linq makes the first bit easier:

itemsToRemove = originalArrayList
  .Where(item => ...)
  .ToArray();

foreach (var item in itemsToRemove) {
  originalArrayList.Remove(item);
}

Replace "..." with your condition that determines if item should be removed.

How to make an Android device vibrate? with different frequency?

Update 2017 vibrate(interval) method is deprecated with Android-O(API 8.0)

To support all Android versions use this method.

// Vibrate for 150 milliseconds
private void shakeItBaby() {
    if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
    }
}

Kotlin:

// Vibrate for 150 milliseconds
private fun shakeItBaby(context: Context) {
    if (Build.VERSION.SDK_INT >= 26) {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
    }
}

How can I install pip on Windows?

There is also an issue with pip on 64 bit Cygwin. After installation, the output of pip command is always empty, no matters what commands/options do you use (even pip -V doesn't produce any output).

If it's your case, just install the development version of Cygwin's package libuuid called libuuid-devel. Without that package using of libuuid causes a segfault. And pip uses that package, so the segfault is the cause of an empty output of pip on Cygwin x64. On 32 bit Cygwin it's working fine even without that package.

You can read some details there: https://github.com/kennethreitz/requests/issues/1547

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Android Design Support Library expandable Floating Action Button(FAB) menu

Another option for the same result with ConstraintSet animation:

fab animation example

1) Put all the animated views in one ConstraintLayout

2) Animate it from code like this (if you want some more effects its up to you..this is only example)

menuItem1 and menuItem2 is the first and second FABs in menu, descriptionItem1 and descriptionItem2 is the description to the left of menu, parentConstraintLayout is the root ConstraintLayout wich contains all the animated views, isMenuOpened is some function to change open/closed flag in the state

I put animation code in extension file but its not necessary.

fun FloatingActionButton.expandMenu(
    menuItem1: View,
    menuItem2: View,
    descriptionItem1: TextView,
    descriptionItem2: TextView,
    parentConstraintLayout: ConstraintLayout,
    isMenuOpened: (Boolean)-> Unit
) {
    val constraintSet = ConstraintSet()
    constraintSet.clone(parentConstraintLayout)

    constraintSet.setVisibility(descriptionItem1.id, View.VISIBLE)
    constraintSet.clear(menuItem1.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem1.id, ConstraintSet.BOTTOM, this.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    constraintSet.setVisibility(descriptionItem2.id, View.VISIBLE)
    constraintSet.clear(menuItem2.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem2.id, ConstraintSet.BOTTOM, menuItem1.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    val transition = AutoTransition()
    transition.duration = 150
    transition.interpolator = AccelerateInterpolator()

    transition.addListener(object: Transition.TransitionListener {
        override fun onTransitionEnd(p0: Transition) {
            isMenuOpened(true)
        }
        override fun onTransitionResume(p0: Transition) {}
        override fun onTransitionPause(p0: Transition) {}
        override fun onTransitionCancel(p0: Transition) {}
        override fun onTransitionStart(p0: Transition) {}
    })

    TransitionManager.beginDelayedTransition(parentConstraintLayout, transition)
    constraintSet.applyTo(parentConstraintLayout)
}

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

Why are you not able to declare a class as static in Java?

Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.

class OuterClass {
    public static class StaticNestedClass {
    }

    public class InnerClass {
    }

    public InnerClass getAnInnerClass() {
        return new InnerClass();
    }

    //This method doesn't work
    public static InnerClass getAnInnerClassStatically() {
        return new InnerClass();
    }
}

class OtherClass {
    //Use of a static nested class:
    private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();

    //Doesn't work
    private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();

    //Use of an inner class:
    private OuterClass outerclass= new OuterClass();
    private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
    private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}

Sources :

On the same topic :

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

Recommended way to get hostname in Java

InetAddress.getLocalHost().getHostName() is better (as explained by Nick), but still not very good

One host can be known under many different hostnames. Usually you'll be looking for the hostname your host has in a specific context.

For example, in a web application, you might be looking for the hostname used by whoever issued the request you're currently handling. How to best find that one depends on which framework you're using for your web application.

In some kind of other internet-facing service, you'll want the hostname your service is available through from the 'outside'. Due to proxies, firewalls etc this might not even be a hostname on the machine your service is installed on - you might try to come up with a reasonable default, but you should definitely make this configurable for whoever installs this.

sql how to cast a select query

I interpreted the question as using cast on a subquery. Yes, you can do that:

select cast((<subquery>) as <newtype>)

If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:

select (select cast(<val> as <newtype>) . . .)

Set HTML element's style property in javascript

I'd like to note that it's usually preferable to change the class of the node instead of it's style and let CSS handle what that means.

How to Execute a Python File in Notepad ++?

You can run your script via cmd and be in script-directory:

cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Here is a demo. Use position:fixed; top:0; left:0; so the header always stay on top.

?#header {
    background:red;
    height:50px;
    width:100%;
    position:fixed;
    top:0;
    left:0;    
}.scroller {
    height:300px; 
    overflow:scroll;    
}

How to pad a string with leading zeros in Python 3

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(f'length = {length:03}')
length = 001

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

Combine a list of data frames into one data frame by row

One other option is to use a plyr function:

df <- ldply(listOfDataFrames, data.frame)

This is a little slower than the original:

> system.time({ df <- do.call("rbind", listOfDataFrames) })
   user  system elapsed 
   0.25    0.00    0.25 
> system.time({ df2 <- ldply(listOfDataFrames, data.frame) })
   user  system elapsed 
   0.30    0.00    0.29
> identical(df, df2)
[1] TRUE

My guess is that using do.call("rbind", ...) is going to be the fastest approach that you will find unless you can do something like (a) use a matrices instead of a data.frames and (b) preallocate the final matrix and assign to it rather than growing it.

Edit 1:

Based on Hadley's comment, here's the latest version of rbind.fill from CRAN:

> system.time({ df3 <- rbind.fill(listOfDataFrames) })
   user  system elapsed 
   0.24    0.00    0.23 
> identical(df, df3)
[1] TRUE

This is easier than rbind, and marginally faster (these timings hold up over multiple runs). And as far as I understand it, the version of plyr on github is even faster than this.

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.

Use:

mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.