Programs & Examples On #Copy

To copy is to create a duplicate of an object without destroying the original. Commonly seen in text editors that will let you copy some text and paste it somewhere else.

How to copy a char array in C?

You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:

For char arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy():

#include <string.h>

char array1[18] = "abcdefg";
char array2[18];

...

strcpy(array2, array1);

If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf():

#include <stdio.h>

char array1[] = "a longer string that might not fit";
char array2[18];

...

snprintf(array2, sizeof array2, "%s", array1);

If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy:

#include <string.h>

char array1[28] = "a non null terminated string";
char array2[28];

...

memcpy(array2, array1, sizeof array2);

How do I copy a 2 Dimensional array in Java?

Here's how you can do it by using loops.

public static int[][] makeCopy(int[][] array){
    b=new int[array.length][];

    for(int row=0; row<array.length; ++row){
        b[row]=new int[array[row].length];
        for(int col=0; col<b[row].length; ++col){
            b[row][col]=array[row][col];
        }
    }
    return b;
}

Copy filtered data to another sheet using VBA

I suggest you do it a different way.

In the following code I set as a Range the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.

I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification

Sub TestThat()

'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long

'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")

Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
    'I went from the cell row3/column6 (or F3) and go down until the last non empty cell

    i = 2

    For Each rCell In SportsRange 'loop through each cell in the range

        If rCell = "hockey" Then 'check if the cell is equal to "hockey"

            i = i + 1                                'Row number (+1 everytime I found another "hockey")
            HokySh.Cells(i, 2) = i - 2               'S No.
            HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
            HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
            HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age

        End If

    Next rCell

End Sub

How to export all data from table to an insertable sql format?

I know this is an old question, but victorio also asked if there are any other options to copy data from one table to another. There is a very short and fast way to insert all the records from one table to another (which might or might not have similar design).

If you dont have identity column in table B_table:

INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table

If you have identity column in table B_table, you have to specify columns to insert. Basically you select all except identity column, which will be auto incremented by default.

In case if you dont have existing B_table in B_db

SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table

will create table B_table in database B_db with all existing values

Standard concise way to copy a file in Java?

A little late to the party, but here is a comparison of the time taken to copy a file using various file copy methods. I looped in through the methods for 10 times and took an average. File transfer using IO streams seem to be the worst candidate:

Comparison of file transfer using various methods

Here are the methods:

private static long fileCopyUsingFileStreams(File fileToCopy, File newFile) throws IOException {
    FileInputStream input = new FileInputStream(fileToCopy);
    FileOutputStream output = new FileOutputStream(newFile);
    byte[] buf = new byte[1024];
    int bytesRead;
    long start = System.currentTimeMillis();
    while ((bytesRead = input.read(buf)) > 0)
    {
        output.write(buf, 0, bytesRead);
    }
    long end = System.currentTimeMillis();

    input.close();
    output.close();

    return (end-start);
}

private static long fileCopyUsingNIOChannelClass(File fileToCopy, File newFile) throws IOException
{
    FileInputStream inputStream = new FileInputStream(fileToCopy);
    FileChannel inChannel = inputStream.getChannel();

    FileOutputStream outputStream = new FileOutputStream(newFile);
    FileChannel outChannel = outputStream.getChannel();

    long start = System.currentTimeMillis();
    inChannel.transferTo(0, fileToCopy.length(), outChannel);
    long end = System.currentTimeMillis();

    inputStream.close();
    outputStream.close();

    return (end-start);
}

private static long fileCopyUsingApacheCommons(File fileToCopy, File newFile) throws IOException
{
    long start = System.currentTimeMillis();
    FileUtils.copyFile(fileToCopy, newFile);
    long end = System.currentTimeMillis();
    return (end-start);
}

private static long fileCopyUsingNIOFilesClass(File fileToCopy, File newFile) throws IOException
{
    Path source = Paths.get(fileToCopy.getPath());
    Path destination = Paths.get(newFile.getPath());
    long start = System.currentTimeMillis();
    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
    long end = System.currentTimeMillis();

    return (end-start);
}

The only drawback what I can see while using NIO channel class is that I still can't seem to find a way to show intermediate file copy progress.

batch/bat to copy folder and content at once

if you have xcopy, you can use the /E param, which will copy directories and subdirectories and the files within them, including maintaining the directory structure for empty directories

xcopy [source] [destination] /E

Batch file to copy directories recursively

I wanted to replicate Unix/Linux's cp -r as closely as possible. I came up with the following:

xcopy /e /k /h /i srcdir destdir

Flag explanation:

/e Copies directories and subdirectories, including empty ones.
/k Copies attributes. Normal Xcopy will reset read-only attributes.
/h Copies hidden and system files also.
/i If destination does not exist and copying more than one file, assume destination is a directory.


I made the following into a batch file (cpr.bat) so that I didn't have to remember the flags:

xcopy /e /k /h /i %*

Usage: cpr srcdir destdir


You might also want to use the following flags, but I didn't:
/q Quiet. Do not display file names while copying.
/b Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o Copies directory and file ACLs. (requires UAC admin)

PG COPY error: invalid input syntax for integer

Just came across this while looking for a solution and wanted to add I was able to solve the issue by adding the "null" parameter to the copy_from call:

cur.copy_from(f, tablename, sep=',', null='')

Copying a local file from Windows to a remote server using scp

If your drive letter is C, you should be able to use

scp -r \desktop\myfolder\deployments\ user@host:/path/to/whereyouwant/thefile

without drive letter and backslashes instead of forward slashes.

You are using putty, so you can use pscp. It is better adapted to Windows.

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

In MySQL, can I copy one row to insert into the same table?

I'm assuming you want the new record to have a new primarykey? If primarykey is AUTO_INCREMENT then just do this:

INSERT INTO table (col1, col2, col3, ...)
SELECT col1, col2, col3, ... FROM table
  WHERE primarykey = 1

...where col1, col2, col3, ... is all of the columns in the table except for primarykey.

If it's not an AUTO_INCREMENT column and you want to be able to choose the new value for primarykey it's similar:

INSERT INTO table (primarykey, col2, col3, ...)
SELECT 567, col2, col3, ... FROM table
  WHERE primarykey = 1

...where 567 is the new value for primarykey.

Copy Image from Remote Server Over HTTP

For those who need to preserve the original filename and extension

$origin = 'http://example.com/image.jpg';

$filename = pathinfo($origin, PATHINFO_FILENAME);
$ext = pathinfo($origin, PATHINFO_EXTENSION);

$dest = 'myfolder/' . $filename . '.' . $ext;

copy($origin, $dest);

Copy multiple files in Python

Look at shutil in the Python docs, specifically the copytree command.

If the destination directory already exists, try:

shutil.copytree(source, destination, dirs_exist_ok=True)

How to deep copy a list?

This is more pythonic

my_list = [0, 1, 2, 3, 4, 5]  # some list
my_list_copy = list(my_list)  # my_list_copy and my_list does not share reference now.

NOTE: This is not safe with a list of referenced objects

Understanding dict.copy() - shallow or deep?

By "shallow copying" it means the content of the dictionary is not copied by value, but just creating a new reference.

>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

In contrast, a deep copy will copy all contents by value.

>>> import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})

So:

  1. b = a: Reference assignment, Make a and b points to the same object.

    Illustration of 'a = b': 'a' and 'b' both point to '{1: L}', 'L' points to '[1, 2, 3]'.

  2. b = a.copy(): Shallow copying, a and b will become two isolated objects, but their contents still share the same reference

    Illustration of 'b = a.copy()': 'a' points to '{1: L}', 'b' points to '{1: M}', 'L' and 'M' both point to '[1, 2, 3]'.

  3. b = copy.deepcopy(a): Deep copying, a and b's structure and content become completely isolated.

    Illustration of 'b = copy.deepcopy(a)': 'a' points to '{1: L}', 'L' points to '[1, 2, 3]'; 'b' points to '{1: M}', 'M' points to a different instance of '[1, 2, 3]'.

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

How do you copy the contents of an array to a std::vector in C++ without looping?

Yet another answer, since the person said "I don't know how many times my function will be called", you could use the vector insert method like so to append arrays of values to the end of the vector:

vector<int> x;

void AddValues(int* values, size_t size)
{
   x.insert(x.end(), values, values+size);
}

I like this way because the implementation of the vector should be able to optimize for the best way to insert the values based on the iterator type and the type itself. You are somewhat replying on the implementation of stl.

If you need to guarantee the fastest speed and you know your type is a POD type then I would recommend the resize method in Thomas's answer:

vector<int> x;

void AddValues(int* values, size_t size)
{
   size_t old_size(x.size());
   x.resize(old_size + size, 0);
   memcpy(&x[old_size], values, size * sizeof(int));
}

How can a file be copied?

Use the shutil module.

copyfile(src, dst)

Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.

Take a look at filesys for all the file and directory handling functions available in standard Python modules.

How to programmatically move, copy and delete files and directories on SD?

  1. Permissions:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
  2. Get SD card root folder:

    Environment.getExternalStorageDirectory()
    
  3. Delete file: this is an example on how to delete all empty folders in a root folder:

    public static void deleteEmptyFolder(File rootFolder){
        if (!rootFolder.isDirectory()) return;
    
        File[] childFiles = rootFolder.listFiles();
        if (childFiles==null) return;
        if (childFiles.length == 0){
            rootFolder.delete();
        } else {
            for (File childFile : childFiles){
                deleteEmptyFolder(childFile);
            }
        }
    }
    
  4. Copy file:

    public static void copyFile(File src, File dst) throws IOException {
        FileInputStream var2 = new FileInputStream(src);
        FileOutputStream var3 = new FileOutputStream(dst);
        byte[] var4 = new byte[1024];
    
        int var5;
        while((var5 = var2.read(var4)) > 0) {
            var3.write(var4, 0, var5);
        }
    
        var2.close();
        var3.close();
    }
    
  5. Move file = copy + delete source file

Using scp to copy a file to Amazon EC2 instance?

You should be on you local machine to try the above scp command.

On your local machine try:

scp -i ~/Downloads/myAmazonKey.pem ~/Downloads/phpMyAdmin-3.4.5-all-languages.tar.gz  [email protected]:~/.

Using a batch to copy from network drive to C: or D: drive

This might be due to a security check. This thread might help you.

There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...

Powershell 2 copy-item which creates a folder if doesn't exist

function Copy-File ([System.String] $sourceFile, [System.String] $destinationFile, [Switch] $overWrite) {

    if ($sourceFile -notlike "filesystem::*") {
        $sourceFile = "filesystem::$sourceFile" 
    }

    if ($destinationFile -notlike "filesystem::*") {
        $destinationFile = "filesystem::$destinationFile" 
    }

    $destinationFolder = $destinationFile.Replace($destinationFile.Split("\")[-1],"")

    if (!(Test-Path -path $destinationFolder)) {
        New-Item $destinationFolder -Type Directory
    }

    try {
        Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force
        Return $true 
    } catch [System.IO.IOException] {
        # If overwrite enabled, then delete the item from the destination, and try again:
        if ($overWrite) {
            try {
                Remove-Item -Path $destinationFile -Recurse -Force        
                Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force 
                Return $true
            } catch {
                Write-Error -Message "[Copy-File] Overwrite error occurred!`n$_" -ErrorAction SilentlyContinue
                #$PSCmdlet.WriteError($Global:Error[0])
                Return $false
            }
        } else {
            Write-Error -Message "[Copy-File] File already exists!" -ErrorAction SilentlyContinue
            #$PSCmdlet.WriteError($Global:Error[0])
            Return $false
        }
    } catch {
        Write-Error -Message "[Copy-File] File move failed!`n$_" -ErrorAction SilentlyContinue
        #$PSCmdlet.WriteError($Global:Error[0]) 
        Return $false
    } 
}

Wait Until File Is Completely Written

From the documentation for FileSystemWatcher:

The OnCreated event is raised as soon as a file is created. If a file is being copied or transferred into a watched directory, the OnCreated event will be raised immediately, followed by one or more OnChanged events.

So, if the copy fails, (catch the exception), add it to a list of files that still need to be moved, and attempt the copy during the OnChanged event. Eventually, it should work.

Something like (incomplete; catch specific exceptions, initialize variables, etc):

public static void listener_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine
            (
                "File Created:\n"
               + "ChangeType: " + e.ChangeType
               + "\nName: " + e.Name
               + "\nFullPath: " + e.FullPath
            );
    try {
        File.Copy(e.FullPath, @"D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name);
    }
    catch {
        _waitingForClose.Add(e.FullPath);
    }
    Console.Read();
}

public static void listener_Changed(object sender, FileSystemEventArgs e)
{
     if (_waitingForClose.Contains(e.FullPath))
     {
          try {
              File.Copy(...);
              _waitingForClose.Remove(e.FullPath);
          }
          catch {}
     }

}

fast way to copy formatting in excel

For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:

range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)

And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")


edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?

Copying sets Java

Java 8+:

Set<String> copy = new HashSet<>(mySet); 

How to copy Java Collections list

With Java 8 being null-safe, you could use the following code.

List<String> b = Optional.ofNullable(a)
                         .map(list -> (List<String>) new ArrayList<>(list))
                         .orElseGet(Collections::emptyList);

Or using a collector

List<String> b = Optional.ofNullable(a)
                         .map(List::stream)
                         .orElseGet(Stream::empty)
                         .collect(Collectors.toList())

Create a directory if it doesn't exist

Probably the easiest and most efficient way is to use boost and the boost::filesystem functions. This way you can build a directory simply and ensure that it is platform independent.

const char* path = _filePath.c_str();
boost::filesystem::path dir(path);
if(boost::filesystem::create_directory(dir))
{
    std::cerr<< "Directory Created: "<<_filePath<<std::endl;
}

boost::filesystem::create_directory - documentation

Move / Copy File Operations in Java

Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.

Duration using FileOutputStream byte stream: 4 965 078

Duration using BufferedOutputStream: 1 237 206

Duration using (character text Reader: 2 858 875

Duration using BufferedReader(Buffered character text stream: 1 998 005

Duration using (Files NIO copy): 18 351 115

when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.

How can I create a copy of an object in Python?

I believe the following should work with many well-behaved classed in Python:

def copy(obj):
    return type(obj)(obj)

(Of course, I am not talking here about "deep copies," which is a different story, and which may be not a very clear concept -- how deep is deep enough?)

According to my tests with Python 3, for immutable objects, like tuples or strings, it returns the same object (because there is no need to make a shallow copy of an immutable object), but for lists or dictionaries it creates an independent shallow copy.

Of course this method only works for classes whose constructors behave accordingly. Possible use cases: making a shallow copy of a standard Python container class.

Copy data from one existing row to another existing row in SQL?

This works well for coping entire records.

UPDATE your_table
SET new_field = sourse_field

How to copy files from 'assets' folder to sdcard?

You can also use Guava's ByteStream to copy the files from the assets folder to the SD card. This is the solution I ended up with which copies files recursively from the assets folder to the SD card:

/**
 * Copies all assets in an assets directory to the SD file system.
 */
public class CopyAssetsToSDHelper {

    public static void copyAssets(String assetDir, String targetDir, Context context) 
        throws IOException {
        AssetManager assets = context.getAssets();
        String[] list = assets.list(assetDir);
        for (String f : Objects.requireNonNull(list)) {
            if (f.indexOf(".") > 1) { // check, if this is a file
                File outFile = new File(context.getExternalFilesDir(null), 
                    String.format("%s/%s", targetDir, f));
                File parentFile = outFile.getParentFile();
                if (!Objects.requireNonNull(parentFile).exists()) {
                    if (!parentFile.mkdirs()) {
                        throw new IOException(String.format("Could not create directory %s.", 
                            parentFile));
                    }
                }
                try (InputStream fin = assets.open(String.format("%s/%s", assetDir, f));
                     OutputStream fout = new FileOutputStream(outFile)) {
                    ByteStreams.copy(fin, fout);
                }
            } else { // This is a directory
                copyAssets(String.format("%s/%s", assetDir, f), String.format("%s/%s", targetDir, f), 
                    context);
            }
        }
    }

}

Is there a function to make a copy of a PHP array to another?

Safest and cheapest way I found is:

<?php 
$b = array_values($a);

This has also the benefit to reindex the array.

This will not work as expected on associative array (hash), but neither most of previous answer.

How do I copy items from list to list without foreach?

This method will create a copy of your list but your type should be serializable.

Use:

List<Student> lstStudent = db.Students.Where(s => s.DOB < DateTime.Now).ToList().CopyList(); 

Method:

public static List<T> CopyList<T>(this List<T> lst)
    {
        List<T> lstCopy = new List<T>();
        foreach (var item in lst)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, item);
                stream.Position = 0;
                lstCopy.Add((T)formatter.Deserialize(stream));
            }
        }
        return lstCopy;
    }

Git copy file preserving history

All you have to do is:

  1. move the file to two different locations,
  2. merge the two commits that do the above, and
  3. move one copy back to the original location.

You will be able to see historical attributions (using git blame) and full history of changes (using git log) for both files.

Suppose you want to create a copy of file foo called bar. In that case the workflow you'd use would look like this:

git mv foo bar
git commit

SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit

git merge $SAVED     # This will generate conflicts
git commit -a        # Trivially resolved like this

git mv copy foo
git commit

Why this works

After you execute the above commands, you end up with a revision history that looks like this:

( revision history )            ( files )

    ORIG_HEAD                      foo
     /     \                      /   \
SAVED       ALTERNATE          bar     copy
     \     /                      \   /
      MERGED                     bar,copy
        |                           |
     RESTORED                    bar,foo

When you ask Git about the history of foo, it will:

  1. detect the rename from copy between MERGED and RESTORED,
  2. detect that copy came from the ALTERNATE parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and ALTERNATE.

From there it will dig into the history of foo.

When you ask Git about the history of bar, it will:

  1. notice no change between MERGED and RESTORED,
  2. detect that bar came from the SAVED parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and SAVED.

From there it will dig into the history of foo.

It's that simple. :)

You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

There is another way of copying a list that was not listed until now : adding an empty list : l2 = l + []. I tested it with Python 3.8 :

l = [1,2,3]
l2 = l + []
print(l,l2)
l[0] = 'a'
print(l,l2)

Not the best answer but it works.

Eclipse copy/paste entire line keyboard shortcut

You have to turn off the graphics hot keys that flip the screen. If you're on Windows, you need to right click on the Windows desktop and select "Graphics Properties..." (or something similar depending on your version of Windows). This will bring up a screen where you can manage graphics and display options, look for a place where you can disable hot keys, sometimes it's hidden under something like "Options and Support". Turn off the CTRL + ALT + ? and CTRL + ALT + ? hotkeys (alternatively you can just disable all graphics hot keys if you're not using them).

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

jQuery: get the file name selected from <input type="file" />

<input onchange="readURL(this);"  type="file" name="userfile" />
<img src="" id="blah"/>
<script>
 function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah')
                    .attr('src', e.target.result)
                    .width(150).height(200);
        };

        reader.readAsDataURL(input.files[0]);
        //console.log(reader);
        //alert(reader.readAsDataURL(input.files[0]));
    }
}
</script>

SQL Server - copy stored procedures from one db to another

SELECT definition + char(13) + 'GO' FROM MyDatabase.sys.sql_modules s INNER JOIN MyDatabase.sys.procedures p ON [s].[object_id] = [p].[object_id] WHERE p.name LIKE 'Something%'" queryout "c:\SP_scripts.sql -S MyInstance -T -t -w

get the sp and execute it

How to copy a string of std::string type in C++?

strcpy is only for C strings. For std::string you copy it like any C++ object.

std::string a = "text";
std::string b = a; // copy a into b

If you want to concatenate strings you can use the + operator:

std::string a = "text";
std::string b = "image";
a = a + b; // or a += b;

You can even do many at once:

std::string c = a + " " + b + "hello";

Although "hello" + " world" doesn't work as you might expect. You need an explicit std::string to be in there: std::string("Hello") + "world"

How to copy a java.util.List into another java.util.List

Starting from Java 10:

List<E> oldList = List.of();
List<E> newList = List.copyOf(oldList);

List.copyOf() returns an unmodifiable List containing the elements of the given Collection.

The given Collection must not be null, and it must not contain any null elements.

Also, if you want to create a deep copy of a List, you can find many good answers here.

Copy output of a JavaScript variable to the clipboard

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')

How to copy an object in Objective-C

I don't know the difference between that code and mine, but I have problems with that solution, so I read a little bit more and found that we have to set the object before return it. I mean something like:

#import <Foundation/Foundation.h>

@interface YourObject : NSObject <NSCopying>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *line;
@property (strong, nonatomic) NSMutableString *tags;
@property (strong, nonatomic) NSString *htmlSource;
@property (strong, nonatomic) NSMutableString *obj;

-(id) copyWithZone: (NSZone *) zone;

@end


@implementation YourObject


-(id) copyWithZone: (NSZone *) zone
{
    YourObject *copy = [[YourObject allocWithZone: zone] init];

    [copy setNombre: self.name];
    [copy setLinea: self.line];
    [copy setTags: self.tags];
    [copy setHtmlSource: self.htmlSource];

    return copy;
}

I added this answer because I have a lot of problems with this issue and I have no clue about why is it happening. I don't know the difference, but it's working for me and maybe it can be useful for others too : )

Copying HTML code in Google Chrome's inspect element

This is bit tricky

Now a days most of website new techniques to save websites from scraping

1st Technique

Ctrl+U this will show you Page Source enter image description here

2nd Technique

This one is small hack if the website has ajax like functionality.

Just Hover the mouse key on inspect element untill whole screen becomes just right click then and copy element enter image description here

That's it you are good to go.

Copy a table from one database to another in Postgres

You can also use the backup functionality in pgAdmin II. Just follow these steps:

  • In pgAdmin, right click the table you want to move, select "Backup"
  • Pick the directory for the output file and set Format to "plain"
  • Click the "Dump Options #1" tab, check "Only data" or "only Schema" (depending on what you are doing)
  • Under the Queries section, click "Use Column Inserts" and "User Insert Commands".
  • Click the "Backup" button. This outputs to a .backup file
  • Open this new file using notepad. You will see the insert scripts needed for the table/data. Copy and paste these into the new database sql page in pgAdmin. Run as pgScript - Query->Execute as pgScript F6

Works well and can do multiple tables at a time.

Create a copy of a table within the same database DB2

You have to surround the select part with parenthesis.

CREATE TABLE SCHEMA.NEW_TB AS (
    SELECT *
    FROM SCHEMA.OLD_TB
) WITH NO DATA

Should work. Pay attention to all the things @Gilbert said would not be copied.

I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.

Dockerfile copy keep subdirectory structure

Remove star from COPY, with this Dockerfile:

FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*

Structure is there:

$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon 
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : COPY files/ /files/
 ---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
 ---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2

/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2
 ---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b

Using FileSystemWatcher to monitor a directory

You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.

You can wait for a file to be ready by using this function in a loop.

How to copy a row and insert in same table with a autoincrement field in MySQL?

insert into MyTable(field1, field2, id_backup)
    select field1, field2, uniqueId from MyTable where uniqueId = @Id;

Make copy of an array

you can use

int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();

as well.

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

How do I copy a folder from remote to local using scp?

And if you have one hell of a files to download from the remote location and if you don't much care about security, try changing the scp default encryption (Triple-DES) to something like 'blowfish'.

This will reduce file copying time drastically.

scp -c blowfish -r [email protected]:/path/to/foo /home/user/Desktop/

How to copy directory recursively in python and overwrite all?

In Python 3.8 the dirs_exist_ok keyword argument was added to shutil.copytree():

dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.

So, the following will work in recent versions of Python, even if the destination directory already exists:

shutil.copytree(src, dest, dirs_exist_ok=True)  # 3.8+ only!

One major benefit is that it's more flexible than distutils.dir_util.copy_tree() as it takes additional arguments on files to ignore, etc. There is also a draft PEP (PEP 632, associated discussion), which suggests that distutils may be deprecated and then removed in future versions of Python 3.

Python copy files to a new directory and rename if file name already exists

Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
    for filename in files:
        # I use absolute path, case you want to move several dirs.
        old_name = os.path.join( os.path.abspath(root), filename )

        # Separate base from extension
        base, extension = os.path.splitext(filename)

        # Initial new name
        new_name = os.path.join(basedir, base, filename)

        # If folder basedir/base does not exist... You don't want to create it?
        if not os.path.exists(os.path.join(basedir, base)):
            print os.path.join(basedir,base), "not found" 
            continue    # Next filename
        elif not os.path.exists(new_name):  # folder exists, file does not
            shutil.copy(old_name, new_name)
        else:  # folder exists, file exists as well
            ii = 1
            while True:
                new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                if not os.path.exists(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1

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')

Copying one structure to another

Copying by plain assignment is best, since it's shorter, easier to read, and has a higher level of abstraction. Instead of saying (to the human reader of the code) "copy these bits from here to there", and requiring the reader to think about the size argument to the copy, you're just doing a plain assignment ("copy this value from here to here"). There can be no hesitation about whether or not the size is correct.

Also, if the structure is heavily padded, assignment might make the compiler emit something more efficient, since it doesn't have to copy the padding (and it knows where it is), but mempcy() doesn't so it will always copy the exact number of bytes you tell it to copy.

If your string is an actual array, i.e.:

struct {
  char string[32];
  size_t len;
} a, b;

strcpy(a.string, "hello");
a.len = strlen(a.string);

Then you can still use plain assignment:

b = a;

To get a complete copy. For variable-length data modelled like this though, this is not the most efficient way to do the copy since the entire array will always be copied.

Beware though, that copying structs that contain pointers to heap-allocated memory can be a bit dangerous, since by doing so you're aliasing the pointer, and typically making it ambiguous who owns the pointer after the copying operation.

For these situations a "deep copy" is really the only choice, and that needs to go in a function.

How to properly -filter multiple strings in a PowerShell copy script

Something like this should work (it did for me). The reason for wanting to use -Filter instead of -Include is that include takes a huge performance hit compared to -Filter.

Below just loops each file type and multiple servers/workstations specified in separate files.

##  
##  This script will pull from a list of workstations in a text file and search for the specified string


## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside

$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'

##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'

foreach ($server in $servers)
    {

    foreach ($filetype in $filetypes)
    {

    ## below creates the search path.  This could be further improved to exclude the windows directory
    $serverString = "\\"+$server+"\c$\Program Files"


    ## Display the server being queried
    write-host “Server:” $server "searching for " $filetype in $serverString

    Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
    #-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
    Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt

    $os = gwmi win32_operatingsystem -computer $server
    $sp = $os | % {$_.servicepackmajorversion}
    $a = $os | % {$_.caption}

    ##  Below will list again the server name as well as its OS and SP
    ##  Because the script may not be monitored, this helps confirm the machine has been successfully scanned
        write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp


    }

}
#end script

MySQL: Cloning a MySQL database on the same MySql instance

I don't think there is a method to do this. When PHPMyAdmin does this, it dumps the DB then re-inserts it under the new name.

Copy the entire contents of a directory in C#

Copy folder recursively without recursion to avoid stack overflow.

public static void CopyDirectory(string source, string target)
{
    var stack = new Stack<Folders>();
    stack.Push(new Folders(source, target));

    while (stack.Count > 0)
    {
        var folders = stack.Pop();
        Directory.CreateDirectory(folders.Target);
        foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
        {
            File.Copy(file, Path.Combine(folders.Target, Path.GetFileName(file)));
        }

        foreach (var folder in Directory.GetDirectories(folders.Source))
        {
            stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
        }
    }
}

public class Folders
{
    public string Source { get; private set; }
    public string Target { get; private set; }

    public Folders(string source, string target)
    {
        Source = source;
        Target = target;
    }
}

How to export dataGridView data Instantly to Excel on button click?

In my opinion this is the easiest and instantly working method of exporting datagridview.

 try
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
            sfd.FileName = "ProfitLoss.xlsx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                DataTable dts = new DataTable();
                for (int i = 0; i < grdProfitAndLoss.Columns.Count; i++)
                {
                    dts.Columns.Add(grdProfitAndLoss.Columns[i].Name);
                }
                for (int j = 0; j < grdProfitAndLoss.Rows.Count; j++)
                {
                    DataRow toInsert = dts.NewRow();
                    int k = 0;
                    int inc = 0;
                    for (k = 0; k < grdProfitAndLoss.Columns.Count; k++)
                    {
                        if (grdProfitAndLoss.Columns[k].Visible == false) { continue; }
                        toInsert[inc] = grdProfitAndLoss.Rows[j].Cells[k].Value;
                        inc++;
                    }
                    dts.Rows.Add(toInsert);
                }
                dts.AcceptChanges();
                ExcelUtlity obj = new ExcelUtlity();
                obj.WriteDataTableToExcel(dts, "Profit And Loss", sfd.FileName, "Profit And Loss");
                MessageBox.Show("Exported Successfully");
            }
        }
        catch (Exception ex)
        {

        }

How to copy data from one table to another new table in MySQL?

CREATE TABLE newTable LIKE oldTable;

Then, to copy the data over

INSERT INTO newTable SELECT * FROM oldTable;

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

There is a much cleaner solution:

var srcArray = [1, 2, 3];
var clonedArray = srcArray.length === 1 ? [srcArray[0]] : Array.apply(this, srcArray);

The length check is required, because the Array constructor behaves differently when it is called with exactly one argument.

How to copy file from HDFS to the local file system

1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.

$hdfs dfs -get /output-fileFolderName-In-hdfs

Copy files from one directory into an existing directory

cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2

How to copy a file from one directory to another using PHP?

copy will do this. Please check the php-manual. Simple Google search should answer your last two questions ;)

Copy struct to struct in C

I think you should cast the pointers to (void *) to get rid of the warnings.

memcpy((void *)&RTCclk, (void *)&RTCclkBuffert, sizeof RTCclk);

Also you have use sizeof without brackets, you can use this with variables but if RTCclk was defined as an array, sizeof of will return full size of the array. If you use use sizeof with type you should use with brackets.

sizeof(struct RTCclk)

Is there a macro to conditionally copy rows to another worksheet?

This is partially pseudocode, but you will want something like:

rows = ActiveSheet.UsedRange.Rows
n = 0

while n <= rows
  if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then
     ActiveSheet.Rows(n).CopyTo(DestinationSheet)
  endif
  n = n + 1
wend

How can I create a copy of an Oracle table without copying the data?

Just use a where clause that won't select any rows:

create table xyz_new as select * from xyz where 1=0;

Limitations

The following things will not be copied to the new table:

  • sequences
  • triggers
  • indexes
  • some constraints may not be copied
  • materialized view logs

This also does not handle partitions


Copying the cell value preserving the formatting from one cell to another in excel using VBA

To copy formatting:

Range("F10").Select
Selection.Copy
Range("I10:J10").Select ' note that we select the whole merged cell
Selection.PasteSpecial Paste:=xlPasteFormats

copying the formatting will break the merged cells, so you can use this to put the cell back together

Range("I10:J10").Select
Selection.Merge

To copy a cell value, without copying anything else (and not using copy/paste), you can address the cells directly

Range("I10").Value = Range("F10").Value

other properties (font, color, etc ) can also be copied by addressing the range object properties directly in the same way

Find and copy files

The reason for that error is that you are trying to copy a folder which requires -r option also to cp Thanks

Copying a HashMap in Java

Since the OP has mentioned he does not have access to the base class inside of which exists a HashMap - I am afraid there are very few options available.

One (painfully slow and resource intensive) way of performing a deep copy of an object in Java is to abuse the 'Serializable' interface which many classes either intentionally - or unintentionally extend - and then utilise this to serialise your class to ByteStream. Upon de-serialisation you will have a deep copy of the object in question.

A guide for this can be found here: https://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html

CentOS: Copy directory to another directory

To copy all files, including hidden files use:

cp -r /home/server/folder/test/. /home/server/

Copy tables from one database to another in SQL Server

On SQL Server? and on the same database server? Use three part naming.

INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar

This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

How do I copy an object in Java?

public class MyClass implements Cloneable {

private boolean myField= false;
// and other fields or objects

public MyClass (){}

@Override
public MyClass clone() throws CloneNotSupportedException {
   try
   {
       MyClass clonedMyClass = (MyClass)super.clone();
       // if you have custom object, then you need create a new one in here
       return clonedMyClass ;
   } catch (CloneNotSupportedException e) {
       e.printStackTrace();
       return new MyClass();
   }

  }
}

and in your code:

MyClass myClass = new MyClass();
// do some work with this object
MyClass clonedMyClass = myClass.clone();

copying all contents of folder to another folder using batch file?

If you have robocopy,

robocopy C:\Folder1 D:\Folder2 /COPYALL /E

otherwise,

xcopy /e /v C:\Folder1 D:\Folder2

Hide Command Window of .BAT file that Executes Another .EXE File

Using start works for me:

@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe

EDIT: Ok, looking more closely, start seems to interpret the first parameter as the new window title if quoted. So, if you need to quote the path to your ThirdParty.exe you must supply a title string as well.

Examples:

:: Title not needed:
start C:\ThirdParty.exe

:: Title needed
start "Third Party App" "C:\Program Files\Vendor\ThirdParty.exe"

How do I copy a hash in Ruby?

Since standard cloning method preserves the frozen state, it is not suitable for creating new immutable objects basing on the original object, if you would like the new objects be slightly different than the original (if you like stateless programming).

Copying files from one directory to another in Java

I provided an alternate solution without the need to use a third party, such as apache FileUtils. This can be done through the command line.

I tested this out on Windows and it works for me. A Linux solution follows.

Here I am utilizing Windows xcopy command to copy all files including subdirectories. The parameters that I pass are defined as per below.

  • /e - Copies all subdirectories, even if they are empty.
  • /i - If Source is a directory or contains wildcards and Destination does not exist, xcopy assumes Destination specifies a directory name and creates a new directory. Then, xcopy copies all specified files into the new directory.
  • /h - Copies files with hidden and system file attributes. By default, xcopy does not copy hidden or system files

My example(s) utilizes the ProcessBuilder class to construct a process to execute the copy(xcopy & cp) commands.

Windows:

String src = "C:\\srcDir";
String dest = "C:\\destDir";
List<String> cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Linux:

String src = "srcDir/";
String dest = "~/destDir/";
List<String> cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
try {
    Process proc = new ProcessBuilder(cmd).start();
    BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = inp.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Or a combo that can work on both Windows or Linux environments.

private static final String OS = System.getProperty("os.name");
private static String src = null;
private static String dest = null;
private static List<String> cmd = null;

public static void main(String[] args) {
    if (OS.toLowerCase().contains("windows")) { // setup WINDOWS environment
        src = "C:\\srcDir";
        dest = "C:\\destDir";
        cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");

        System.out.println("on: " + OS);
    } else if (OS.toLowerCase().contains("linux")){ // setup LINUX environment
        src = "srcDir/";
        dest = "~/destDir/";
        cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);

        System.out.println("on: " + OS);
    }

    try {
        Process proc = new ProcessBuilder(cmd).start();
        BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = null;
        while ((line = inp.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

What is the difference between `sorted(list)` vs `list.sort()`?

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

Copy folder structure (without files) from one location to another

cd /path/to/directories &&
find . -type d -exec mkdir -p -- /path/to/backup/{} \;

What is the difference between a deep copy and a shallow copy?

Deep Copy

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

Shallow Copy

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

How can I copy a file on Unix using C?

It's straight forward to use fork/execl to run cp to do the work for you. This has advantages over system in that it is not prone to a Bobby Tables attack and you don't need to sanitize the arguments to the same degree. Further, since system() requires you to cobble together the command argument, you are not likely to have a buffer overflow issue due to sloppy sprintf() checking.

The advantage to calling cp directly instead of writing it is not having to worry about elements of the target path existing in the destination. Doing that in roll-you-own code is error-prone and tedious.

I wrote this example in ANSI C and only stubbed out the barest error handling, other than that it's straight forward code.

void copy(char *source, char *dest)
{
    int childExitStatus;
    pid_t pid;
    int status;
    if (!source || !dest) {
        /* handle as you wish */
    }

    pid = fork();

    if (pid == 0) { /* child */
        execl("/bin/cp", "/bin/cp", source, dest, (char *)0);
    }
    else if (pid < 0) {
        /* error - couldn't start process - you decide how to handle */
    }
    else {
        /* parent - wait for child - this has all error handling, you
         * could just call wait() as long as you are only expecting to
         * have one child process at a time.
         */
        pid_t ws = waitpid( pid, &childExitStatus, WNOHANG);
        if (ws == -1)
        { /* error - handle as you wish */
        }

        if( WIFEXITED(childExitStatus)) /* exit code in childExitStatus */
        {
            status = WEXITSTATUS(childExitStatus); /* zero is normal exit */
            /* handle non-zero as you wish */
        }
        else if (WIFSIGNALED(childExitStatus)) /* killed */
        {
        }
        else if (WIFSTOPPED(childExitStatus)) /* stopped */
        {
        }
    }
}

C++, copy set to vector

Just use the constructor for the vector that takes iterators:

std::set<T> s;

//...

std::vector v( s.begin(), s.end() );

Assumes you just want the content of s in v, and there's nothing in v prior to copying the data to it.

Move top 1000 lines from text file to a new file using Unix shell commands

head -1000 file.txt > first100lines.txt
tail --lines=+1001 file.txt > restoffile.txt

what is the difference between OLE DB and ODBC data sources?

On a very basic level those are just different APIs for the different data sources (i.e. databases). OLE DB is newer and arguably better.

You can read more on both in Wikipedia:

  1. OLE DB
  2. ODBC

I.e. you could connect to the same database using an ODBC driver or OLE DB driver. The difference in the database behaviour in those cases is what your book refers to.

How to remove last n characters from a string in Bash?

You can do like this:

#!/bin/bash

v="some string.rtf"

v2=${v::-4}

echo "$v --> $v2"

How to try convert a string to a Guid

This will get you pretty close, and I use it in production and have never had a collision. However, if you look at the constructor for a guid in reflector, you will see all of the checks it makes.

 public static bool GuidTryParse(string s, out Guid result)
    {
        if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
        {
            result = new Guid(s);
            return true;
        }

        result = default(Guid);
        return false;
    }

    static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
                          "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
                          "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Compiled);

IIS7 folder permissions for web application

  1. Working on IIS 7.5 and Windows 7 i couldnt give permission APPPOOL/Mypool
  2. IUSR and IIS_IUSRS permissions not working for me
  3. I got to problem this way:

    -Created console application with C#
    -This appliaction using createeventsource like this

    if(!System.Diagnostics.EventLog.SourceExists(sourceName)) System.Diagnostics.EventLog.CreateEventSource(sourceName,logName);

    -Build solution and get .exe file

    -Run exe as administator.This create log file.

NOTE: Dont remember Event viewer must be refresh for see the log.

I hope this solution helps someone :)

What does "static" mean in C?

A static variable value persists between different function calls andits scope is limited to the local block a static var always initializes with value 0

The remote end hung up unexpectedly while git cloning

I have the same error while using BitBucket. What I did was remove https from the URL of my repo and set the URL using HTTP.

git remote set-url origin http://[email protected]/mj/pt.git

How to convert jsonString to JSONObject in Java

Use JsonNode of fasterxml for the Generic Json Parsing. It internally creates a Map of key value for all the inputs.

Example:

private void test(@RequestBody JsonNode node)

input String :

{"a":"b","c":"d"}

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

This is as pythonic as you can get:

for lat, long in zip(Latitudes, Longitudes):
    print(lat, long)

What's the best free C++ profiler for Windows?

There is an instrumenting (function-accurate) profiler for MS VC 7.1 and higher called MicroProfiler. You can get it here (x64) or here (x86). It doesn't require any modifications or additions to your code and is able of displaying function statistics with callers and callees in real-time without the need of closing application/stopping the profiling process.

It integrates with VisualStudio, so you can easily enable/disable profiling for a project. It is also possible to install it on the clean machine, it only needs the symbol information be located along with the executable being profiled.

This tool is useful when statistical approximation from sampling profilers like Very Sleepy isn't sufficient.

Rough comparison shows, that it beats AQTime (when it is invoked in instrumenting, function-level run). The following program (full optimization, inlining disabled) runs three times faster with micro-profiler displaying results in real-time, than with AQTime simply collecting stats:

void f()
{
    srand(time(0));

    vector<double> v(300000);

    generate_n(v.begin(), v.size(), &random);
    sort(v.begin(), v.end());
    sort(v.rbegin(), v.rend());
    sort(v.begin(), v.end());
    sort(v.rbegin(), v.rend());
}

Extension methods must be defined in a non-generic static class

change

public class LinqHelper

to

public static class LinqHelper

Following points need to be considered when creating an extension method:

  1. The class which defines an extension method must be non-generic, static and non-nested
  2. Every extension method must be a static method
  3. The first parameter of the extension method should use the this keyword.

At runtime, find all classes in a Java application that extend a base class

One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):

public class Dog extends Animal{

static
{
   Animal a = new Dog();
   //add a to the List
}

It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.

Writing to a new file if it doesn't exist, and appending to a file if it does

Just open it in 'a' mode:

a   Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

with open(filename, 'a') as f:
    f.write(...)

To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.

with open('somefile.txt', 'a') as f:
    if f.tell() == 0:
        print('a new file or the file was empty')
        f.write('The header\n')
    else:
        print('file existed, appending')
    f.write('Some data\n')

If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END) right after open or use io.open instead.

Inline SVG in CSS

On Mac/Linux, you can easily convert a SVG file to a base64 encoded value for CSS background attribute with this simple bash command:

echo "background: transparent url('data:image/svg+xml;base64,"$(openssl base64 < path/to/file.svg)"') no-repeat center center;"

Tested on Mac OS X. This way you also avoid the URL escaping mess.

Remember that base64 encoding an SVG file increase its size, see css-tricks.com blog post.

Can I append an array to 'formdata' in javascript?

use "xxx[]" as name of the field in formdata (you will get an array of - stringified objects - in you case)

so within your loop

$('.tag-form').each(function(i){
            article = $(this).find('input[name="article"]').val();
            gender = $(this).find('input[name="gender"]').val();
            brand = $(this).find('input[name="brand"]').val();
            this_tag = new Array();
            this_tag.article = article;
            this_tag.gender = gender;
            this_tag.brand = brand;
            //tags.push(this_tag);    
            formdata.append('tags[]', this_tag);
...

What is the meaning of curly braces?

A dictionary is something like an array that's accessed by keys (e.g. strings,...) rather than just plain sequential numbers. It contains key/value pairs, you can look up values using a key like using a phone book: key=name, number=value.

For defining such a dictionary, you use this syntax using curly braces, see also: http://wiki.python.org/moin/SimplePrograms

scale Image in an UIButton to AspectFit?

1 - clear Button default text (important)

2 - set alignment like image

3 - set content mode like image

enter image description here

Updating a java map entry

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Subversion ignoring "--password" and "--username" options

The problem was that the working copy was checked out via svn+ssh (thanks, Thomas). Instead of setting up ssh keys as was suggested, I just checked out a new working copy using svn://domain.com/path/to/repo rather than svn+ssh://domain.com/path/to/repo. Because this working copy is on the same machine as the repository itself, I'm not really missing out on anything, and I can now use the --password and --username options gratuitously. Seems obvious now that I think about it.

What are the advantages and disadvantages of recursion?

Some situation would arise where you would have to abandon recursion in a problem where recursion appears to be to your advantage, this is because for problems where your recursion would have to occur thousand of times this would result in a stackoverflow error even though your code did not get stuck in an infinite recursion. Most programming languages limits you to a number of stack calls, so if your recursion goes beyond this limit, then you might consider not using recursion.

Check if a div exists with jquery

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

Setting default values to null fields when mapping with Jackson

There are already a lot of good suggestions, but here's one more. You can use @JsonDeserialize to perform an arbitrary "sanitizer" which Jackson will invoke post-deserialization:

@JsonDeserialize(converter=Message1._Sanitizer.class)  
public class Message1 extends MessageBase
{
    public String string1 = "";
    public int integer1;

    public static class _Sanitizer extends StdConverter<Message1,Message1> {
        @Override
        public Message1 convert(Message1 message) {
            if (message.string1 == null) message.string1 = "";
            return message;
        }
    }
}

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

Although many answers have been given, the problem I encountered was not yet mentioned.

  • My Scenario: 64-Bit Application, Win10-64, Office 2007 32-Bit installed.
  • Installation of the 32-Bit Installer AccessDatabaseEngine.exe as downloaded from MS reports success, but is NOT installed, as verified with the Powershell Script of one of the postings above here.

  • Installation of the 64-Bit installer AccessDatabaseEngine_X64.exe reported a shocking error message:

enter image description here

The very simple solution has been found here on an Autodesk site. Just add the parameter /passive to the commandline string, like this:

AccessDatabaseEngine_X64.exe /passive

Installation successful, the OleDb driver worked.

The Excel files I am processing with OleDb are of xlsx type, produced with EPPlus 4.5 and modified with Excel 2007.

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

How to specify font attributes for all elements on an html web page?

If you specify CSS attributes for your body element it should apply to anything within <body></body> so long as you don't override them later in the stylesheet.

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

What Are Some Good .NET Profilers?

If you're on ASP.NET MVC, you can try MVCMiniProfiler (http://benjii.me/2011/07/using-the-mvc-mini-profiler-with-entity-framework/)

jQuery posting JSON

In case you are sending this post request to a cross domain, you should check out this link.

https://stackoverflow.com/a/1320708/969984

Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

Ansible: How to delete files and folders inside a directory?

That's what I come up with:

- name: Get directory listing
  find:
    path: "{{ directory }}" 
    file_type: any
    hidden: yes
  register: directory_content_result

- name: Remove directory content
  file:
    path: "{{ item.path }}" 
    state: absent
  with_items: "{{ directory_content_result.files }}" 
  loop_control:
    label: "{{ item.path }}" 

First, we're getting directory listing with find, setting

  • file_type to any, so we wouldn't miss nested directories and links
  • hidden to yes, so we don't skip hidden files
  • also, do not set recurse to yes, since it is not only unnecessary, but may increase execution time.

Then, we go through that list with file module. It's output is a bit verbose, so loop_control.label will help us with limiting output (found this advice here).


But I found previous solution to be somewhat slow, since it iterates through the content, so I went with:

- name: Get directory stats
  stat:
    path: "{{ directory }}"
  register: directory_stat

- name: Delete directory
  file:
    path: "{{ directory }}"
    state: absent

- name: Create directory
  file:
    path: "{{ directory }}"
    state: directory
    owner: "{{ directory_stat.stat.pw_name }}"
    group: "{{ directory_stat.stat.gr_name }}"
    mode: "{{ directory_stat.stat.mode }}"
  • get directory properties with the stat
  • delete directory
  • recreate directory with the same properties.

That was enough for me, but you can add attributes as well, if you want.

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

HashMap allows duplicates?

Code example:

HashMap<Integer,String> h = new HashMap<Integer,String> ();

h.put(null,null);
h.put(null, "a");

System.out.println(h);

Output:

{null=a}

It overrides the value at key null.

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

How do I best silence a warning about unused variables?

macro-less and portable way to declare one or more parameters as unused:

template <typename... Args> inline void unused(Args&&...) {}

int main(int argc, char* argv[])
{
    unused(argc, argv);
    return 0;
}

Mean per group in a data.frame

A third great alternative is using the package data.table, which also has the class data.frame, but operations like you are looking for are computed much faster.

library(data.table)
mydt <- structure(list(Name = c("Aira", "Aira", "Aira", "Ben", "Ben", "Ben", "Cat", "Cat", "Cat"), Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(15.6396600443877, 2.15649279424609, 6.24692918928743, 2.37658797276116, 34.7500663272292, 3.28750138697048, 29.3265553981065, 17.9821839334431, 10.8639802575958), Rate2 = c(17.1680489538369, 5.84231656330206, 8.54330866437461, 5.88415184986176, 3.02064294862551, 17.2053351400752, 16.9552950199166, 2.56058000170089, 15.7496228048122)), .Names = c("Name", "Month", "Rate1", "Rate2"), row.names = c(NA, -9L), class = c("data.table", "data.frame"))

Now to take the mean of Rate1 and Rate2 for all 3 months, for each person (Name): First, decide which columns you want to take the mean of

colstoavg <- names(mydt)[3:4]

Now we use lapply to take the mean over the columns we want to avg (colstoavg)

mydt.mean <- mydt[,lapply(.SD,mean,na.rm=TRUE),by=Name,.SDcols=colstoavg]

 mydt.mean
   Name     Rate1     Rate2
1: Aira  8.014361 10.517891
2:  Ben 13.471385  8.703377
3:  Cat 19.390907 11.755166

curl: (60) SSL certificate problem: unable to get local issuer certificate

I have solved this problem by adding one line code in cURL script:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Warning: This makes the request absolute insecure (see answer by @YSU)!

How get value from URL

You can get that value by using the $_GET array. So the id value would be stored in $_GET['id'].

So in your case you could store that value in the $id variable as follows:

$id = $_GET['id'];

regex to remove all text before a character

Variant of Tim's one, good only on some implementations of Regex: ^.*?_

var subjectString = "3.04_somename.jpg";
var resultString = Regex.Replace(subjectString,
    @"^   # Match start of string
    .*?   # Lazily match any character, trying to stop when the next condition becomes true
    _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

How to quickly and conveniently disable all console.log statements in my code?

I think that the easiest and most understandable method in 2020 is to just create a global function like log() and you can pick one of the following methods:

const debugging = true;

function log(toLog) {
  if (debugging) {
    console.log(toLog);
  }
}
function log(toLog) {
  if (true) { // You could manually change it (Annoying, though)
    console.log(toLog);
  }
}

You could say that the downside of these features is that:

  1. You are still calling the functions on runtime
  2. You have to remember to change the debugging variable or the if statement in the second option
  3. You need to make sure you have the function loaded before all of your other files

And my retorts to these statements is that this is the only method that won't completely remove the console or console.log function which I think is bad programming because other developers who are working on the website would have to realize that you ignorantly removed them. Also, you can't edit JavaScript source code in JavaScript, so if you really want something to just wipe all of those from the code you could use a minifier that minifies your code and removes all console.logs. Now, the choice is yours, what will you do?

how to add value to a tuple?

Based on the syntax, I'm guessing this is Python. The point of a tuple is that it is immutable, so you need to replace each element with a new tuple:

list = [l + (''.join(l),) for l in list]
# output:
[('1', '2', '3', '4', '1234'), 
 ('2', '3', '4', '5', '2345'), 
 ('3', '4', '5', '6', '3456'), 
 ('4', '5', '6', '7', '4567')]

git clone from another directory

It's as easy as it looks.

14:27:05 ~$ mkdir gittests
14:27:11 ~$ cd gittests/
14:27:13 ~/gittests$ mkdir localrepo
14:27:20 ~/gittests$ cd localrepo/
14:27:21 ~/gittests/localrepo$ git init
Initialized empty Git repository in /home/andwed/gittests/localrepo/.git/
14:27:22 ~/gittests/localrepo (master #)$ cd ..
14:27:35 ~/gittests$ git clone localrepo copyoflocalrepo
Cloning into 'copyoflocalrepo'...
warning: You appear to have cloned an empty repository.
done.
14:27:42 ~/gittests$ cd copyoflocalrepo/
14:27:46 ~/gittests/copyoflocalrepo (master #)$ git status
On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)
14:27:46 ~/gittests/copyoflocalrepo (master #)$ 

How to simulate "Press any key to continue?"

Another option is using threads with function pointers:

#include <iostream>
#include <thread> // this_thread::sleep_for() and thread objects
#include <chrono> // chrono::milliseconds()

bool stopWaitingFlag = false;

void delayms(int millisecondsToSleep) 
{
  std::this_thread::sleep_for(std::chrono::milliseconds(millisecondsToSleep));
}

void WaitForKey() 
{
  while (stopWaitingFlag == false)
  {
    std::cout<<"Display from the thread function"<<std::endl;
    delayms(1000);
  }
}

 

int main()
{
  std::thread threadObj(&WaitForKey);

  char userInput = '\0';
  while (userInput != 'y')
  {
    std::cout << "\e[1;31mWaiting for a key, Enter 'y' for yes\e[0m" << std::endl;
    std::cin >> userInput;
    if (userInput == 'y') {
      stopWaitingFlag = true;
    }
  }
  if (threadObj.joinable())
    threadObj.join();

  std::cout<<"Exit of Main function"<<std::endl;
  return 0;
}

How do I format a date as ISO 8601 in moment.js?

When you use Mongoose to store dates into MongoDB you need to use toISOString() because all dates are stored as ISOdates with miliseconds.

moment.format() 

2018-04-17T20:00:00Z

moment.toISOString() -> USE THIS TO STORE IN MONGOOSE

2018-04-17T20:00:00.000Z

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

How to dynamically remove items from ListView on a button click?

 List<String> entries;
 private ArrayAdapter<String> categoryAdapter;
 //Your list of entries {Example: <"category1","category2","category3">}
 entries =  new ArrayList<String>();
 categoryAdapter = new ArrayAdapter<String>(ViewBeaconsActivity.this,
                                   android.R.layout.simple_list_item_1, entries);
 //Remove that specific category from the list
 entries.remove(categoryName);
 //Notify the adapter that your dataset has changed.
 categoryAdapter.notifyDataSetChanged();

How to make Toolbar transparent?

Add below code to styles.xml file

<style name="LayoutPageTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <!-- Support library compatibility -->
    <item name="windowActionBarOverlay">true</item>
    <item name="android:actionBarStyle">@style/TransparentActionBar</item>
</style>
<!-- ActionBar styles -->
<style name="TransparentActionBar"
    parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">@android:color/transparent</item>
</style>

          <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
           android:background="@android:color/transparent"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

Don't forget to write: android:background="@android:color/transparent"

How to remove lines in a Matplotlib plot

This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around.

WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.

Okay, here we go. Each matplotlib object (Figure, Axes, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating.

We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id()).

>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]

>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)

>>> #The object in ax is the same as the object in fig.axes[0], which is 
>>> #   a list of axes objects attached to fig 
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8)  #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects

This also extends to lines in an axes object:

>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))

>>> #Lines and ax.lines contain the same line2D instances 
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]

>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)

>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)

If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line:

A figure containing a set of axes and a single line

Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:

>>> id(lines), id(ax.lines)
(212754584, 211335288)

As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:

>>> #THIS DOES NOTHING:
>>> lines.pop(0)

>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)

So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:

>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and two lines

>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and only the second line

All of the above works for fig.axes just as well as it works for ax.lines

Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn't get garbage collected:

>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]

>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn't have the same ID as ax.lines but contained the same elements? Well, that's the problem.

>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.

>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>

So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.

How to justify a single flexbox item (override justify-content)

I solved a similar case by setting the inner item's style to margin: 0 auto.
Situation: My menu usually contains three buttons, in which case they need to be justify-content: space-between. But when there's only one button, it will now be center aligned instead of to the left.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

On line 10 there's a space between s and t. It should be one word: stylesheet.

How can I change the language (to english) in Oracle SQL Developer?

Or use the menu: Tools->Preferences->Database->NLS and change language and territory. enter image description here

How to get the list of all database users

EXEC sp_helpuser

or

SELECT * FROM sysusers

Both of these select all the users of the current database (not the server).

Postgresql - unable to drop database because of some auto connections to DB

If no potential impact on other services on your machine, simply service postgresql restart

How to update an "array of objects" with Firestore?

#Edit (add explanation :) ) say you have an array you want to update your existing firestore document field with. You can use set(yourData, {merge: true} ) passing setOptions(second param in set function) with {merge: true} is must in order to merge the changes instead of overwriting. here is what the official documentation says about it

An options object that configures the behavior of set() calls in DocumentReference, WriteBatch, and Transaction. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a SetOptions with merge: true.

you can use this

const yourNewArray = [{who: "[email protected]", when:timestamp}
{who: "[email protected]", when:timestamp}]    


collectionRef.doc(docId).set(
  {
    proprietary: "jhon",
    sharedWith: firebase.firestore.FieldValue.arrayUnion(...yourNewArray),
  },
  { merge: true },
);

hope this helps :)

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

Execute raw SQL using Doctrine 2

In your model create the raw SQL statement (example below is an example of a date interval I had to use but substitute your own. If you are doing a SELECT add ->fetchall() to the execute() call.

   $sql = "DELETE FROM tmp 
            WHERE lastedit + INTERVAL '5 minute' < NOW() ";

    $stmt = $this->getServiceLocator()
                 ->get('Doctrine\ORM\EntityManager')
                 ->getConnection()
                 ->prepare($sql);

    $stmt->execute();

How can I make my website's background transparent without making the content (images & text) transparent too?

You probably want an extra wrapper. use a div for the background and position it below your content..

http://jsfiddle.net/pixelass/42F2j/

HTML

<div id="background-image"></div>
<div id="content">
    Here is the content at opacity 1
    <img src="http://lorempixel.com/100/50/fashion/1/">

</div>

CSS

#background-image {
    background-image: url(http://lorempixel.com/400/200/sports/1/);
    opacity:0.4;
    position:absolute;
    top:0;
    left:0;
    height:200px;
    width:400px;
    z-index:0;
}
#content {
    z-index:1;
    position:relative;
}

How do I find the parent directory in C#?

To get a 'grandparent' directory, call Directory.GetParent() twice:

var gparent = Directory.GetParent(Directory.GetParent(str_directory).ToString());

SQL how to increase or decrease one for a int column in one command

If my understanding is correct, updates should be pretty simple. I would just do the following.

UPDATE TABLE SET QUANTITY = QUANTITY + 1 and
UPDATE TABLE SET QUANTITY = QUANTITY - 1 where QUANTITY > 0

You may need additional filters to just update a single row instead of all the rows.

For inserts, you can cache some unique id related to your record locally and check against this cache and decide whether to insert or not. The alternative approach is to always insert and check for PK violation error and ignore since this is a redundant insert.

How to install a certificate in Xcode (preparing for app store submission)

These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)

a) Part on the developers' website:

Sign in into: https://developer.apple.com/

Member Center

Certificates, Identifiers & Profiles

Certificates>All

Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.

b) XCode part:

After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.

How do I toggle an element's class in pure JavaScript?

If you want to toggle a class to an element using native solution, you could try this suggestion. I have tasted it in different cases, with or without other classes onto the element, and I think it works pretty much:

(function(objSelector, objClass){
   document.querySelectorAll(objSelector).forEach(function(o){
      o.addEventListener('click', function(e){
        var $this = e.target,
            klass = $this.className,
            findClass = new RegExp('\\b\\s*' + objClass + '\\S*\\s?', 'g');

        if( !findClass.test( $this.className ) )
            if( klass ) 
                $this.className = klass + ' ' + objClass;
            else 
                $this.setAttribute('class', objClass);
        else 
        {
            klass = klass.replace( findClass, '' );
            if(klass) $this.className = klass;
            else $this.removeAttribute('class');
        }
    });
  });
})('.yourElemetnSelector', 'yourClass');

How do I get the IP address into a batch-file variable?

I know this is an older post but I ran across this while trying to solve the same problem in vbscript. I haven't tested this with mulitple network adapters but hope that it's helpful nonetheless.

for /f "delims=: tokens=2" %%a in ('ipconfig ^| findstr /R /C:"IPv4 Address"') do (set tempip=%%a)  
set tempip=%tempip: =%  
echo %tempip%

This assumes Win7. For XP, replace IPv4 Address with IP Address.

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

Capturing standard out and error with Start-Process

I really had troubles with those examples from Andy Arismendi and from LPG. You should always use:

$stdout = $p.StandardOutput.ReadToEnd()

before calling

$p.WaitForExit()

A full example is:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$p.WaitForExit()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

Clear form after submission with jQuery

try this in your post methods callback function

$(':input','#myform')
 .not(':button, :submit, :reset, :hidden')
 .val('')
 .removeAttr('checked')
 .removeAttr('selected');

for more info read this

How to start a stopped Docker container with a different command?

I took @Dmitriusan's answer and made it into an alias:

alias docker-run-prev-container='prev_container_id="$(docker ps -aq | head -n1)" && docker commit "$prev_container_id" "prev_container/$prev_container_id" && docker run -it --entrypoint=bash "prev_container/$prev_container_id"'

Add this into your ~/.bashrc aliases file, and you'll have a nifty new docker-run-prev-container alias which'll drop you into a shell in the previous container.

Helpful for debugging failed docker builds.

How to unzip a file in Powershell?

Here is a simple way using ExtractToDirectory from System.IO.Compression.ZipFile:

Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
    param([string]$zipfile, [string]$outpath)

    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}

Unzip "C:\a.zip" "C:\a"

Note that if the target folder doesn't exist, ExtractToDirectory will create it. Other caveats:

See also:

PHP Fatal error: Cannot access empty property

This way you can create a new object with a custom property name.

$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);

Now you can reach it like:

echo $a->foo;  //returns bar

How to disable a particular checkstyle rule for a particular line of code?

If you prefer to use annotations to selectively silence rules, this is now possible using the @SuppressWarnings annotation, starting with Checkstyle 5.7 (and supported by the Checkstyle Maven Plugin 2.12+).

First, in your checkstyle.xml, add the SuppressWarningsHolder module to the TreeWalker:

<module name="TreeWalker">
    <!-- Make the @SuppressWarnings annotations available to Checkstyle -->
    <module name="SuppressWarningsHolder" />
</module>

Next, enable the SuppressWarningsFilter there (as a sibling to TreeWalker):

<!-- Filter out Checkstyle warnings that have been suppressed with the @SuppressWarnings annotation -->
<module name="SuppressWarningsFilter" />

<module name="TreeWalker">
...

Now you can annotate e.g. the method you want to exclude from a certain Checkstyle rule:

@SuppressWarnings("checkstyle:methodlength")
@Override
public boolean equals(Object obj) {
    // very long auto-generated equals() method
}

The checkstyle: prefix in the argument to @SuppressWarnings is optional, but I like it as a reminder where this warning came from. The rule name must be lowercase.

Lastly, if you're using Eclipse, it will complain about the argument being unknown to it:

Unsupported @SuppressWarnings("checkstyle:methodlength")

You can disable this Eclipse warning in the preferences if you like:

Preferences:
  Java
  --> Compiler
  --> Errors/Warnings
  --> Annotations
  --> Unhandled token in '@SuppressWarnings': set to 'Ignore'

jQuery find events handlers registered with an object

You can do it by crawling the events (as of jQuery 1.8+), like this:

$.each($._data($("#id")[0], "events"), function(i, event) {
  // i is the event type, like "click"
  $.each(event, function(j, h) {
    // h.handler is the function being called
  });
});

Here's an example you can play with:

_x000D_
_x000D_
$(function() {_x000D_
  $("#el").click(function(){ alert("click"); });_x000D_
  $("#el").mouseover(function(){ alert("mouseover"); });_x000D_
_x000D_
  $.each($._data($("#el")[0], "events"), function(i, event) {_x000D_
    output(i);_x000D_
    $.each(event, function(j, h) {_x000D_
        output("- " + h.handler);_x000D_
    });_x000D_
  });_x000D_
});_x000D_
_x000D_
function output(text) {_x000D_
    $("#output").html(function(i, h) {_x000D_
        return h + text + "<br />";_x000D_
    });_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="el">Test</div>_x000D_
<code>_x000D_
    <span id="output"></span>_x000D_
</code>
_x000D_
_x000D_
_x000D_

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

Resetting a setTimeout

To reset the timer, you would need to set and clear out the timer variable

$time_out_handle = 0;
window.clearTimeout($time_out_handle);
$time_out_handle = window.setTimeout( function(){---}, 60000 );

What is the iOS 5.0 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

iPad:

Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

How to save to local storage using Flutter?

A late answer but I hope it will help anyone visiting here later too..

I will provide categories to save and their respective best methods...

  1. Shared Preferences Use this when storing simple values on storage e.g Color theme, app language, last scroll position(in reading apps).. these are simple settings that you would want to persist when the app restarts.. You could, however, use this to store large things(Lists, Maps, Images) but that would require serialization and deserialization.. To learn more on this deserialization and serialization go here.
  2. Files This helps a lot when you have data that is defined more by you for example log files, image files and maybe you want to export csv files.. I heard that this type of persistence can be washed by storage cleaners once disk runs out of space.. Am not sure as i have never seen it.. This also can store almost anything but with the help of serialization and deserialization..
  3. Saving to a database This is enormously helpful in data which is a bit complex. And I think this doesn't get washed up by disc cleaners as it is stored in AppData(for android).. In this, your data is stored in an SQLite database. Its plugin is SQFLite. Kinds of data that you might wanna put in here are like everything that can be represented by a database.

What should a JSON service return on failure / error

If the user supplies invalid data, it should definitely be a 400 Bad Request (The request contains bad syntax or cannot be fulfilled.)

How to trigger an event in input text after I stop typing/writing?

I've been searching for a simple HTML/JS code and I did not found any. Then, I wrote the code below using onkeyup="DelayedSubmission()".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
    var date = new Date();
    initial_time = date.getTime();
    if (typeof setInverval_Variable == 'undefined') {
            setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
    } 
}
function DelayedSubmission_Check() {
    var date = new Date();
    check_time = date.getTime();
    var limit_ms=check_time-initial_time;
    if (limit_ms > 800) { //Change value in milliseconds
        alert("insert your function"); //Insert your function
        clearInterval(setInverval_Variable);
        delete setInverval_Variable;
    }
}

</script>
</head>
<body>

<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />

</body>
</html>

postgresql: INSERT INTO ... (SELECT * ...)

If you want insert into specify column:

INSERT INTO table (time)
(SELECT time FROM 
    dblink('dbname=dbtest', 'SELECT time FROM tblB') AS t(time integer) 
    WHERE time > 1000
);

How to change the buttons text using javascript

You can toggle filterstatus value like this

filterstatus ^= 1;

So your function looks like

function showFilterItem(objButton) {
if (filterstatus == 0) {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
    objButton.value = "Hide Filter";
}
else {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
    objButton.value = "Show filter";
}
  filterstatus ^= 1;    
}

How to handle the new window in Selenium WebDriver using Java?

I have a sample program for this:

public class BrowserBackForward {

/**
 * @param args
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumhq.org/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //maximize the window
    driver.manage().window().maximize();

    driver.findElement(By.linkText("Documentation")).click();
    System.out.println(driver.getCurrentUrl());
    driver.navigate().back();
    System.out.println(driver.getCurrentUrl());
    Thread.sleep(30000);
    driver.navigate().forward();
    System.out.println("Forward");
    Thread.sleep(30000);
    driver.navigate().refresh();

}

}

Java Round up Any Number

10 years later but that problem still caught me.

So this is the answer to those that are too late as me.

This does not work

int b = (int) Math.ceil(a / 100);

Cause the result a / 100 turns out to be an integer and it's rounded so Math.ceil can't do anything about it.

You have to avoid the rounded operation with this

int b = (int) Math.ceil((float) a / 100);

Now it works.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

 s=scan.nextLine();

It returns input was skipped.

so you might use

 s=scan.next();

Change Default branch in gitlab

For gitlab v10+ (as of Sept 2018), this has moved to settings-> repository -> default branch

enter image description here

As stated by @Luke this is still valid as on 4/1/2021

How does one represent the empty char?

There is no such thing as the "empty character" ''.

If you need a space character, that can be represented as a space: c[i] = ' ' or as its ASCII octal equivalent: c[i] = '\040'. If you need a NUL character that's c[i] = '\0'.

how to access iFrame parent page using jquery?

in parent window put :

<script>
function ifDoneChildFrame(val)
{
   $('#parentPrice').html(val);
}
</script>

and in iframe src file put :

<script>window.parent.ifDoneChildFrame('Your value here');</script>

How to check if there exists a process with a given pid in Python?

Combining Giampaolo Rodolà's answer for POSIX and mine for Windows I got this:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False

Describe table structure

For SQL Server use exec sp_help

USE db_name;
exec sp_help 'dbo.table_name'

For MySQL, use describe

DESCRIBE table_name;

How do I cancel form submission in submit button onclick event?

you should change the type from submit to button:

<input type='button' value='submit request'>

instead of

<input type='submit' value='submit request'>

you then get the name of your button in javascript and associate whatever action you want to it

var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};

worked for me hope it helps.

Where to find Application Loader app in Mac?

you can find it by going to xcode > open developer tool > application Loader

enter image description here

Set value of hidden field in a form using jQuery's ".val()" doesn't work

Another gotcha here wasted some of my time, so I thought I would pass along the tip. I had a hidden field I gave an id that had . and [] brackets in the name (due to use with struts2) and the selector $("#model.thefield[0]") would not find my hidden field. Renaming the id to not use the periods and brackets caused the selector to begin working. So in the end I ended up with an id of model_the_field_0 instead and the selector worked fine.

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

Have a variable in images path in Sass?

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

How to wait for a JavaScript Promise to resolve before resuming function?

If using ES2016 you can use async and await and do something like:

(async () => {
  const data = await fetch(url)
  myFunc(data)
}())

If using ES2015 you can use Generators. If you don't like the syntax you can abstract it away using an async utility function as explained here.

If using ES5 you'll probably want a library like Bluebird to give you more control.

Finally, if your runtime supports ES2015 already execution order may be preserved with parallelism using Fetch Injection.

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

How can I tell AngularJS to "refresh"

Why $apply should be called?

TL;DR: $apply should be called whenever you want to apply changes made outside of Angular world.


Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.

$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed. That step that checks to see if any binding values have changed actually has a method, $scope.$digest()1. We almost never call it directly, as we use $scope.$apply() instead (which will call $scope.$digest).

Angular only monitors variables used in expressions and anything inside of a $watch living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply() for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.

"Fatal error: Unable to find local grunt." when running "grunt" command

if you are a exists project, maybe should execute npm install.

guntjs getting started step 2.

Send email from localhost running XAMMP in PHP using GMAIL mail server

in php.ini file,uncomment this one

sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
;sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"

and in sendmail.ini

smtp_server=smtp.gmail.com
smtp_port=465
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=yourpassword
[email protected]
hostname=localhost

configure this one..it will works...it working fine for me.

thanks.

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

What is the difference between display: inline and display: inline-block?

All answers above contribute important info on the original question. However, there is a generalization that seems wrong.

It is possible to set width and height to at least one inline element (that I can think of) – the <img> element.

Both accepted answers here and on this duplicate state that this is not possible but this doesn’t seem like a valid general rule.

Example:

_x000D_
_x000D_
img {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  border: 1px solid red;_x000D_
}
_x000D_
<img src="#" />
_x000D_
_x000D_
_x000D_

The img has display: inline, but its width and height were successfully set.

Disabling and enabling a html input button

Since you are disabling it in the first place, the way to enable it is to set its disabled property as false.

To change its disabled property in Javascript, you use this:

var btn = document.getElementById("Button");
btn.disabled = false;

And obviously to disable it again, you'd use true instead.

Since you also tagged the question with jQuery, you could use the .prop method. Something like:

var btn = $("#Button");
btn.prop("disabled", true);   // Or `false`

This is in the newer versions of jQuery. The older way to do this is to add or remove an attribute like so:

var btn = $("#Button");
btn.attr("disabled", "disabled");
// or
btn.removeAttr("disabled");

The mere presence of the disabled property disables the element, so you cannot set its value as "false". Even the following should disable the element

<input type="button" value="Submit" disabled="" />

You need to either remove the attribute completely or set its property.

How to disable submit button once it has been clicked?

I don't think you need this.form.submit(). The disabling code should run, then it will pass on the click which will click the form.

What's the difference between [ and [[ in Bash?

The most important difference will be the clarity of your code. Yes, yes, what's been said above is true, but [[ ]] brings your code in line with what you would expect in high level languages, especially in regards to AND (&&), OR (||), and NOT (!) operators. Thus, when you move between systems and languages you will be able to interpret script faster which makes your life easier. Get the nitty gritty from a good UNIX/Linux reference. You may find some of the nitty gritty to be useful in certain circumstances, but you will always appreciate clear code! Which script fragment would you rather read? Even out of context, the first choice is easier to read and understand.


if [[ -d $newDir && -n $(echo $newDir | grep "^${webRootParent}") && -n $(echo $newDir | grep '/$') ]]; then ...

or

if [ -d "$newDir" -a -n "$(echo "$newDir" | grep "^${webRootParent}")" -a -n "$(echo "$newDir" | grep '/$')" ]; then ...

Regex match everything after question mark?

str.replace(/^.+?\"|^.|\".+/, '');

This is sometimes bad to use when you wanna select what else to remove between "" and you cannot use it more than twice in one string. All it does is select whatever is not in between "" and replace it with nothing.

Even for me it is a bit confusing, but ill try to explain it. ^.+? (not anything OPTIONAL) till first " then | Or/stop (still researching what it really means) till/at ^. has selected nothing until before the 2nd " using (| stop/at). And select all that comes after with .+.

Pandas index column title or name

You can use rename_axis, for removing set to None:

d = {'Index Title': ['Apples', 'Oranges', 'Puppies', 'Ducks'],'Column 1': [1.0, 2.0, 3.0, 4.0]}
df = pd.DataFrame(d).set_index('Index Title')
print (df)
             Column 1
Index Title          
Apples            1.0
Oranges           2.0
Puppies           3.0
Ducks             4.0

print (df.index.name)
Index Title

print (df.columns.name)
None

The new functionality works well in method chains.

df = df.rename_axis('foo')
print (df)
         Column 1
foo              
Apples        1.0
Oranges       2.0
Puppies       3.0
Ducks         4.0

You can also rename column names with parameter axis:

d = {'Index Title': ['Apples', 'Oranges', 'Puppies', 'Ducks'],'Column 1': [1.0, 2.0, 3.0, 4.0]}
df = pd.DataFrame(d).set_index('Index Title').rename_axis('Col Name', axis=1)
print (df)
Col Name     Column 1
Index Title          
Apples            1.0
Oranges           2.0
Puppies           3.0
Ducks             4.0

print (df.index.name)
Index Title

print (df.columns.name)
Col Name
print df.rename_axis('foo').rename_axis("bar", axis="columns")
bar      Column 1
foo              
Apples        1.0
Oranges       2.0
Puppies       3.0
Ducks         4.0

print df.rename_axis('foo').rename_axis("bar", axis=1)
bar      Column 1
foo              
Apples        1.0
Oranges       2.0
Puppies       3.0
Ducks         4.0

From version pandas 0.24.0+ is possible use parameter index and columns:

df = df.rename_axis(index='foo', columns="bar")
print (df)
bar      Column 1
foo              
Apples        1.0
Oranges       2.0
Puppies       3.0
Ducks         4.0

Removing index and columns names means set it to None:

df = df.rename_axis(index=None, columns=None)
print (df)
         Column 1
Apples        1.0
Oranges       2.0
Puppies       3.0
Ducks         4.0

If MultiIndex in index only:

mux = pd.MultiIndex.from_arrays([['Apples', 'Oranges', 'Puppies', 'Ducks'],
                                  list('abcd')], 
                                  names=['index name 1','index name 1'])


df = pd.DataFrame(np.random.randint(10, size=(4,6)), 
                  index=mux, 
                  columns=list('ABCDEF')).rename_axis('col name', axis=1)
print (df)
col name                   A  B  C  D  E  F
index name 1 index name 1                  
Apples       a             5  4  0  5  2  2
Oranges      b             5  8  2  5  9  9
Puppies      c             7  6  0  7  8  3
Ducks        d             6  5  0  1  6  0

print (df.index.name)
None

print (df.columns.name)
col name

print (df.index.names)
['index name 1', 'index name 1']

print (df.columns.names)
['col name']

df1 = df.rename_axis(('foo','bar'))
print (df1)
col name     A  B  C  D  E  F
foo     bar                  
Apples  a    5  4  0  5  2  2
Oranges b    5  8  2  5  9  9
Puppies c    7  6  0  7  8  3
Ducks   d    6  5  0  1  6  0

df2 = df.rename_axis('baz', axis=1)
print (df2)
baz                        A  B  C  D  E  F
index name 1 index name 1                  
Apples       a             5  4  0  5  2  2
Oranges      b             5  8  2  5  9  9
Puppies      c             7  6  0  7  8  3
Ducks        d             6  5  0  1  6  0

df2 = df.rename_axis(index=('foo','bar'), columns='baz')
print (df2)
baz          A  B  C  D  E  F
foo     bar                  
Apples  a    5  4  0  5  2  2
Oranges b    5  8  2  5  9  9
Puppies c    7  6  0  7  8  3
Ducks   d    6  5  0  1  6  0

Removing index and columns names means set it to None:

df2 = df.rename_axis(index=(None,None), columns=None)
print (df2)

           A  B  C  D  E  F
Apples  a  6  9  9  5  4  6
Oranges b  2  6  7  4  3  5
Puppies c  6  3  6  3  5  1
Ducks   d  4  9  1  3  0  5

For MultiIndex in index and columns is necessary working with .names instead .name and set by list or tuples:

mux1 = pd.MultiIndex.from_arrays([['Apples', 'Oranges', 'Puppies', 'Ducks'],
                                  list('abcd')], 
                                  names=['index name 1','index name 1'])


mux2 = pd.MultiIndex.from_product([list('ABC'),
                                  list('XY')], 
                                  names=['col name 1','col name 2'])

df = pd.DataFrame(np.random.randint(10, size=(4,6)), index=mux1, columns=mux2)
print (df)
col name 1                 A     B     C   
col name 2                 X  Y  X  Y  X  Y
index name 1 index name 1                  
Apples       a             2  9  4  7  0  3
Oranges      b             9  0  6  0  9  4
Puppies      c             2  4  6  1  4  4
Ducks        d             6  6  7  1  2  8

Plural is necessary for check/set values:

print (df.index.name)
None

print (df.columns.name)
None

print (df.index.names)
['index name 1', 'index name 1']

print (df.columns.names)
['col name 1', 'col name 2']

df1 = df.rename_axis(('foo','bar'))
print (df1)
col name 1   A     B     C   
col name 2   X  Y  X  Y  X  Y
foo     bar                  
Apples  a    2  9  4  7  0  3
Oranges b    9  0  6  0  9  4
Puppies c    2  4  6  1  4  4
Ducks   d    6  6  7  1  2  8

df2 = df.rename_axis(('baz','bak'), axis=1)
print (df2)
baz                        A     B     C   
bak                        X  Y  X  Y  X  Y
index name 1 index name 1                  
Apples       a             2  9  4  7  0  3
Oranges      b             9  0  6  0  9  4
Puppies      c             2  4  6  1  4  4
Ducks        d             6  6  7  1  2  8

df2 = df.rename_axis(index=('foo','bar'), columns=('baz','bak'))
print (df2)
baz          A     B     C   
bak          X  Y  X  Y  X  Y
foo     bar                  
Apples  a    2  9  4  7  0  3
Oranges b    9  0  6  0  9  4
Puppies c    2  4  6  1  4  4
Ducks   d    6  6  7  1  2  8

Removing index and columns names means set it to None:

df2 = df.rename_axis(index=(None,None), columns=(None,None))
print (df2)

           A     B     C   
           X  Y  X  Y  X  Y
Apples  a  2  0  2  5  2  0
Oranges b  1  7  5  5  4  8
Puppies c  2  4  6  3  6  5
Ducks   d  9  6  3  9  7  0

And @Jeff solution:

df.index.names = ['foo','bar']
df.columns.names = ['baz','bak']
print (df)

baz          A     B     C   
bak          X  Y  X  Y  X  Y
foo     bar                  
Apples  a    3  4  7  3  3  3
Oranges b    1  2  5  8  1  0
Puppies c    9  6  3  9  6  3
Ducks   d    3  2  1  0  1  0

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Thanks a bundle, guys. You are great.

I used Chuff's answer and modified it a little to do what I wanted.

I have 2 worksheets in the same workbook.

On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message

Then I inserted a new blank column next to the phone number

On worksheet 2 I have two columns: phone number, name of person

Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.

Then just copy the formula down the whole column until last sms It worked beautifully.

=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

What is the meaning of "Failed building wheel for X" in pip install?

I would like to add that if you only have Python3 on your system then you need to start using pip3 instead of pip.

You can install pip3 using the following command;

sudo apt install python3-pip -y

After this you can try to install the package you need with;

sudo pip3 install <package>

How to determine equality for two JavaScript objects?

I'm making the following assumptions with this function:

  1. You control the objects you are comparing and you only have primitive values (ie. not nested objects, functions, etc.).
  2. Your browser has support for Object.keys.

This should be treated as a demonstration of a simple strategy.

/**
 * Checks the equality of two objects that contain primitive values. (ie. no nested objects, functions, etc.)
 * @param {Object} object1
 * @param {Object} object2
 * @param {Boolean} [order_matters] Affects the return value of unordered objects. (ex. {a:1, b:2} and {b:2, a:1}).
 * @returns {Boolean}
 */
function isEqual( object1, object2, order_matters ) {
    var keys1 = Object.keys(object1),
        keys2 = Object.keys(object2),
        i, key;

    // Test 1: Same number of elements
    if( keys1.length != keys2.length ) {
        return false;
    }

    // If order doesn't matter isEqual({a:2, b:1}, {b:1, a:2}) should return true.
    // keys1 = Object.keys({a:2, b:1}) = ["a","b"];
    // keys2 = Object.keys({b:1, a:2}) = ["b","a"];
    // This is why we are sorting keys1 and keys2.
    if( !order_matters ) {
        keys1.sort();
        keys2.sort();
    }

    // Test 2: Same keys
    for( i = 0; i < keys1.length; i++ ) {
        if( keys1[i] != keys2[i] ) {
            return false;
        }
    }

    // Test 3: Values
    for( i = 0; i < keys1.length; i++ ) {
        key = keys1[i];
        if( object1[key] != object2[key] ) {
            return false;
        }
    }

    return true;
}

ECMAScript 6 class destructor

Is there such a thing as destructors for ECMAScript 6?

No. EcmaScript 6 does not specify any garbage collection semantics at all[1], so there is nothing like a "destruction" either.

If I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted

A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered.
What you are actually looking for is a method of registering listeners without marking them as live root objects. (Ask your local eventsource manufacturer for such a feature).

1): Well, there is a beginning with the specification of WeakMap and WeakSet objects. However, true weak references are still in the pipeline [1][2].

SVN- How to commit multiple files in a single shot

Same as the answer by Dmitry Yudakov, but without an intermediate file, using process substitution:

svn commit --targets <(echo "MyFile1.txt\nMyFile2.txt\n")

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If the SSH it gives you 2 options, choose number 1, and put "None". Just that...for the moment.

Calling a JSON API with Node.js

I think that for simple HTTP requests like this it's better to use the request module. You need to install it with npm (npm install request) and then your code can look like this:

const request = require('request')
     ,url = 'http://graph.facebook.com/517267866/?fields=picture'

request(url, (error, response, body)=> {
  if (!error && response.statusCode === 200) {
    const fbResponse = JSON.parse(body)
    console.log("Got a response: ", fbResponse.picture)
  } else {
    console.log("Got an error: ", error, ", status code: ", response.statusCode)
  }
})

How to create empty text file from a batch file?

IMPORTANT:

If you don't set the encoding, many softwares can break. git is a very popular example.

Set-Content "your_ignore_file.txt" .gitignore -Encoding utf8 this is case-sensitive and forces utf8 encoding!

How to check if an excel cell is empty using Apache POI?

If you're using Apache POI 4.x, you can do that with:

 Cell c = row.getCell(3);
 if (c == null || c.getCellType() == CellType.Blank) {
    // This cell is empty
 }

For older Apache POI 3.x versions, which predate the move to the CellType enum, it's:

 Cell c = row.getCell(3);
 if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
    // This cell is empty
 }

Don't forget to check if the Row is null though - if the row has never been used with no cells ever used or styled, the row itself might be null!

How to Disable GUI Button in Java

Is there a reason you are not doing something like:

public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;

    private JButton btnConvertDocuments;
    private JButton btnExtractImages;
    private JButton btnParseRIDValues;
    private JButton btnParseImageInfo;

    public IPGUI() 
    {
        ...

        btnConvertDocuments = new JButton("1. Convert Documents");

        ...

        btnExtractImages = new JButton("2. Extract Images");

        ...

        //etc.
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btnConvertDocuments.setEnabled( false );
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btnExtractImages.setEnabled( false );
        }

        // etc.
    }    
}

The if statement with your disabling code won't get called unless you keep calling the IPGUI constructor.

How to enter command with password for git pull?

Note that the way the git credential helper "store" will store the unencrypted passwords changes with Git 2.5+ (Q2 2014).
See commit 17c7f4d by Junio C Hamano (gitster)

credential-xdg

Tweak the sample "store" backend of the credential helper to honor XDG configuration file locations when specified.

The doc now say:

If not specified:

  • credentials will be searched for from ~/.git-credentials and $XDG_CONFIG_HOME/git/credentials, and
  • credentials will be written to ~/.git-credentials if it exists, or $XDG_CONFIG_HOME/git/credentials if it exists and the former does not.

How to use ADB to send touch events to device using sendevent command?

Consider using Android's uiautomator, with adb shell uiautomator [...] or directly using the .jar that comes with the SDK.

What is the difference between an abstract function and a virtual function?

An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.

A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.

So for example:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

My requirement was to keep the password in a config file in encrypted form and decrypt when the program runs. For this I used the jasypt library (jasypt-1.9.3.jar). This is a very good library and we can accomplish the task with just 4 lines of code.

First, after adding jar to my project I imported the below library.

import org.jasypt.util.text.AES256TextEncryptor;

Then I created the below method. I then called this method by passing the text which I need to encrypt in password parameter. Using aesEncryptor.encrypt method, I encrypted the password which is stored to the myEncryptedPassword variable.

public void EncryptPassword(String password)
{   
    AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
    aesEncryptor.setPassword("mypassword");
    String myEncryptedPassword = aesEncryptor.encrypt(password);
    System.out.println(myEncryptedPassword );       
}

You might have noticed the method setPassword method and the value mypassword is used in the above code. This is to make sure that no one can decrypt the password even if they use the encrypted password using the same library.

Now I can see the value in the myEncryptedPassword variable something like h9oJ4P5P8ToRy38wvK11PUQCBrT1oH/zbMWuMrbOlI0rfZrj+qSg6f/u0jctOs/ZUf9t3shiwnEt05/nq8bnag==. This is the encrypted password. Keep this value in the config file.

I then created the below method to decrypt the password to be used in my program. The value of passwordFromConfigFile is the encrypted text which I got from the EncryptPassword method. Note that you have to use the same password in the aesEncryptor.setPassword method that you used to encrypt the password.

public String DecryptPassword(String passwordFromConfigFile)
{           
    AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
    aesEncryptor.setPassword("mypassword");
    String decryptedPassword = aesEncryptor.decrypt(passwordFromConfigFile);
    return decryptedPassword;   
}

The variable decryptedPassword will now have the decrypted password value.

How to create a database from shell command?

cat filename.sql | mysql -u username -p # type mysql password when asked for it

Where filename.sql holds all the sql to create your database. Or...

echo "create database `database-name`" | mysql -u username -p

If you really only want to create a database.

Image style height and width not taken in outlook mails

_x000D_
_x000D_
<img id="_x005Fi1026" src="images/img.jpg" width="120" height="150" />
_x000D_
_x000D_
_x000D_

This worked for me both in gmail and outlook.

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

jQuery delete all table rows except first


$("#p-items").find( 'tr.row-items' ).remove();

convert NSDictionary to NSString

if you like to use for URLRequest httpBody

extension Dictionary {

    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }

}

// print: Fields=sdad&ServiceId=1222

Combine several images horizontally with Python

Edit: DTing's answer is more applicable to your question since it uses PIL, but I'll leave this up in case you want to know how to do it in numpy.

Here is a numpy/matplotlib solution that should work for N images (only color images) of any size/shape.

import numpy as np
import matplotlib.pyplot as plt

def concat_images(imga, imgb):
    """
    Combines two color image ndarrays side-by-side.
    """
    ha,wa = imga.shape[:2]
    hb,wb = imgb.shape[:2]
    max_height = np.max([ha, hb])
    total_width = wa+wb
    new_img = np.zeros(shape=(max_height, total_width, 3))
    new_img[:ha,:wa]=imga
    new_img[:hb,wa:wa+wb]=imgb
    return new_img

def concat_n_images(image_path_list):
    """
    Combines N color images from a list of image paths.
    """
    output = None
    for i, img_path in enumerate(image_path_list):
        img = plt.imread(img_path)[:,:,:3]
        if i==0:
            output = img
        else:
            output = concat_images(output, img)
    return output

Here is example use:

>>> images = ["ronda.jpeg", "rhod.jpeg", "ronda.jpeg", "rhod.jpeg"]
>>> output = concat_n_images(images)
>>> import matplotlib.pyplot as plt
>>> plt.imshow(output)
>>> plt.show()

enter image description here

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Opaque will cause less system strain since 'transparent' will still attempt to apply alpha. The reason you see transparent used instead is because most web authors don't pay attention to detail (ie, just copy-pasted some embed code they found).

BTW, you are correct about it being undocumented. The best I've ever seen is a blog by a guy who claims to have talked to a Macromedia developer about it. Unfortunaetly I can't find the link.

EDIT: I think it was this one: http://www.communitymx.com/content/article.cfm?cid=e5141

Create unique constraint with null columns

I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.

That would lead to the reduced table definition:

CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);

twitter bootstrap navbar fixed top overlapping site

For handling wrapping lines in menu-bar, apply an id to the navbar, like this:

<div class="navbar navbar-default navbar-fixed-top" role="navigation" id="topnavbar">

and add this small script in the head after including the jquery, like this:

<script>
    $(document).ready(function(){
        $(document.body).css('padding-top', $('#topnavbar').height() + 10);
        $(window).resize(function(){
            $(document.body).css('padding-top', $('#topnavbar').height() + 10);
        });
    });
</script>

That way, the top-padding of the body gets automatically adjusted.

facebook: permanent Page Access Token?

I found this answer which refers to this tool which really helped a lot.

I hope this answer is still valid when you read this.

How do you get the current time of day?

Another option using String.Format()

string.Format("{0:HH:mm:ss tt}", DateTime.Now)

How to add text inside the doughnut chart using Chart.js?

I create a demo with 7 jQueryUI Slider and ChartJs (with dynamic text inside)

Chart.types.Doughnut.extend({
        name: "DoughnutTextInside",
        showTooltip: function() {
            this.chart.ctx.save();
            Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);
            this.chart.ctx.restore();
        },
        draw: function() {
            Chart.types.Doughnut.prototype.draw.apply(this, arguments);

            var width = this.chart.width,
                height = this.chart.height;

            var fontSize = (height / 140).toFixed(2);
            this.chart.ctx.font = fontSize + "em Verdana";
            this.chart.ctx.textBaseline = "middle";

            var red = $( "#red" ).slider( "value" ),
            green = $( "#green" ).slider( "value" ),
            blue = $( "#blue" ).slider( "value" ),
            yellow = $( "#yellow" ).slider( "value" ),
            sienna = $( "#sienna" ).slider( "value" ),
            gold = $( "#gold" ).slider( "value" ),
            violet = $( "#violet" ).slider( "value" );
            var text = (red+green+blue+yellow+sienna+gold+violet) + " minutes";
            var textX = Math.round((width - this.chart.ctx.measureText(text).width) / 2);
            var textY = height / 2;
            this.chart.ctx.fillStyle = '#000000';
            this.chart.ctx.fillText(text, textX, textY);
        }
    });


var ctx = $("#myChart").get(0).getContext("2d");
var myDoughnutChart = new Chart(ctx).DoughnutTextInside(data, {
    responsive: false
});

DEMO IN JSFIDDLE

enter image description here

Set environment variables on Mac OS X Lion

Let me illustrate you from my personal example in a very redundant way.

  1. First after installing JDK, make sure it's installed. enter image description here
  2. Sometimes macOS or Linux automatically sets up environment variable for you unlike Windows. But that's not the case always. So let's check it. enter image description here The line immediately after echo $JAVA_HOME would be empty if the environment variable is not set. It must be empty in your case.

  3. Now we need to check if we have bash_profile file. enter image description here You saw that in my case we already have bash_profile. If not we have to create a bash_profile file.

  4. Create a bash_profile file. enter image description here

  5. Check again to make sure bash_profile file is there. enter image description here

  6. Now let's open bash_profile file. macOS opens it using it's default TextEdit program. enter image description here

  7. This is the file where environment variables are kept. If you have opened a new bash_profile file, it must be empty. In my case, it was already set for python programming language and Anaconda distribution. Now, i need to add environment variable for Java which is just adding the first line. YOU MUST TYPE the first line VERBATIM. JUST the first line. Save and close the TextEdit. Then close the terminal. enter image description here

  8. Open the terminal again. Let's check if the environment variable is set up. enter image description here

Generic type conversion FROM string

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

How to import or copy images to the "res" folder in Android Studio?

  1. Go to your image in windows, then press ctrl + c OR Right click and Copy

  2. Go to Your res Folder And choose One of the folders(eg. MDPI, HDPI..) and press ctrl + v OR right click it and Paste

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

List of all index & index columns in SQL Server DB

with connect(schema_name,table_name,index_name,index_column_id,column_name) as
(   select s.name schema_name, t.name table_name, i.name index_name, index_column_id, cast(c.name as varchar(max)) column_name
 from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
        inner join sys.columns c on c.object_id = t.object_id and
                ic.column_id = c.column_id
                where index_column_id=1
union all
select s.name schema_name, t.name table_name, i.name index_name, ic.index_column_id, cast(connect.column_name + ',' + c.name as varchar(max)) column_name
 from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id=i.index_id
        inner join sys.columns c on c.object_id = t.object_id and
                ic.column_id = c.column_id join connect on
connect.index_column_id+1 = ic.index_column_id
and connect.schema_name = s.name
and connect.table_name = t.name
and connect.index_name = i.name)
select connect.schema_name,connect.table_name,connect.index_name,connect.column_name
from connect join (select schema_name,table_name,index_name,MAX(index_column_id) index_column_id
from connect group by schema_name,table_name,index_name) mx
on connect.schema_name = mx.schema_name
and connect.table_name = mx.table_name
and connect.index_name = mx.index_name
and connect.index_column_id = mx.index_column_id
order by 1,2,3

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
metadata:
  name: service-y
  namespace: namespace-a
spec:
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  ports:
  - port: 80

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Python: Passing variables between functions

Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.

def defineAList():
    #list = ['1','2','3'] this creates a new list, named list in the current namespace.
    #same name, different list!

    list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
    print "For checking purposes: in defineAList, list is",list
    return list

Alternatively, you can pass it around:

def main():
    new_list = defineAList()
    useTheList(new_list)

How to calculate UILabel height dynamically?

The current solution has been deprecated as of iOS 7.

Here is an updated solution:

+ (CGFloat)heightOfCellWithIngredientLine:(NSString *)ingredientLine
                       withSuperviewWidth:(CGFloat)superviewWidth
{
    CGFloat labelWidth                  = superviewWidth - 30.0f;
    //    use the known label width with a maximum height of 100 points
    CGSize labelContraints              = CGSizeMake(labelWidth, 100.0f);

    NSStringDrawingContext *context     = [[NSStringDrawingContext alloc] init];

    CGRect labelRect                    = [ingredientLine boundingRectWithSize:labelContraints
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                     attributes:nil
                                                        context:context];

    //    return the calculated required height of the cell considering the label
    return labelRect.size.height;
}

The reason that my solution is set up like this is because I am using a UITableViewCell and resizing the cell dynamically relative to how much room the label will take up.

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

C programming: Dereferencing pointer to incomplete type error

You haven't defined struct stasher_file by your first definition. What you have defined is an nameless struct type and a variable stasher_file of that type. Since there's no definition for such type as struct stasher_file in your code, the compiler complains about incomplete type.

In order to define struct stasher_file, you should have done it as follows

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

Note where the stasher_file name is placed in the definition.

Git in Visual Studio - add existing project?

Here is how to do it in Visual Studio 2015.

  1. Open the project and go to Tools >> Options >> "Source Control" tab and select "Git" as your source control. enter image description here

  2. Go to File Menu and select "Add to source control".

What this does is essentially execute "git init" by visual studio creating all the bells and whistles (setup ignore files accordingly like ignore user specific files, temporary files, directory etc).

Essentially your git repository has been created correct locally (this is the major step with VS project since this folder contains a lot of files that we want to ignore).

Now you can connect this git repository to any other git like GitHub, BitBucket etc in git bash (outside Visual Studio).

I start Git Bash session now in this working directory and since I use BitBucket, I follow the instructions given there (just copy the lines below from there).

git remote add origin https://[email protected]/yourusername/hookdemo.git

git push -u origin master

That's it.

Afterwards you can manage the repository on git command line itself since its setup properly now.

Delete element in a slice

Where a is the slice, and i is the index of the element you want to delete:

a = append(a[:i], a[i+1:]...)

... is syntax for variadic arguments in Go.

Basically, when defining a function it puts all the arguments that you pass into one slice of that type. By doing that, you can pass as many arguments as you want (for example, fmt.Println can take as many arguments as you want).

Now, when calling a function, ... does the opposite: it unpacks a slice and passes them as separate arguments to a variadic function.

So what this line does:

a = append(a[:0], a[1:]...)

is essentially:

a = append(a[:0], a[1], a[2])

Now, you may be wondering, why not just do

a = append(a[1:]...)

Well, the function definition of append is

func append(slice []Type, elems ...Type) []Type

So the first argument has to be a slice of the correct type, the second argument is the variadic, so we pass in an empty slice, and then unpack the rest of the slice to fill in the arguments.

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx) http://www.ofx.net/

This is what apps like quicken, ms money etc use.

How can I get session id in php and show it?

You have uniqid function for unique id

You can add prefix to make it more unique

Source : http://pk1.php.net/uniqid

How do you set a JavaScript onclick event to a class with css

It can't be done via CSS as CSS only changes the presentation (e.g. only Javascript can make the alert popup). I'd strongly recommend you check out a Javascript library called jQuery as it makes doing something like this trivial:

$(document).ready(function(){
  $("a").click(function(){
    alert("hohoho");
  });
});

javascript window.location in new tab

window.open('https://support.wwf.org.uk', '_blank');

The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :)

Zip folder in C#

There is a ZipPackage class in the System.IO.Packaging namespace which is built into .NET 3, 3.5, and 4.0.

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

Here is an example how to use it. http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command line using

D:\>xcopy myfile.dat xcopytest\test\

and the target directory was properly created.

If not you can create the target dir using the mkdir command with cmd's command extensions enabled like

cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"

('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd)

use

cmd /? 
mkdir /?
xcopy /?

for further information :)

Why is PHP session_destroy() not working?

After using session_destroy(), the session is destroyed behind the scenes. For some reason this doesn't affect the values in $_SESSION, which was already populated for this request, but it will be empty in future requests.

You can manually clear $_SESSION if you so desire ($_SESSION = [];).

MySQL: Can't create table (errno: 150)

From the MySQL - FOREIGN KEY Constraints Documentation:

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails due to Error 150, this means that a foreign key definition would be incorrectly formed for the altered table.

Create text file and fill it using bash

If you're wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):

#!/bin/bash
if [ -e $1 ]; then
  echo "File $1 already exists!"
else
  echo >> $1
fi

If you don't want the "already exists" message, you can use:

#!/bin/bash
if [ ! -e $1 ]; then
  echo >> $1
fi

Edit about using:

Save whichever version with a name you like, let's say "create_file" (quotes mine, you don't want them in the file name). Then, to make the file executatble, at a command prompt do:

chmod u+x create_file

Put the file in a directory in your path, then use it with:

create_file NAME_OF_NEW_FILE

The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.

How to get document height and width without using jquery

Get document size without jQuery

document.documentElement.clientWidth
document.documentElement.clientHeight

And use this if you need Screen size

screen.width
screen.height

What is the best method of handling currency/money?

Common practice for handling currency is to use decimal type. Here is a simple example from "Agile Web Development with Rails"

add_column :products, :price, :decimal, :precision => 8, :scale => 2 

This will allow you to handle prices from -999,999.99 to 999,999.99
You may also want to include a validation in your items like

def validate 
  errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01 
end 

to sanity-check your values.

How to see top processes sorted by actual memory usage?

You can see memory usage by executing this code in your terminal:

$ watch -n2 free -m
$ htop

Install a module using pip for specific python version

You can execute pip module for a specific python version using the corresponding python:

Python 2.6:

python2.6 -m pip install beautifulsoup4

Python 2.7

python2.7 -m pip install beautifulsoup4

How to convert an OrderedDict into a regular dict in python3

>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!

how to remove the dotted line around the clicked a element in html

In my case it was a button, and apparently, with buttons, this is only a problem in Firefox. Solution found here:

button::-moz-focus-inner {
  border: 0;
}

How to prepend a string to a column value in MySQL?

UPDATE tablename SET fieldname = CONCAT("test", fieldname) [WHERE ...]

How to sort an object array by date property?

I personally use following approach to sort dates.

let array = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];

array.sort(function(date1, date2) {
   date1 = new Date(date1);
   date2 = new Date(date2);
   if (date1 > date2) return 1;
   if (date1 < date2) return -1;
})

Best way to convert list to comma separated string in java

The Separator you are using is a UI component. You would be better using a simple String sep = ", ".

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.

If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:

RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

to:

RewriteRule ^(wp-(content|admin|includes).*) - [L]

The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.

It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.

Javascript close alert box

I guess you could open a popup window and call that a dialog box. I'm unsure of the details, but I'm pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?

How to capture a JFrame's close button click event?

This is what I put as a menu option where I made a button on a JFrame to display another JFrame. I wanted only the new frame to be visible, and not to destroy the one behind it. I initially hid the first JFrame, while the new one became visible. Upon closing of the new JFrame, I disposed of it followed by an action of making the old one visible again.

Note: The following code expands off of Ravinda's answer and ng is a JButton:

ng.addActionListener((ActionEvent e) -> {
    setVisible(false);
    JFrame j = new JFrame("NAME");
    j.setVisible(true);
    j.addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            setVisible(true);
        }
    });
});

How do I alter the position of a column in a PostgreSQL database table?

There are some workarounds to make it possible:

  1. Recreating the whole table

  2. Create new columns within the current table

  3. Create a view

https://tableplus.com/blog/2018/09/postgresql-is-it-possible-to-alter-column-order-position-in-a-table.html

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

Why am I getting a NoClassDefFoundError in Java?

NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

try {
    // Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
    Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}

Getting input values from text box

This is the sample code for the email and javascript.

params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += "      Query:    ";
content += unescape(params["FormsMultiLine4"]);
var email = "[email protected]";
document.write('<a href="mailto:'+email+'?subject='+subject+'&body='+content+'">SUBMIT QUERY</a>');

How to calculate the sum of the datatable column in asp.net?

Compute Sum of Column in Datatable , Works 100%

lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();

if you want to have any conditions, use it like this

   lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();

Select random lines from a file

seq 1 100 | python3 -c 'print(__import__("random").choice(__import__("sys").stdin.readlines()))'

Is it possible to reference one CSS rule within another?

You can use var() function.

The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property.

Example:

:root {
  --main-bg-color: yellow;
}

@media (prefers-color-scheme: dark) {
  :root {
    --main-bg-color: black;
  }
}

body {
  background-color: var(--main-bg-color);
}

How is Docker different from a virtual machine?

Docker encapsulates an application with all its dependencies.

A virtualizer encapsulates an OS that can run any applications it can normally run on a bare metal machine.

What is the best way to find the users home directory in Java?

As I was searching for Scala version, all I could find was McDowell's JNA code above. I include my Scala port here, as there currently isn't anywhere more appropriate.

import com.sun.jna.platform.win32._
object jna {
    def getHome: java.io.File = {
        if (!com.sun.jna.Platform.isWindows()) {
            new java.io.File(System.getProperty("user.home"))
        }
        else {
            val pszPath: Array[Char] = new Array[Char](WinDef.MAX_PATH)
            new java.io.File(Shell32.INSTANCE.SHGetSpecialFolderPath(null, pszPath, ShlObj.CSIDL_MYDOCUMENTS, false) match {
                case true => new String(pszPath.takeWhile(c => c != '\0'))
                case _    => System.getProperty("user.home")
            })
        }
    }
}

As with the Java version, you will need to add Java Native Access, including both jar files, to your referenced libraries.

It's nice to see that JNA now makes this much easier than when the original code was posted.

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

bash: pip: command not found

I have to admit to being absolutely new to python, which I only need for one thing: awscli. I encountered this problem having downloaded python 3.x.x - pip: command not found

Whilst following the instructions for downloading the AWS cli I changed

pip install awscli

to

pip3 install awscli

which ran the correct version.

I've made an alias on my machine to run python3 whilst typing python, which would normally run the system version 2.7. I'm not sure this is a good idea now. I think I'll just type in the commands as they intended them to be

Truncate (not round) decimal places in SQL Server

Try like this:

SELECT cast(round(123.456,2,1) as decimal(18,2)) 

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I tested all the answers about this topic. And nothing worked here… but I found another solution.

Go to pom -> overview and add these to your properties:

Name: “maven.compiler.target” Value: “1.8”

and

Name: “maven.compiler.source” Value: “1.8”

Now do a maven update.

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

FFmpeg does not write to a specific log file, but rather sends its output to standard error. To capture that, you need to either

  • capture and parse it as it is generated
  • redirect standard error to a file and read that afterward the process is finished

Example for std error redirection:

ffmpeg -i myinput.avi {a-bunch-of-important-params} out.flv 2> /path/to/out.txt

Once the process is done, you can inspect out.txt.

It's a bit trickier to do the first option, but it is possible. (I've done it myself. So have others. Have a look around SO and the net for details.)

How to cast an Object to an int

so divide1=me.getValue()/2;

int divide1 = (Integer) me.getValue()/2;

jwt check if token expired

This is for react-native, but login will work for all types.

isTokenExpired = async () => {
    try {
        const LoginTokenValue = await AsyncStorage.getItem('LoginTokenValue');
        if (JSON.parse(LoginTokenValue).RememberMe) {
            const { exp } = JwtDecode(LoginTokenValue);
            if (exp < (new Date().getTime() + 1) / 1000) {
                this.handleSetTimeout();
                return false;
            } else {
                //Navigate inside the application
                return true;
            }
        } else {
            //Navigate to the login page
        }
    } catch (err) {
        console.log('Spalsh -> isTokenExpired -> err', err);
        //Navigate to the login page
        return false;
    }
}

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

javascript filter array of objects

_x000D_
_x000D_
var names = [{_x000D_
        name: "Joe",_x000D_
        age: 20,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Mike",_x000D_
        age: 50,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Joe",_x000D_
        age: 45,_x000D_
        email: "[email protected]"_x000D_
    }_x000D_
];_x000D_
const res = _.filter(names, (name) => {_x000D_
    return name.name == "Joe" && name.age < 30;_x000D_
_x000D_
});_x000D_
console.log(res);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Waiting for Target Device to Come Online

Go to the Sdk manager--> SDKtools --> instal the emulator 25.3.1

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

Can I convert long to int?

A possible way is to use the modulo operator to only let the values stay in the int32 range, and then cast it to int.

var intValue= (int)(longValue % Int32.MaxValue);

Alternate output format for psql

pspg is a simple tool that offers advanced table formatting, horizontal scrolling, search and many more features.

git clone https://github.com/okbob/pspg.git
cd pspg
./configure
make
make install

then make sure to update PAGER variable e.g. in your ~/.bashrc

export PAGER="pspg -s 6" 

where -s stands for color scheme (1-14). If you're using pgdg repositories simply install a package (on Debian-like distribution):

sudo apt install pspg

pspg example

Declaring an enum within a class

I prefer following approach (code below). It solves the "namespace pollution" problem, but also it is much more typesafe (you can't assign and even compare two different enumerations, or your enumeration with any other built-in types etc).

struct Color
{
    enum Type
    {
        Red, Green, Black
    };
    Type t_;
    Color(Type t) : t_(t) {}
    operator Type () const {return t_;}
private:
   //prevent automatic conversion for any other built-in types such as bool, int, etc
   template<typename T>
    operator T () const;
};

Usage:

Color c = Color::Red;
switch(c)
{
   case Color::Red:
     //????????? ???
   break;
}
Color2 c2 = Color2::Green;
c2 = c; //error
c2 = 3; //error
if (c2 == Color::Red ) {} //error
If (c2) {} error

I create macro to facilitate usage:

#define DEFINE_SIMPLE_ENUM(EnumName, seq) \
struct EnumName {\
   enum type \
   { \
      BOOST_PP_SEQ_FOR_EACH_I(DEFINE_SIMPLE_ENUM_VAL, EnumName, seq)\
   }; \
   type v; \
   EnumName(type v) : v(v) {} \
   operator type() const {return v;} \
private: \
    template<typename T> \
    operator T () const;};\

#define DEFINE_SIMPLE_ENUM_VAL(r, data, i, record) \
    BOOST_PP_TUPLE_ELEM(2, 0, record) = BOOST_PP_TUPLE_ELEM(2, 1, record),

Usage:

DEFINE_SIMPLE_ENUM(Color,
             ((Red, 1))
             ((Green, 3))
             )

Some references:

  1. Herb Sutter, Jum Hyslop, C/C++ Users Journal, 22(5), May 2004
  2. Herb Sutter, David E. Miller, Bjarne Stroustrup Strongly Typed Enums (revision 3), July 2007

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

jquery Ajax call - data parameters are not being passed to MVC Controller action

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

How to change fonts in matplotlib (python)?

import pylab as plb
plb.rcParams['font.size'] = 12

or

import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12

WPF Label Foreground Color

The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:

<StackPanel>
    <Label Foreground="Red">Red text</Label>
    <Label Foreground="Blue">Blue text</Label>
</StackPanel>

In summary, No, there was nothing wrong with your snippet.

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

Error inflating when extending a class

in my case I added such cyclic resource:

<drawable name="above_shadow">@drawable/above_shadow</drawable>

then changed to

<drawable name="some_name">@drawable/other_name</drawable>

and it worked