Programs & Examples On #Stack memory

Matplotlib (pyplot) savefig outputs blank image

change the order of the functions fixed the problem for me:

  • first Save the plot
  • then Show the plot

as following:

plt.savefig('heatmap.png')

plt.show()

MySQL error 2006: mysql server has gone away

For users using XAMPP, there are 2 max_allowed_packet parameters in C:\xampp\mysql\bin\my.ini.

What are the differences between Visual Studio Code and Visual Studio?

Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.

Powershell script does not run via Scheduled Tasks

If you don't have any error messages and don't know what the problem is - why PowerShell scripts don't want to start from a Scheduled Task do the following steps to get the answer:

  1. Run CMD as a user who has been set for Scheduled Task to execute the PowerShell script
  2. Browse to the folder where the PowerShell script is located
  3. Execute the PowerShell script (remove all statements that block the error notifications if any exists inside of the script like $ErrorActionPreference= 'silentlycontinue')

You should be able to see all error notifications.

In case of one of my script it was:

"Unable to find type [System.ServiceProcess.ServiceController]. Make sure that the assembly that contains this type is loaded."

And in this case I have to add additional line at the begining of the script to load the missing assembly:

Add-Type -AssemblyName "System.ServiceProcess"

And next errors:

Exception calling "GetServices" with "1" argument(s): "Cannot open Service Control Manager on computer ''. This operation might require other privileges."

select : The property cannot be processed because the property "Database Name" already exists

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Is there a cross-browser onload event when clicking the back button?

Bill, I dare answer your question, however I am not 100% sure with my guesses. I think other then IE browsers when taking user to a page in history will not only load the page and its resources from cache but they will also restore the entire DOM (read session) state for it. IE doesn't do DOM restoration (or at lease did not do) and thus the onload event looks to be necessary for proper page re-initialization there.

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

How to run batch file from network share without "UNC path are not supported" message?

Editing Windows registries is not worth it and not safe, use Map network drive and load the network share as if it's loaded from one of your local drives.

enter image description here

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

How to delete rows from a pandas DataFrame based on a conditional expression

When you do len(df['column name']) you are just getting one number, namely the number of rows in the DataFrame (i.e., the length of the column itself). If you want to apply len to each element in the column, use df['column name'].map(len). So try

df[df['column name'].map(len) < 2]

How to draw a graph in PHP?

Have no idea about gd2, but I have done a similar thing with gd and it was not that hard.

Go to http://www.php.net/ and search for things like

  • ImageCreate
  • imageline
  • imagestring

It's not as flashy as some of those other solution out there, but since you generate a picture it will work in all browsers. (except lynx... :-) )

/Johan


Update: I nearly forgot, don't use jpeg for this type of pictures. The jpeg artefacts will be really annoying, png is a better solution.

alternative to "!is.null()" in R

Ian put this in the comment, but I think it's a good answer:

if (exists("aVariable"))
{
  do whatever
}

note that the variable name is quoted.

How to filter JSON Data in JavaScript or jQuery?

Try this way, allow you even filter by other key

data:

var my_data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}];

usage:

//We do that to ensure to get a correct JSON
var my_json = JSON.stringify(my_data)
//We can use {'name': 'Lenovo Thinkpad 41A429ff8'} as criteria too
var filtered_json = find_in_object(JSON.parse(my_json), {website: 'yahoo'});

filter function

function find_in_object(my_object, my_criteria){

  return my_object.filter(function(obj) {
    return Object.keys(my_criteria).every(function(c) {
      return obj[c] == my_criteria[c];
    });
  });

}

Set background colour of cell to RGB value of data in cell

Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...

Put this function into a new module:

Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
  On Error Resume Next
  x.Interior.Color = RGB(R, G, B)
  x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function

Then use this formula in your sheet, for example in cell D2:

=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")

Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2 to C2. The font color is a contrasting white or black.

! [rejected] master -> master (fetch first)

Sometimes it happens when you duplicate files typically README sort of.

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

Google.com and clients1.google.com/generate_204

In the event that Chrome detects SSL connection timeouts, certificate errors, or other network issues that might be caused by a captive portal (a hotel's WiFi network, for instance), Chrome will make a cookieless request to http://www.gstatic.com/generate_204 and check the response code. If that request is redirected, Chrome will open the redirect target in a new tab on the assumption that it's a login page. Requests to the captive portal detection page are not logged.

Source: Google Chrome Privacy Whitepaper

What is the iOS 5.0 user agent string?

I use the following to detect different mobile devices, viewport and screen. Works quite well for me, might be helpful to others:

var pixelRatio = window.devicePixelRatio || 1;

var viewport = {
    width: window.innerWidth,
    height: window.innerHeight
};

var screen = {
    width: window.screen.availWidth * pixelRatio,
    height: window.screen.availHeight * pixelRatio
};

var iPhone = /iPhone/i.test(navigator.userAgent);
var iPhone4 = (iPhone && pixelRatio == 2);
var iPhone5 = /iPhone OS 5_0/i.test(navigator.userAgent);
var iPad = /iPad/i.test(navigator.userAgent);
var android = /android/i.test(navigator.userAgent);
var webos = /hpwos/i.test(navigator.userAgent);
var iOS = iPhone || iPad;
var mobile = iOS || android || webos;

window.devicePixelRatio is the ratio between physical pixels and device-independent pixels (dips) on the device. window.devicePixelRatio = physical pixels / dips.

More info here.

MongoDB via Mongoose JS - What is findByID?

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

How to use support FileProvider for sharing content to other apps?

If you get an image from camera none of these solutions work for Android 4.4. In this case it's better to check versions.

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getContext().getPackageManager()) != null) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        uri = Uri.fromFile(file);
    } else {
        uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file);
    }
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, CAMERA_REQUEST);
}

Byte Array and Int conversion in Java

Your methods should be (something like)

public static int byteArrayToInt(byte[] b) 
{
    return   b[3] & 0xFF |
            (b[2] & 0xFF) << 8 |
            (b[1] & 0xFF) << 16 |
            (b[0] & 0xFF) << 24;
}

public static byte[] intToByteArray(int a)
{
    return new byte[] {
        (byte) ((a >> 24) & 0xFF),
        (byte) ((a >> 16) & 0xFF),   
        (byte) ((a >> 8) & 0xFF),   
        (byte) (a & 0xFF)
    };
}

These methods were tested with the following code :

Random rand = new Random(System.currentTimeMillis());
byte[] b;
int a, v;
for (int i=0; i<10000000; i++) {
    a = rand.nextInt();
    b = intToByteArray(a);
    v = byteArrayToInt(b);
    if (a != v) {
        System.out.println("ERR! " + a + " != " + Arrays.toString(b) + " != " + v);
    }
}
System.out.println("Done!");

MySQL - SELECT all columns WHERE one column is DISTINCT

SELECT a.* FROM orders a INNER JOIN (SELECT course,MAX(id) as id FROM orders WHERE admission_id=".$id." GROUP BY course ) AS b ON a.course = b.course AND a.id = b.id

With the Above Query you will get unique records with where condition

python ignore certificate validation urllib2

In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).

My evil workaround (don't do this in production!):

import urllib2
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

urllib2.urlopen("https://your-test-server.local", context=ctx)

According to docs calling SSLContext constructor directly should work, too. I haven't tried that.

What is Python buffer type for?

I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer in this mailinglist post).

For example, numpy seems to use buffer for efficient data storage:

import numpy
a = numpy.ndarray(1000000)

the a.data is a:

<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

Here is an applescript that will launch Chrome with the --allow-file-access-from-files switch turned on, for OSX/Chrome devs out there:

set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"    
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"

Overlay with spinner

Here is simple overlay div without using any gif, This can be applied over another div.

<style>
.loader {
  position: relative;
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 70px;
  height: 70px;
  left:50%;
  top:50%;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
}
#overlay{
    position: absolute;
    top:0px;
    left:0px;
    width: 100%;
    height: 100%;
    background: black;
    opacity: .5;
}
.container{
    position:relative;
    height: 300px;
    width: 200px;
    border:1px solid
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

<h2>How To Create A Loader</h2>

<div class="container">
  <h3>Overlay over this div</h3>
  <div id="overlay">
      <div class="loader"></div>
  </div>
<div>

Use Expect in a Bash script to provide a password to an SSH command

A simple Expect script:

File Remotelogin.exp

    #!/usr/bin/expect
    set user [lindex $argv 1]
    set ip [lindex $argv 0]
    set password [lindex $argv 2]
    spawn ssh $user@$ip
    expect "password"
    send "$password\r"
    interact

Example:

./Remotelogin.exp <ip> <user name> <password>

Client on Node.js: Uncaught ReferenceError: require is not defined

I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.

The line

const {ipcRenderer} = require('electron')

throws the Uncaught ReferenceError: require is not defined

I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.

function createAddItemWindow() {

    // Create a new window
    addItemWindown = new BrowserWindow({
        width: 300,
        height: 200,
        title: 'Add Item',

        // The lines below solved the issue
        webPreferences: {
            nodeIntegration: true
        }
})}

That solved the issue for me. The solution was proposed here.

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

Is your application running as a 64 or 32bit process? You can check this in the task manager.

It could be, it is running as 32bit, even though the entire system is running on 64bit.

If 32bit, a third party library could be causing this. But first make sure your application is compiling for "Any CPU", as stated in the comments.

How do I use WebRequest to access an SSL encrypted site using https?

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

Laravel 5.4 redirection to custom url after login

in accord with Laravel documentation, I create in app/Http/Controllers/Auth/LoginController.php the following method :

protected function redirectTo()
{
    $user=Auth::user();

    if($user->account_type == 1){
        return '/admin';
    }else{
        return '/home';
    }

}

to get the user information from my db I used "Illuminate\Support\Facades\Auth;".

SQL recursive query on self referencing table (Oracle)

What about using PRIOR,

so

SELECT id, parent_id, PRIOR name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id`

or if you want to get the root name

SELECT id, parent_id, CONNECT_BY_ROOT name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id

How to convert XML to JSON in Python?

xmltodict (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory.

Once you have that data structure, you can serialize it to JSON:

import xmltodict, json

o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'

Unable to set variables in bash script

here's your amended script

#!/bin/bash    
folder="ABC" #no spaces between assignment    
useracct='test'    
day=$(date "+%d") # use $() to assign return value of date command to variable    
month=$(date "+%B")     
year=$(date "+%Y")    
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"    
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"    
ECHO "Network is $network" $network    
ECHO "day is $day"    
ECHO "Month is $month"    
ECHO "YEAR is $year"    
ECHO "source is $folderToBeMoved"    
ECHO "dest is $newfoldername"    

mkdir "$newfoldername"    
cp -R "$folderToBeMoved" "$newfoldername"
if [ -f "$newfoldername/Primetime.eyetv" ]; then # <-- put a space at square brackets and quote your variables.
 rm "$folderToBeMoved";
fi

Create a sample login page using servlet and JSP?

You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.

Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.

...

Using .text() to retrieve only text not nested in child tags

Similar to the accepted answer, but without cloning:

$("#foo").contents().not($("#foo").children()).text();

And here is a jQuery plugin for this purpose:

$.fn.immediateText = function() {
    return this.contents().not(this.children()).text();
};

Here is how to use this plugin:

$("#foo").immediateText(); // get the text without children

How to iterate through table in Lua?

All the answers here suggest to use ipairs but beware, it does not work all the time.

t = {[2] = 44, [4]=77, [6]=88}

--This for loop prints the table
for key,value in next,t,nil do 
  print(key,value) 
end

--This one does not print the table
for key,value in ipairs(t) do 
  print(key,value) 
end

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

Mercurial undo last commit

hg strip will completely remove a revision (and any descendants) from the repository.

To use strip you'll need to install MqExtension by adding the following lines to your .hgrc (or mercurial.ini):

[extensions]
mq =

In TortoiseHg the strip command is available in the workbench. Right click on a revision and choose 'Modify history' -> 'Strip'.

Since strip changes the the repository's history you should only use it on revisions which haven't been shared with anyone yet. If you are using mercurial 2.1+ you can uses phases to track this information. If a commit is still in the draft phase it hasn't been shared with other repositories so you can safely strip it. (Thanks to Zasurus for pointing this out).

Why are unnamed namespaces used and what are their benefits?

Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:

namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }

The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.

This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.

namespace { int a1; }
static int a2;

Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.

Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).

How do I import an SQL file using the command line in MySQL?

Using MySQL Secure Shell:

mysqlsh -u <username> -p -h <host> -D <database name> -f dump.sql

In Java, can you modify a List while iterating through it?

Use CopyOnWriteArrayList
and if you want to remove it, do the following:

for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
    if (wordsToRemove.contains(word))
    {
        it.remove();
    }
}

Best way to "push" into C# array

The is no array.push(newValue) in C#. You don't push to an Array in C#. What we use for this is a List<T>. What you may want to consider (for teaching purpose only) is the ArrayList (no generic and it is a IList, so ...).

static void Main()
{
    // Create an ArrayList and add 3 elements.
    ArrayList list = new ArrayList();
    list.Add("One"); // Add is your push
    list.Add("Two");
    list.Add("Three");
}

Git submodule update

To address the --rebase vs. --merge option:

Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling

git submodule update

you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B

cd B
git checkout -b bestIdeaForBEver
<do work>

Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.

<in A>
git merge develop
git submodule update

Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:

git merge develop
git submodule update --rebase

Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'

Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!

(The --merge will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)

When should I create a destructor?

UPDATE: This question was the subject of my blog in May of 2015. Thanks for the great question! See the blog for a long list of falsehoods that people commonly believe about finalization.

When should I manually create a destructor?

Almost never.

Typically one only creates a destructor when your class is holding on to some expensive unmanaged resource that must be cleaned up when the object goes away. It is better to use the disposable pattern to ensure that the resource is cleaned up. A destructor is then essentially an assurance that if the consumer of your object forgets to dispose it, the resource still gets cleaned up eventually. (Maybe.)

If you make a destructor be extremely careful and understand how the garbage collector works. Destructors are really weird:

  • They don't run on your thread; they run on their own thread. Don't cause deadlocks!
  • An unhandled exception thrown from a destructor is bad news. It's on its own thread; who is going to catch it?
  • A destructor may be called on an object after the constructor starts but before the constructor finishes. A properly written destructor will not rely on invariants established in the constructor.
  • A destructor can "resurrect" an object, making a dead object alive again. That's really weird. Don't do it.
  • A destructor might never run; you can't rely on the object ever being scheduled for finalization. It probably will be, but that's not a guarantee.

Almost nothing that is normally true is true in a destructor. Be really, really careful. Writing a correct destructor is very difficult.

When have you needed to create a destructor?

When testing the part of the compiler that handles destructors. I've never needed to do so in production code. I seldom write objects that manipulate unmanaged resources.

How to get names of enum entries?

Assuming you stick to the rules and only produce enums with numeric values, you can use this code. This correctly handles the case where you have a name that is coincidentally a valid number

enum Color {
    Red,
    Green,
    Blue,
    "10" // wat
}

var names: string[] = [];
for(var n in Color) {
    if(typeof Color[n] === 'number') names.push(n);
}
console.log(names); // ['Red', 'Green', 'Blue', '10']

Understanding checked vs unchecked exceptions in Java

Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of RuntimeException (unchecked exception)

However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.

Here's my extended view on the topic.

As for the particular questions:

  1. Is the NumberFormatException consider a checked exception?
    No. NumberFormatException is unchecked (= is subclass of RuntimeException). Why? I don't know. (but there should have been a method isValidInteger(..))

  2. Is RuntimeException an unchecked exception?
    Yes, exactly.

  3. What should I do here?
    It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:

    • log it and return
    • rethrow it (declare it to be thrown by the method)
    • construct a new exception by passing the current one in constructor
  4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?
    It could've been. But nothing stops you from catching the unchecked exception as well

  5. Why do people add class Exception in the throws clause?
    Most often because people are lazy to consider what to catch and what to rethrow. Throwing Exception is a bad practice and should be avoided.

Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

From in Sql Server Management Studio: Tools -> Sql Server profiler. Although as @bobs said, you may need to install additional components first.

Datepicker: How to popup datepicker when click on edittext

import android.app.DatePickerDialog;
import android.content.Context;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class DatePickerHelper {

private final Calendar calendar = Calendar.getInstance();
private final String dateFormat = "MM/dd/yy";
private TextView textView = null;

public DatePickerHelper(final Context context, TextView textView) {
    this.textView = textView;

    // Setup on click listener if the TextView is not null
    if (textView != null) {
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDatePickerDialog(context).show();
            }
        });
    }
}

/**
 * Return a new date picker listener tied to the specified TextView field
 * @return
 */
private DatePickerDialog.OnDateSetListener getOnDateSetListener() {
    return new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
            textView.setText(sdf.format(calendar.getTime()));
        }
    };
}

/**
 * Return new DatePickerDialog for field
 * @param context
 * @return
 */
private DatePickerDialog getDatePickerDialog(Context context) {
    return new DatePickerDialog(context, getOnDateSetListener(), calendar
            .get(Calendar.YEAR), calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH));
}

}

Usage:

  DatePickerHelper assessmentDueDateHelper = new DatePickerHelper(AssessmentsDetailActivity.this,
            (TextView) findViewById(R.id.assessmentDueDateEditText));

How to insert element as a first child?

$('.parent-div').children(':first').before("<div class='child-div'>some text</div>");

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

Multipart File upload Spring Boot

You can simply use a controller method like this:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
    @RequestParam("file") MultipartFile file) {

  try {
    // Handle the received file here
    // ...
  }
  catch (Exception e) {
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }

  return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

Without any additional configurations for Spring Boot.

Using the following html form client side:

<html>
<body>
  <form action="/uploadFile" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload"> 
  </form>
</body>
</html>

If you want to set limits on files size you can do it in the application.properties:

# File size limit
multipart.maxFileSize = 3Mb

# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb

Moreover to send the file with Ajax take a look here: http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/

Can I automatically increment the file build version when using Visual Studio?

Setting a * in the version number in AssemblyInfo or under project properties as described in the other posts does not work with all versions of Visual Studio / .NET.

Afaik it did not work in VS 2005 (but in VS 2003 and VS 2008). For VS 2005 you could use the following: Auto Increment Visual Studio 2005 version build and revision number on compile time.

But be aware that changing the version number automatically is not recommended for strong-named assemblies. The reason is that all references to such an assembly must be updated each time the referenced assembly is rebuilt due to the fact that strong-named assembly references are always a reference to a specific assembly version. Microsoft themselves change the version number of the .NET Framework assemblies only if there are changes in interfaces. (NB: I'm still searching for the link in MSDN where I read that.)

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

Why should you use strncpy instead of strcpy?

The strncpy() function was designed with a very particular problem in mind: manipulating strings stored in the manner of original UNIX directory entries. These used a fixed sized array, and a nul-terminator was only used if the filename was shorter than the array.

That's what's behind the two oddities of strncpy():

  • It doesn't put a nul-terminator on the destination if it is completely filled; and
  • It always completely fills the destination, with nuls if necessary.

For a "safer strcpy()", you are better off using strncat() like so:

if (dest_size > 0)
{
    dest[0] = '\0';
    strncat(dest, source, dest_size - 1);
}

That will always nul-terminate the result, and won't copy more than necessary.

What does SQL clause "GROUP BY 1" mean?

It will group by first field in the select clause

Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

Is it possible to preview stash contents in git?

To view a current list of stash:

git stash list

You'll see a list like this:

stash@{0}: WIP on ...
stash@{1}: ...
stash@{2}: ...
...

To view diff on any of those stashes:

git stash show -p stash@{n}

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Fit Image in ImageButton in Android

I want them to cover 75% of the button area.

Use android:padding="20dp" (adjust the padding as needed) to control how much the image takes up on the button.

but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?

Use a android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling.

All of these attributes can be set in code on each ImageButton at runtime. However, it is much easier to set and preview in xml in my opinion.

Also, do not use sp for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp dimensions will be larger than your intended if the user has a "large" text setting. Use dp instead, as it is not scaled by the user's text size preference.

Here's a snippet of what each button should look like:

    <ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:scaleType="fitCenter" />

Sample Button

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

Alternatively to injection and even worse Singleton, you can call Detach method before Add.

EntityFramework 6: ((IObjectContextAdapter)cs).ObjectContext.Detach(city1);

EntityFramework 4: cs.Detach(city1);

There is yet another way, in case you don't need first DBContext object. Just wrap it with using keyword:

Payroll.Entities.City city1;
using (CityService cs = new CityService())
{
  city1 = cs.SelectCity(Convert.ToInt64(cmbCity.SelectedItem.Value));
}

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

How to get progress from XMLHttpRequest

For the bytes uploaded it is quite easy. Just monitor the xhr.upload.onprogress event. The browser knows the size of the files it has to upload and the size of the uploaded data, so it can provide the progress info.

For the bytes downloaded (when getting the info with xhr.responseText), it is a little bit more difficult, because the browser doesn't know how many bytes will be sent in the server request. The only thing that the browser knows in this case is the size of the bytes it is receiving.

There is a solution for this, it's sufficient to set a Content-Length header on the server script, in order to get the total size of the bytes the browser is going to receive.

For more go to https://developer.mozilla.org/en/Using_XMLHttpRequest .

Example: My server script reads a zip file (it takes 5 seconds):

$filesize=filesize('test.zip');

header("Content-Length: " . $filesize); // set header length
// if the headers is not set then the evt.loaded will be 0
readfile('test.zip');
exit 0;

Now I can monitor the download process of the server script, because I know it's total length:

function updateProgress(evt) 
{
   if (evt.lengthComputable) 
   {  // evt.loaded the bytes the browser received
      // evt.total the total bytes set by the header
      // jQuery UI progress bar to show the progress on screen
     var percentComplete = (evt.loaded / evt.total) * 100;  
     $('#progressbar').progressbar( "option", "value", percentComplete );
   } 
}   
function sendreq(evt) 
{  
    var req = new XMLHttpRequest(); 
    $('#progressbar').progressbar();    
    req.onprogress = updateProgress;
    req.open('GET', 'test.php', true);  
    req.onreadystatechange = function (aEvt) {  
        if (req.readyState == 4) 
        {  
             //run any callback here
        }  
    };  
    req.send(); 
}

Convert array values from string to int?

Keep it simple...

$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);

Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode (). People have posted how to use that, so I am not including it here.

Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:

$str = '1';
($str == 1) // true but
($str === 1) //false

Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.

javascript node.js next()

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

See, for example, the code samples here:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
        res.redirect('/sessions/new');
      }
    });
  } else {
    res.redirect('/sessions/new');
  }
}

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...
});

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

There's nothing special about the name next in this example; we could have named it anything.

Search in lists of lists by given index

You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to map() or similar, but it's always going to be there.

My preference would always be to have clean and simple code, unless performance is a major factor.

Here's perhaps a more Pythonic version of your code:

data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for sublist in data:
    if sublist[1] == search:
        print "Found it!", sublist
        break
# Prints: Found it! ['a', 'c']

It breaks out of the loop as soon as it finds a match.

(You have a typo, by the way, in ['b''d'].)

Remove x-axis label/text in chart.js

If you want the labels to be retained for the tooltip, but not displayed below the bars the following hack might be useful. I made this change for use on an private intranet application and have not tested it for efficiency or side-effects, but it did what I needed.

At about line 71 in chart.js add a property to hide the bar labels:

// Boolean - Whether to show x-axis labels
barShowLabels: true,

At about line 1500 use that property to suppress changing this.endPoint (it seems that other portions of the calculation code are needed as chunks of the chart disappeared or were rendered incorrectly if I disabled anything more than this line).

if (this.xLabelRotation > 0) {
    if (this.ctx.barShowLabels) {
        this.endPoint -= Math.sin(toRadians(this.xLabelRotation)) * originalLabelWidth + 3;
    } else {
        // don't change this.endPoint
    }
}

At about line 1644 use the property to suppress the label rendering:

if (ctx.barShowLabels) {    
    ctx.fillText(label, 0, 0);
}

I'd like to make this change to the Chart.js source but aren't that familiar with git and don't have the time to test rigorously so would rather avoid breaking anything.

Laravel 5 call a model function in a blade view

I ran into a similar issue where I wanted to call a function defined in my controller from my view. Although it perplexed me for a while trying to figure out how to get to the controller from the view it turned out to be fairly straightforward.

I hand off an array to my views with data records that the view formats and presents to the user with jQuery DataTables (big duh). One column in the presented UI table is a set of action buttons that need to be created per row based on the content of the data in each of the rows. I guess I could have added the button definitions to the data rows as a column sent to the views but not all views needed the buttons so why? Instead, I wanted the view that needed them add them.

In the controller I pass a reference to the controller itself to the view as in

->with('callbackController', $this)

I called it callbackController as that is what I was doing. Now, inside my view I can either escape to PHP to use $callbackController to access the parent controller as in

<?php echo $callbackController->makeButtons($parameters); ?>

or just use the Blade mechanism

{!! $callbackController->makeButtons($parameters); ?>

It seems to be working fine across multiple controllers and views. I have not noticed a performance penalty using this mechanism and I have one huge table with over 50K rows.

I have not tried to pass on references to other objects (e.g., models, etc) yet but I do not see what that would not work as well

Might not be elegant but it seems to get the job done.

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

How to change time in DateTime?

here is a ghetto way, but it works :)

DateTime dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));

Check if string matches pattern

One-liner: re.match(r"pattern", string) # No need to compile

import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
...     print('Yes')
... 
Yes

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True

Hibernate Criteria Query to get specific columns

You can map another entity based on this class (you should use entity-name in order to distinct the two) and the second one will be kind of dto (dont forget that dto has design issues ). you should define the second one as readonly and give it a good name in order to be clear that this is not a regular entity. by the way select only few columns is called projection , so google with it will be easier.

alternative - you can create named query with the list of fields that you need (you put them in the select ) or use criteria with projection

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

Python method for reading keypress?

I really did not want to post this as a comment because I would need to comment all answers and the original question.

All of the answers seem to rely on MSVCRT Microsoft Visual C Runtime. If you would like to avoid that dependency :

In case you want cross platform support, using the library here:

https://pypi.org/project/getkey/#files

https://github.com/kcsaff/getkey

Can allow for a more elegant solution.

Code example:

from getkey import getkey, keys
key = getkey()
if key == keys.UP:
  ...  # Handle the UP key
elif key == keys.DOWN:
  ...  # Handle the DOWN key
elif key == 'a':
  ...  # Handle the `a` key
elif key == 'Y':
  ...  # Handle `shift-y`
else:
  # Handle other text characters
  buffer += key
  print(buffer)

Global variables in c#.net

Just declare the variable at the starting of a class.

e.g. for string variable:

public partial class Login : System.Web.UI.Page
{
    public string sError;

    protected void Page_Load(object sender, EventArgs e)
    {
         //Page Load Code
    }

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

Credit card payment gateway in PHP?

Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php

Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.

Deserialize JSON into C# dynamic object?

It's pretty simple using Json.NET:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Also using Newtonsoft.Json.Linq:

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Documentation: Querying JSON with dynamic

How to avoid pressing Enter with getchar() for reading a single character only?

Can create a new function that checks for Enter:

#include <stdio.h>

char getChar()
{
    printf("Please enter a char:\n");

    char c = getchar();
    if (c == '\n')
    {
        c = getchar();
    }

    return c;
}

int main(int argc, char *argv[])
{
    char ch;
    while ((ch = getChar()) != '.')
    {
        printf("Your char: %c\n", ch);
    }

    return 0;
}

Node.js + Nginx - What now?

You can run nodejs using pm2 if you want to manage each microservice means and run it. Node will be running in a port right just configure that port in nginx(/etc/nginx/sites-enabled/domain.com)

server{
    listen 80;
    server_name domain.com www.domain.com;

  location / {
     return 403;
  }
    location /url {
        proxy_pass http://localhost:51967/info;
    }
}

Check whether localhost is running or not by using ping.

And

Create one single Node.js server which handles all Node.js requests. This reads the requested files and evals their contents. So the files are interpreted on each request, but the server logic is much simpler.

This is best and as you said easier too

How to check if a Constraint exists in Sql server?

SELECT tabla.name as Tabla,

        restriccion.name as Restriccion, 
        restriccion.type as Tipo, 
        restriccion.type_desc as Tipo_Desc
FROM {DATABASE_NAME}.sys.objects tabla 

INNER JOIN {DATABASE_NAME}.sys.objects restriccion

ON tabla.object_id = restriccion.parent_object_id

WHERE tabla.type = 'U' - Solo tablas creadas por el usuario.

AND restriccion.type = 'UQ' --Tipo de Restriccion UNIQUE

ORDER BY tabla.name, restriccion.type_desc                

JQUERY ajax passing value from MVC View to Controller

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Form Submit jQuery does not work

Don't forget to close your form with a </form>. That stopped submit() working for me.

What's the right way to decode a string that has special HTML entities in it?

Don’t use the DOM to do this. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results.

For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.

Here’s how you’d use it:

he.decode("We&#39;re unable to complete your request at this time.");
? "We're unable to complete your request at this time."

Disclaimer: I'm the author of the he library.

See this Stack Overflow answer for some more info.

Angular 2 - innerHTML styling

If you are using sass as style preprocessor, you can switch back to native Sass compiler for dev dependency by:

npm install node-sass --save-dev

So that you can keep using /deep/ for development.

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

postgres default timezone

What if you set the timezone of the role you are using?

ALTER ROLE my_db_user IN DATABASE my_database
    SET "TimeZone" TO 'UTC';

Will this be of any use?

Right way to split an std::string into a vector<string>

A convenient way would be boost's string algorithms library.

#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
// ...

std::vector<std::string> words;
std::string s;
boost::split(words, s, boost::is_any_of(", "), boost::token_compress_on);

What is the size of a pointer?

Function Pointers can have very different sizes, from 4 to 20 Bytes on an X86 machine, depending on the compiler. So the answer is NO - sizes can vary.

Another example: take an 8051 program, it has three memory ranges and thus has three different pointer sizes, from 8 bit, 16bit, 24bit, depending on where the target is located, even though the target's size is always the same (e.g. char).

How to append binary data to a buffer in node.js

insert byte to specific place.

insertToArray(arr,index,item) {
   return Buffer.concat([arr.slice(0,index),Buffer.from(item,"utf-8"),arr.slice(index)]);
}

HTML5 Form Input Pattern Currency Format

Use this pattern "^\d*(\.\d{2}$)?"

What are native methods in Java and where should they be used?

What are native methods in Java and where should they be used?

Once you see a small example, it becomes clear:

Main.java:

public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:

#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:

javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.

So it is clear that it allows you to:

  • call a compiled dynamically loaded library (here written in C) with arbitrary assembly code from Java
  • and get results back into Java

This could be used to:

  • write faster code on a critical section with better CPU assembly instructions (not CPU portable)
  • make direct system calls (not OS portable)

with the tradeoff of lower portability.

It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?

Example on GitHub for you to play with.

Implement a loading indicator for a jQuery AJAX call

I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like

$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });

Making the iPhone vibrate

Important Note: Alert of Future Deprecation.

As of iOS 9.0, the API functions description for:

AudioServicesPlaySystemSound(inSystemSoundID: SystemSoundID)
AudioServicesPlayAlertSound(inSystemSoundID: SystemSoundID)

includes the following note:

This function will be deprecated in a future release.
Use AudioServicesPlayAlertSoundWithCompletion or  
AudioServicesPlaySystemSoundWithCompletion instead.

The right way to go will be using any of these two:

AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, nil)

or

AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate) {
 //your callback code when the vibration is done (it may not vibrate in iPod, but this callback will be always called)
}

remember to import AVFoundation

Download file and automatically save it to folder

My program does exactly what you are after, no prompts or anything, please see the following code.

This code will create all of the necessary directories if they don't already exist:

Directory.CreateDirectory(C:\dir\dira\dirb);  // This code will create all of these directories  

This code will download the given file to the given directory (after it has been created by the previous snippet:

private void install()
    {
        WebClient webClient = new WebClient();                                                          // Creates a webclient
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);                   // Uses the Event Handler to check whether the download is complete
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);  // Uses the Event Handler to check for progress made
        webClient.DownloadFileAsync(new Uri("http://www.com/newfile.zip"), @"C\newfile.zip");           // Defines the URL and destination directory for the downloaded file
    }

So using these two pieces of code you can create all of the directories and then tell the downloader (that doesn't prompt you to download the file to that location.

How to check whether a string is a valid HTTP URL?

Try that:

bool IsValidURL(string URL)
{
    string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}

It will accept URL like that:

  • http(s)://www.example.com
  • http(s)://stackoverflow.example.com
  • http(s)://www.example.com/page
  • http(s)://www.example.com/page?id=1&product=2
  • http(s)://www.example.com/page#start
  • http(s)://www.example.com:8080
  • http(s)://127.0.0.1
  • 127.0.0.1
  • www.example.com
  • example.com

How to print a query string with parameter values when using Hibernate

**If you want hibernate to print generated sql queries with real values instead of question marks.**
**add following entry in hibernate.cfg.xml/hibernate.properties:**
show_sql=true
format_sql=true
use_sql_comments=true

**And add following entry in log4j.properties :**
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout

HTML Text with tags to formatted text in an Excel cell

Nice! Very slick.

I was disappointed that Excel doesn't let us paste to a merged cell and also pastes results containing a break into successive rows below the "target" cell though, as that meant it simply doesn't work for me. I tried a few tweaks (unmerge/remerge, etc.) but then Excel dropped anything below a break, so that was a dead end.

Ultimately, I came up with a routine that'll handle simple tags and not use the "native" Unicode converter that is causing the issue with merged fields. Hope others find this useful:

Public Sub AddHTMLFormattedText(rngA As Range, strHTML As String, Optional blnShowBadHTMLWarning As Boolean = False)
    ' Adds converts text formatted with basic HTML tags to formatted text in an Excel cell
    ' NOTE: Font Sizes not handled perfectly per HTML standard, but I find this method more useful!

    Dim strActualText As String, intSrcPos As Integer, intDestPos As Integer, intDestSrcEquiv() As Integer
    Dim varyTags As Variant, varTag As Variant, varEndTag As Variant, blnTagMatch As Boolean
    Dim intCtr As Integer
    Dim intStartPos As Integer, intEndPos As Integer, intActualStartPos As Integer, intActualEndPos As Integer
    Dim intFontSizeStartPos As Integer, intFontSizeEndPos As Integer, intFontSize As Integer

    varyTags = Array("<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<sub>", "</sub>", "<sup>", "</sup>")

    ' Remove unhandled/unneeded tags, convert <br> and <p> tags to line feeds
    strHTML = Trim(strHTML)
    strHTML = Replace(strHTML, "<html>", "")
    strHTML = Replace(strHTML, "</html>", "")
    strHTML = Replace(strHTML, "<p>", "")
    While LCase(Right$(strHTML, 4)) = "</p>" Or LCase(Right$(strHTML, 4)) = "<br>"
        strHTML = Left$(strHTML, Len(strHTML) - 4)
        strHTML = Trim(strHTML)
    Wend
    strHTML = Replace(strHTML, "<br>", vbLf)
    strHTML = Replace(strHTML, "</p>", vbLf)

    strHTML = Trim(strHTML)

    ReDim intDestSrcEquiv(1 To Len(strHTML))
    strActualText = ""
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        blnTagMatch = False
        For Each varTag In varyTags
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intSrcPos = intSrcPos + Len(varTag)
                If intSrcPos > Len(strHTML) Then Exit Do
                Exit For
            End If
        Next
        If blnTagMatch = False Then
            varTag = "<font size"
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intEndPos = InStr(intSrcPos, strHTML, ">")
                intSrcPos = intEndPos + 1
                If intSrcPos > Len(strHTML) Then Exit Do
            Else
                varTag = "</font>"
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    blnTagMatch = True
                    intSrcPos = intSrcPos + Len(varTag)
                    If intSrcPos > Len(strHTML) Then Exit Do
                End If
            End If
        End If
        If blnTagMatch = False Then
            strActualText = strActualText & Mid$(strHTML, intSrcPos, 1)
            intDestSrcEquiv(intSrcPos) = intDestPos
            intDestPos = intDestPos + 1
            intSrcPos = intSrcPos + 1
        End If
    Loop

    ' Clear any bold/underline/italic/superscript/subscript formatting from cell
    rngA.Font.Bold = False
    rngA.Font.Underline = False
    rngA.Font.Italic = False
    rngA.Font.Subscript = False
    rngA.Font.Superscript = False

    rngA.Value = strActualText

    ' Now start applying Formats!"
    ' Start with Font Size first
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        varTag = "<font size"
        If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
            intFontSizeStartPos = InStr(intSrcPos, strHTML, """") + 1
            intFontSizeEndPos = InStr(intFontSizeStartPos, strHTML, """") - 1
            If intFontSizeEndPos - intFontSizeStartPos <= 3 And intFontSizeEndPos - intFontSizeStartPos > 0 Then
                Debug.Print Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                If Mid$(strHTML, intFontSizeStartPos, 1) = "+" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 + 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                ElseIf Mid$(strHTML, intFontSizeStartPos, 1) = "-" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 - 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                Else
                    intFontSize = Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                End If
            Else
                ' Error!
                GoTo HTML_Err
            End If
            intEndPos = InStr(intSrcPos, strHTML, ">")
            intSrcPos = intEndPos + 1
            intStartPos = intSrcPos
            If intSrcPos > Len(strHTML) Then Exit Do
            While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                intStartPos = intStartPos + 1
            Wend
            If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
            varEndTag = "</font>"
            intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
            If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
            While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                intEndPos = intEndPos - 1
            Wend
            If intEndPos > intSrcPos Then
                intActualStartPos = intDestSrcEquiv(intStartPos)
                intActualEndPos = intDestSrcEquiv(intEndPos)
                rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1) _
                    .Font.Size = intFontSize
            End If
        End If
        intSrcPos = intSrcPos + 1
    Loop

    'Now do remaining tags
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        If intDestSrcEquiv(intSrcPos) = 0 Then
            ' This must be a Tag!
            For intCtr = 0 To UBound(varyTags) Step 2
                varTag = varyTags(intCtr)
                intStartPos = intSrcPos + Len(varTag)
                While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                    intStartPos = intStartPos + 1
                Wend
                If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    varEndTag = varyTags(intCtr + 1)
                    intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
                    If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
                    While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                        intEndPos = intEndPos - 1
                    Wend
                    If intEndPos > intSrcPos Then
                        intActualStartPos = intDestSrcEquiv(intStartPos)
                        intActualEndPos = intDestSrcEquiv(intEndPos)
                        With rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1).Font
                            If varTag = "<b>" Then
                                .Bold = True
                            ElseIf varTag = "<i>" Then
                                .Italic = True
                            ElseIf varTag = "<u>" Then
                                .Underline = True
                            ElseIf varTag = "<sup>" Then
                                .Superscript = True
                            ElseIf varTag = "<sub>" Then
                                .Subscript = True
                            End If
                        End With
                    End If
                    intSrcPos = intSrcPos + Len(varTag) - 1
                    Exit For
                End If
            Next
        End If
        intSrcPos = intSrcPos + 1
        intDestPos = intDestPos + 1
    Loop
Exit_Sub:
    Exit Sub
HTML_Err:
    ' There was an error with the Tags. Show warning if requested.
    If blnShowBadHTMLWarning Then
        MsgBox "There was an error with the Tags in the HTML file. Could not apply formatting."
    End If
End Sub

Note this doesn't care about tag nesting, instead only requiring a close tag for every open tag, and assuming the close tag nearest the opening tag applies to the opening tag. Properly nested tags will work fine, while improperly nested tags will not be rejected and may or may not work.

SELECT DISTINCT on one column

SELECT min (id) AS 'ID', min(sku) AS 'SKU', Product
    FROM TestData
    WHERE sku LIKE 'FOO%' -- If you want only the sku that matchs with FOO%
    GROUP BY product 
    ORDER BY 'ID'

android ellipsize multiline textview

Got this problem to, and finaly, I build myself a short solution. You just have to ellipsize manually the line you want, your maxLine attribute will cut your text.

This example cut your text for 3 lines max

        final TextView title = (TextView)findViewById(R.id.text);
        title.setText("A really long text");
        ViewTreeObserver vto = title.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                ViewTreeObserver obs = title.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if(title.getLineCount() > 3){
                    Log.d("","Line["+title.getLineCount()+"]"+title.getText());
                    int lineEndIndex = title.getLayout().getLineEnd(2);
                    String text = title.getText().subSequence(0, lineEndIndex-3)+"...";
                    title.setText(text);
                    Log.d("","NewText:"+text);
                }

            }
        });

SQL WHERE ID IN (id1, id2, ..., idn)

What Ed Guiness suggested is really a performance booster , I had a query like this

select * from table where id in (id1,id2.........long list)

what i did :

DECLARE @temp table(
            ID  int
            )
insert into @temp 
select * from dbo.fnSplitter('#idlist#')

Then inner joined the temp with main table :

select * from table inner join temp on temp.id = table.id

And performance improved drastically.

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

String.Replace(char, char) method in C#

string temp = mystring.Replace("\n", " ");

Codeigniter's `where` and `or_where`

You can modify just the two lines:

->where('(library.available_until >=', date("Y-m-d H:i:s"), FALSE)
->or_where("library.available_until = '00-00-00 00:00:00')", NULL, FALSE)

EDIT:

Omitting the FALSE parameter would have placed the backticks before the brackets and make them a part of the table name/value, making the query unusable.

The NULL parameter is there just because the function requires the second parameter to be a value, and since we don't have one, we send NULL.

Fully custom validation error message with Rails

Yes, there's a way to do this without the plugin! But it is not as clean and elegant as using the mentioned plugin. Here it is.

Assuming it's Rails 3 (I don't know if it's different in previous versions),

keep this in your model:

validates_presence_of :song_rep_xyz, :message => "can't be empty"

and in the view, instead of leaving

@instance.errors.full_messages

as it would be when we use the scaffold generator, put:

@instance.errors.first[1]

And you will get just the message you specified in the model, without the attribute name.

Explanation:

#returns an hash of messages, one element foreach field error, in this particular case would be just one element in the hash:
@instance.errors  # => {:song_rep_xyz=>"can't be empty"}

#this returns the first element of the hash as an array like [:key,"value"]
@instance.errors.first # => [:song_rep_xyz, "can't be empty"]

#by doing the following, you are telling ruby to take just the second element of that array, which is the message.
@instance.errors.first[1]

So far we are just displaying only one message, always for the first error. If you wanna display all errors you can loop in the hash and show the values.

Hope that helped.

String parsing in Java with delimiter tab "\t" using split

You can use yourstring.split("\x09"); I tested it, and it works.

Convert JavaScript string in dot notation into an object reference

I used this code in my project

const getValue = (obj, arrPath) => (
  arrPath.reduce((x, y) => {
    if (y in x) return x[y]
    return {}
  }, obj)
)

Usage:

const obj = { id: { user: { local: 104 } } }
const path = [ 'id', 'user', 'local' ]
getValue(obj, path) // return 104

Using Git with Visual Studio

Git Source Control Provider is new plug-in that integrates Git with Visual Studio.

R: rJava package install failing

Wouldn't

apt-get install r-cran-rjava

have been easier? You could have asked me at useR! :)

Set a border around a StackPanel.

May be it will helpful:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

OSX solution:

install latest rvm stable version

rvm get stable

use rvm command to solve the certificates automatically

rvm osx-ssl-certs update all

Python: count repeated elements in the list

This works for Python 2.6.6

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result

prints

{'a': 2, 'b': 1}

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).

At startup, we do:

TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));

And set the desired timezone to the DateFormat:

fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))

Is there a 'box-shadow-color' property?

Maybe this is new (I am also pretty crap at css3), but I have a page that uses exactly what you suggest:

-moz-box-shadow: 10px 10px 5px #384e69;
-webkit-box-shadow: 10px 10px 5px #384e69;
box-shadow: 10px 10px 5px #384e69;}

.. and it works fine for me (in Chrome at least).

permission denied - php unlink

in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"

however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())

eventually as a fact:

in many programming languages, any permission related error may not directly means an actual permission issue

for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error

How should I print types like off_t and size_t?

As I recall, the only portable way to do it, is to cast the result to "unsigned long int" and use %lu.

printf("sizeof(int) = %lu", (unsigned long) sizeof(int));

How to post JSON to PHP with curl

Normally the parameter -d is interpreted as form-encoded. You need the -H parameter:

curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json

Single line sftp from terminal

A minor modification like below worked for me when using it from within perl and system() call:

sftp {user}@{host} <<< $'put {local_file_path} {remote_file_path}'

How do I install Python 3 on an AWS EC2 instance?

Here is the one command to install python3 on Amazon linux ec2 instance:

$sudo yum install python3 -y

$python3 --version

Python 3.7.6

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Couldn't you just do this?

var things = [
    { id: 1, color: 'yellow' },
    { id: 2, color: 'blue' },
    { id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
   function () {
        $('#result').html('"PassThings()" successfully called.');
   });

...and mark your action with

[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
    // do stuff with things here...
}

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

I am using Windows 10 Home edition.

I tried various combination,

netsh wlan show drivers
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=allow ssid=happy key=12345678
netsh wlan start hostednetwork

and also,

Control Panel\Network and Internet\Network Connections\Ethernet Properties\Sharing\Internet Connection Sharing\Allow other network users to connect through this computer Internet connection...

But still cannot activate WiFi hotspot.

While I have given up, somehow I click on Network icon on the taskbar, suddenly I see the buttons:

[ Wi-Fi ] [ Airplane Mode ] [ Mobile hotspot ]

Just like how our mobile phone can enable Mobile hotspot, Windows 10 has Mobile hotspot build-in. Just click on [ Mobile hotspot ] button and it works.

onclick="javascript:history.go(-1)" not working in Chrome

Use Simply this line code, there is no need to put anything in href attribute:

<a href="" onclick="window.history.go(-1)"> Go TO Previous Page</a>

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

Using 'sudo apt-get install build-essentials'

Drop the 's' off of the package name.

You want sudo apt-get install build-essential

You may also need to run sudo apt-get update to make sure that your package index is up to date.

For anyone wondering why this package may be needed as part of another install, it contains the essential tools for building most other packages from source (C/C++ compiler, libc, and make).

How to disable an Android button?

In Kotlin, if you refer the Button View with id then, enable/disable button as like

layout.xml

<Button
   android:id="@+id/btn_start"
   android:layout_width="100dp"
   android:layout_height="50dp"
   android:text="@string/start"
   android:layout_alignParentBottom="true"/>

activity.kt

  btn_start.isEnabled = true   //to enable button
  btn_start.isEnabled = false  //to disable button

Notification not showing in Oreo

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CHANNEL_ID")
            ........

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Hello";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mNotificationManager.createNotificationChannel(mChannel);
    }
    mNotificationManager.notify(notificationId, notificationBuilder.build());

What is your single most favorite command-line trick using Bash?

^R reverse search. Hit ^R, type a fragment of a previous command you want to match, and hit ^R until you find the one you want. Then I don't have to remember recently used commands that are still in my history. Not exclusively bash, but also: ^E for end of line, ^A for beginning of line, ^U and ^K to delete before and after the cursor, respectively.

Eclipse error ... cannot be resolved to a type

Also If you are using mavenised project then try to update your project by clicking Alt+F5. Or right click on the application and go to maven /update project.

It builds all your components and resolves if any import error is there.

Haskell: Converting Int to String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

CSS root directory

For example your directory is like this:

Desktop >
        ProjectFolder >
                      index.html
                      css >
                          style.css
                      images >
                             img.png

You are at your style.css and you want to use img.png as a background-image, use this:

url("../images/img.png")

Works for me!

How to define global variable in Google Apps Script

I'm using a workaround by returning a function with an object of my global variables:

function globalVariables(){
  var variables = {
    sheetName: 'Sheet1',
    variable1: 1,
    variable2: 2
  };
  return variables;
}

function functionThatUsesVariable (){
  var sheet =   SpreadsheetApp.getActiveSpreadsheet().getSheetByName(globalVariables().sheetName);
}

String concatenation in MySQL

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

Can vue-router open a link in a new tab?

If you are interested ONLY on relative paths like: /dashboard, /about etc, See other answers.

If you want to open an absolute path like: https://www.google.com to a new tab, you have to know that Vue Router is NOT meant to handle those.

However, they seems to consider that as a feature-request. #1280. But until they do that,



Here is a little trick you can do to handle external links with vue-router.

  • Go to the router configuration (probably router.js) and add this code:
/* Vue Router is not meant to handle absolute urls. */
/* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
Router.prototype.absUrl = function(url, newTab = true) {
  const link = document.createElement('a')
  link.href = url
  link.target = newTab ? '_blank' : ''
  if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
  link.click()
}

Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab

this.$router.absUrl('https://www.google.com)

Remember that whenever we open another page to a new tab we MUST use noopener noreferrer.

Read more here

or Here

How can I change text color via keyboard shortcut in MS word 2010

Alt+H, then type letters FC, then pick the color.

How to center a checkbox in a table cell?

This should work, I am using it:

<td align="center"> <input type="checkbox" name="myTextEditBox" value="checked" ></td>

SQL SELECT from multiple tables

SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
FROM product p
LEFT JOIN customer1 c1 ON p.cid = c1.cid
LEFT JOIN customer2 c2 ON p.cid = c2.cid

JavaScript: Object Rename Key

Here is an example to create a new object with renamed keys.

let x = { id: "checkout", name: "git checkout", description: "checkout repository" };

let renamed = Object.entries(x).reduce((u, [n, v]) => {
  u[`__${n}`] = v;
  return u;
}, {});

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

Increasing the JVM maximum heap size for memory intensive applications

Below conf works for me:

JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME

JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"

/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"

How to disable an input box using angular.js

Your markup should contain an additional attribute called ng-disabled whose value should be a condition or expression that would evaluate to be either true or false.

    <input data-ng-model="userInf.username"  class="span12 editEmail" 
       type="text"  placeholder="[email protected]"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{condition or expression}"
/>

And in the controller you may have some code that would affect the value of ng-disabled directive.

Compiling simple Hello World program on OS X via command line

Also, you can use an IDE like CLion (JetBrains) or a text editor like Atom, with the gpp-compiler plugin, works like a charm (F5 to compile & execute).

Find an object in array?

Swift 4,

Another way to achieve this using filter function,

if let object = elements.filter({ $0.title == "title" }).first {
    print("found")
} else {
    print("not found")
}

sqlalchemy IS NOT NULL select

In case anyone else is wondering, you can use is_ to generate foo IS NULL:

>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL

onchange equivalent in angular2

We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference

Since change is on the list of standard DOM events, we can use it:

(change)="saverange()"

In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:

[ngModel]="range" (ngModelChange)="saverange($event)"

Then

saverange(newValue) {
  this.range = newValue;
  this.Platform.ready().then(() => {
     this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
  })
} 

However, with this approach saverange() is called with every keystroke, so you're probably better off using (change).

Fixing Segmentation faults in C++

Before the problem arises, try to avoid it as much as possible:

  • Compile and run your code as often as you can. It will be easier to locate the faulty part.
  • Try to encapsulate low-level / error prone routines so that you rarely have to work directly with memory (pay attention to the modelization of your program)
  • Maintain a test-suite. Having an overview of what is currently working, what is no more working etc, will help you to figure out where the problem is (Boost test is a possible solution, I don't use it myself but the documentation can help to understand what kind of information must be displayed).

Use appropriate tools for debugging. On Unix:

  • GDB can tell you where you program crash and will let you see in what context.
  • Valgrind will help you to detect many memory-related errors.
  • With GCC you can also use mudflap With GCC, Clang and since October experimentally MSVC you can use Address/Memory Sanitizer. It can detect some errors that Valgrind doesn't and the performance loss is lighter. It is used by compiling with the-fsanitize=address flag.

Finally I would recommend the usual things. The more your program is readable, maintainable, clear and neat, the easiest it will be to debug.

Get the name of a pandas DataFrame

From here what I understand DataFrames are:

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

And Series are:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).

Series have a name attribute which can be accessed like so:

 In [27]: s = pd.Series(np.random.randn(5), name='something')

 In [28]: s
 Out[28]: 
 0    0.541
 1   -1.175
 2    0.129
 3    0.043
 4   -0.429
 Name: something, dtype: float64

 In [29]: s.name
 Out[29]: 'something'

EDIT: Based on OP's comments, I think OP was looking for something like:

 >>> df = pd.DataFrame(...)
 >>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
 >>> print(df.name)
 'df'

forEach loop Java 8 for Map entry set

Stream API

public void iterateStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}

Parsing xml using powershell

[xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'

foreach ($bename in $xmlfile.xml.Section.BEName) {
    if($bename.Status -eq 1){
        #Do something
    }
}

jQuery Remove string from string

If you just want to remove "username1" you can use a simple replace.

name.replace("username1,", "")

or you could use split like you mentioned.

var name = "username1, username2 and username3 like this post.".split(",")[1];      
$("h1").text(name);

jsfiddle example

Handling optional parameters in javascript

If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:

function getData(id, opt){
    var data = voodooMagic(id, opt.parameters);
    if (opt.callback!=undefined)
      opt.callback.call(data);
    return data;         
}

getData(5, {parameters: "1,2,3", callback: 
    function(){for (i=0;i<=1;i--)alert("FAIL!");}
});

Verify object attribute value with mockito

If you're using Java 8, you can use Lambda expressions to match.

import java.util.Optional;
import java.util.function.Predicate;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;

public class LambdaMatcher<T> extends BaseMatcher<T>
{
    private final Predicate<T> matcher;
    private final Optional<String> description;

    public LambdaMatcher(Predicate<T> matcher)
    {
        this(matcher, null);
    }

    public LambdaMatcher(Predicate<T> matcher, String description)
    {
        this.matcher = matcher;
        this.description = Optional.ofNullable(description);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean matches(Object argument)
    {
        return matcher.test((T) argument);
    }

    @Override
    public void describeTo(Description description)
    {
        this.description.ifPresent(description::appendText);
    }
}

Example call

@Test
public void canFindEmployee()
{
    Employee employee = new Employee("John");
    company.addEmployee(employee);

    verify(mockedDal).registerEmployee(argThat(new LambdaMatcher<>(e -> e.getName()
                                                                         .equals(employee.getName()))));
}

More info: http://source.coveo.com/2014/10/01/java8-mockito/

Append a Lists Contents to another List C#

if you want to get "terse" :)

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

for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

How to move git repository with all branches from bitbucket to github?

In case you couldn't find "Import code" button on github, you can:

  1. directly open Github Importer and enter the url. It will look like: Screenshot of github importer
  2. give it a name (or it will import the name automatically)
  3. select Public or Private repo
  4. Click Begin Import

UPDATE: Recently, Github announced the ability to "Import repositories with large files"

Adding additional data to select options using jQuery

To store another value in select options:

$("#select").append('<option value="4">another</option>')

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

using this will also work :

inputElement.onchange = function(event) {
   var fileList = event.target.files;
   //TODO do something with fileList.  
}

Export data from R to Excel

Here is a way to write data from a dataframe into an excel file by different IDs and into different tabs (sheets) by another ID associated to the first level id. Imagine you have a dataframe that has email_address as one column for a number of different users, but each email has a number of 'sub-ids' that have all the data.

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email_address = c(rep('[email protected]',3), rep('[email protected]', 3), rep('[email protected]', 3)))

So ids 1,2,3 would be associated with [email protected]. The following code splits the data by email and then puts 1,2,3 into different tabs. The important thing is to set append = True when writing the .xlsx file.


temp_dir <- tempdir()

for(i in unique(data$email_address)){
    
  data %>% 
    filter(email_address == i) %>% 
    arrange(id) -> subset_data
  
  for(j in unique(subset_data$id)){
    write.xlsx(subset_data %>% filter(id == j), 
      file = str_c(temp_dir,"/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0- 
       9._%+-]+"),'_', Sys.Date(), '.xlsx'), 
      sheetName = as.character(j), 
      append = TRUE)}
 
  }

The regex gets the name from the email address and puts it into the file-name.

Hope somebody finds this useful. I'm sure there's more elegant ways of doing this but it works.

Btw, here is a way to then send these individual files to the various email addresses in the data.frame. Code goes into second loop [j]

  send.mail(from = "[email protected]",
            to = i,
          subject = paste("Your report for", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"), 'on', Sys.Date()),
          body = "Your email body",
          authenticate = TRUE,
          smtp = list(host.name = "XXX", port = XXX,
                      user.name = Sys.getenv("XXX"), passwd = Sys.getenv("XXX")),
          attach.files = str_c(temp_dir, "/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"),'_', Sys.Date(), '.xlsx'))


Resize Cross Domain Iframe Height

There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example

<code>
    <?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
    <?php echo $output; ?>
</div>

<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>

<script>
if(window.attachEvent) {
    window.attachEvent('onload', iframeResizer);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            iframeResizer(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = iframeResizer;
    }
}
   function iframeResizer(){
        var result = document.getElementById("iframediv").offsetHeight;

        document.getElementById("iframe").style.height = result;
        document.getElementById("iframediv").style.display = 'none';
        document.getElementById("iframe").style.display = 'inline';
    }
</script>
</code>

Getting All Variables In Scope

If you just want to inspect the variables manually to help debug, just fire up the debugger:

debugger;

Straight into the browser console.

What's the correct way to communicate between controllers in AngularJS?

This is how I do it with Factory / Services and simple dependency injection (DI).

myApp = angular.module('myApp', [])

# PeopleService holds the "data".
angular.module('myApp').factory 'PeopleService', ()->
  [
    {name: "Jack"}
  ]

# Controller where PeopleService is injected
angular.module('myApp').controller 'PersonFormCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
  $scope.people = PeopleService
  $scope.person = {} 

  $scope.add = (person)->
    # Simply push some data to service
    PeopleService.push angular.copy(person)
]

# ... and again consume it in another controller somewhere...
angular.module('myApp').controller 'PeopleListCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
  $scope.people = PeopleService
]

How to Set Focus on JTextField?

if is there only one Top-Level Container then last lines in GUI constructor would be for example

.
.
.
myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});

How to disable action bar permanently

<application
    .
    .
    android:theme="@android:style/Theme.Holo.Light.NoActionBar"
    . >

maybe this help you

Run a Java Application as a Service on Linux

I wrote another simple wrapper here:

#!/bin/sh
SERVICE_NAME=MyService
PATH_TO_JAR=/usr/local/MyProject/MyJar.jar
PID_PATH_NAME=/tmp/MyService-pid
case $1 in
    start)
        echo "Starting $SERVICE_NAME ..."
        if [ ! -f $PID_PATH_NAME ]; then
            nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &
            echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is already running ..."
        fi
    ;;
    stop)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stoping ..."
            kill $PID;
            echo "$SERVICE_NAME stopped ..."
            rm $PID_PATH_NAME
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
    restart)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stopping ...";
            kill $PID;
            echo "$SERVICE_NAME stopped ...";
            rm $PID_PATH_NAME
            echo "$SERVICE_NAME starting ..."
            nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &
            echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
esac 

You can follow a full tutorial for init.d here and for systemd (ubuntu 16+) here

If you need the output log replace the 2

nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &

lines for

nohup java -jar $PATH_TO_JAR >> myService.out 2>&1&

cast class into another class or convert class to another

What he wants to say is:

"If you have two classes which share most of the same properties you can cast an object from class a to class b and automatically make the system understand the assignment via the shared property names?"

Option 1: Use reflection

Disadvantage : It's gonna slow you down more than you think.

Option 2: Make one class derive from another, the first one with common properties and other an extension of that.

Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!

Let there be:

class customer
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public int age { get; set; }
}
class employee
{
    public string firstname { get; set; }
    public int age { get; set; } 
}

Now here is an extension for Object type:

public static T Cast<T>(this Object myobj)
{
    Type objectType = myobj.GetType();
    Type target = typeof(T);
    var x = Activator.CreateInstance(target, false);
    var z = from source in objectType.GetMembers().ToList()
        where source.MemberType == MemberTypes.Property select source ;
    var d = from source in target.GetMembers().ToList()
        where source.MemberType == MemberTypes.Property select source;
    List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
       .ToList().Contains(memberInfo.Name)).ToList();
    PropertyInfo propertyInfo;
    object value;
    foreach (var memberInfo in members)
    {
        propertyInfo = typeof(T).GetProperty(memberInfo.Name);
        value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);

        propertyInfo.SetValue(x,value,null);
    }   
    return (T)x;
}  

Now you use it like this:

static void Main(string[] args)
{
    var cus = new customer();
    cus.firstname = "John";
    cus.age = 3;
    employee emp =  cus.Cast<employee>();
}

Method cast checks common properties between two objects and does the assignment automatically.

Hiding a button in Javascript

visibility=hidden

is very useful, but it will still take up space on the page. You can also use

display=none

because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")

How to get the cookie value in asp.net website

You may use Request.Cookies collection to read the cookies.

if(Request.Cookies["key"]!=null)
{
   var value=Request.Cookies["key"].Value;
}

How to delete the first row of a dataframe in R?

You can use negative indexing to remove rows, e.g.:

dat <- dat[-1, ]

Here is an example:

> dat <- data.frame(A = 1:3, B = 1:3)
> dat[-1, ]
  A B
2 2 2
3 3 3
> dat2 <- dat[-1, ]
> dat2
  A B
2 2 2
3 3 3

That said, you may have more problems than just removing the labels that ended up on row 1. It is more then likely that R has interpreted the data as text and thence converted to factors. Check what str(foo), where foo is your data object, says about the data types.

It sounds like you just need header = TRUE in your call to read in the data (assuming you read it in via read.table() or one of it's wrappers.)

What does 'git remote add upstream' help achieve?

The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.

So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.

htmlentities() vs. htmlspecialchars()

The differences between htmlspecialchars() and htmlentities() is very small. Lets see some examples:

htmlspecialchars

htmlspecialchars(string $string) takes multiple arguments where as the first argument is a string and all other arguments (certain flags, certain encodings etc. ) are optional. htmlspecialchars converts special characters in the string to HTML entities. For example if you have < br > in your string, htmlspecialchars will convert it into &lt; b &gt;. Whereas characters like µ † etc. have no special significance in HTML. So they will be not converted to HTML entities by htmlspecialchars function as shown in the below example.

echo htmlspecialchars('An example <br>'); // This will print - An example &lt; br &gt;
echo htmlspecialchars('µ †');             // This will print -  µ †

htmlentities

htmlentities ( string $string) is very similar to htmlspecialchars and takes multiple arguments where as the first argument is a string and all other arguments are optional (certain flags, certain encodings etc.). Unlike htmlspecialchars, htmlentities converts not only special characters in the string to HTML entities but all applicable characters to HTML entities.

echo htmlentities('An example <br>'); // This will print - An example &lt; br &gt;
echo htmlentities('µ †');             // This will print -  &micro; &dagger; 

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

How do you synchronise projects to GitHub with Android Studio?

In Android Studio 0.8.2 , you have the same option (ie Share on GitHub). If you want to find it, you can use ctrl+shift+a and enter github in the input text.

How to get the width and height of an android.widget.ImageView?

I could get image width and height by its drawable;

int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();

Django: save() vs update() to update the database?

Using update directly is more efficient and could also prevent integrity problems.

From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:

e = Entry.objects.get(id=10)
e.comments_on = False
e.save()

…do this:

Entry.objects.filter(id=10).update(comments_on=False)

Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().

What are MVP and MVC and what is the difference?

Model-View-Presenter

In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.

MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.

Two primary variations

Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.

  • Pro: maximum testability surface; clean separation of the View and Model
  • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.

Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.

  • Pro: by leveraging data binding the amount of code is reduced.
  • Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.

Model-View-Controller

In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:

    Action in the View
        -> Call to Controller
        -> Controller Logic
        -> Controller returns the View.

One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.

Presentation Model

One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.

There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns

How to check if an int is a null

In Java there isn't Null values for primitive Data types. If you need to check Null use Integer Class instead of primitive type. You don't need to worry about data type difference. Java converts int primitive type data to Integer. When concerning about the memory Integer takes more memory than int. But the difference of memory allocation, nothing to be considered.

In this case you must use Inter instead of int

Try below snippet and see example for more info,

Integer id;
String name;

//Refer this example
    Integer val = 0;

`

if (val != null){
System.out.println("value is not null");
}

`

Also you can assign Null as below,

val = null;

Provide an image for WhatsApp link sharing

If you want to have a picture next to an url from your website someone shared on WhatsApp, you have to put a metatag on the page where the URL links to, like this:

<meta property="og:image" content="http://unrestrictedstock.com/wp-content/uploads/Unrestricted-Stock-Small.png"/>

What is the difference between Bootstrap .container and .container-fluid classes?

Updated 2019

The basic difference is that container is scales responsively, while container-fluid is always width:100%. Therefore in the root CSS definitions, they appear the same, but if you look further you'll see that .container is bound to media queries.

Bootstrap 4

The container has 5 widths...

.container {
  width: 100%;
}

@media (min-width: 576px) {
  .container {
    max-width: 540px;
  }
}

@media (min-width: 768px) {
  .container {
    max-width: 720px;
  }
}

@media (min-width: 992px) {
  .container {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .container {
    max-width: 1140px;
  }
}

Bootstrap 3

The container has 4 sizes. Full width on xs screens, and then it's width varies based on the following media queries..

    @media (min-width: 1200px) {
        .container {
            width: 1170px;
        }
    }
    @media (min-width: 992px) {
        .container {
            width: 970px;
        }
    }
    @media (min-width: 768px) {
        .container {
            width: 750px;
        }
    }

container vs. container-fluid demo

How to index characters in a Golang string?

You can also try typecasting it with string.

package main

import "fmt"

func main() {
    fmt.Println(string("Hello"[1]))
}

How to POST a FORM from HTML to ASPX page

This is very possible. I mocked up 3 pages which should give you a proof of concept:

.aspx page:

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
</form>

code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each s As String In Request.Form.AllKeys
        Response.Write(s & ": " & Request.Form(s) & "<br />")
    Next
End Sub

Separate HTML page:

<form action="http://localhost/MyTestApp/Default.aspx" method="post">
    <input name="TextBox1" type="text" value="" id="TextBox1" />
    <input name="TextBox2" type="password" id="TextBox2" />
    <input type="submit" name="Button1" value="Button" id="Button1" />
</form>

...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.

ASP.NET email validator regex

I don't validate email address format anymore (Ok I check to make sure there is an at sign and a period after that). The reason for this is what says the correctly formatted address is even their email? You should be sending them an email and asking them to click a link or verify a code. This is the only real way to validate an email address is valid and that a person is actually able to recieve email.

Use JAXB to create Object from XML String

Or if you want a simple one-liner:

Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);

How do you get a directory listing sorted by creation date in python?

Here's my version:

def getfiles(dirpath):
    a = [s for s in os.listdir(dirpath)
         if os.path.isfile(os.path.join(dirpath, s))]
    a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))
    return a

First, we build a list of the file names. isfile() is used to skip directories; it can be omitted if directories should be included. Then, we sort the list in-place, using the modify date as the key.

Counting the number of occurences of characters in a string

I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.

Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.

Remember, making things simple counts. Life for developers is hard enough looking at complex code.

Have fun!

Tommy "I should be a Teacher" Kwee

How to crop a CvMat in OpenCV?

To create a copy of the crop we want, we can do the following,

// Read img
cv::Mat img = cv::imread("imgFileName");
cv::Mat croppedImg;

// This line picks out the rectangle from the image
// and copies to a new Mat
img(cv::Rect(xMin,yMin,xMax-xMin,yMax-yMin)).copyTo(croppedImg);

// Display diff
cv::imshow( "Original Image",  img );
cv::imshow( "Cropped Image",  croppedImg);
cv::waitKey();

How to remove all characters after a specific character in python?

The method find will return the character position in a string. Then, if you want remove every thing from the character, do this:

mystring = "123?567"
mystring[ 0 : mystring.index("?")]

>> '123'

If you want to keep the character, add 1 to the character position.

Why is an OPTIONS request sent and can I disable it?

edit 2018-09-13: added some precisions about this pre-flight request and how to avoid it at the end of this reponse.

OPTIONS requests are what we call pre-flight requests in Cross-origin resource sharing (CORS).

They are necessary when you're making requests across different origins in specific situations.

This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.

Your server should not ignore but handle these requests whenever you're attempting to do cross origin requests.

A good resource can be found here http://enable-cors.org/

A way to handle these to get comfortable is to ensure that for any path with OPTIONS method the server sends a response with this header

Access-Control-Allow-Origin: *

This will tell the browser that the server is willing to answer requests from any origin.

For more information on how to add CORS support to your server see the following flowchart

http://www.html5rocks.com/static/images/cors_server_flowchart.png

CORS Flowchart


edit 2018-09-13

CORS OPTIONS request is triggered only in somes cases, as explained in MDN docs:

Some requests don’t trigger a CORS preflight. Those are called “simple requests” in this article, though the Fetch spec (which defines CORS) doesn’t use that term. A request that doesn’t trigger a CORS preflight—a so-called “simple request”—is one that meets all the following conditions:

The only allowed methods are:

  • GET
  • HEAD
  • POST

Apart from the headers set automatically by the user agent (for example, Connection, User-Agent, or any of the other headers with names defined in the Fetch spec as a “forbidden header name”), the only headers which are allowed to be manually set are those which the Fetch spec defines as being a “CORS-safelisted request-header”, which are:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type (but note the additional requirements below)
  • DPR
  • Downlink
  • Save-Data
  • Viewport-Width
  • Width

The only allowed values for the Content-Type header are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.

No ReadableStream object is used in the request.

..The underlying connection was closed: An unexpected error occurred on a receive

Before Execute query I put the statement as below and it resolved my error. Just FYI in case it will help someone.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ctx.ExecuteQuery();

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Create a global variable in TypeScript

I found a way that works if I use JavaScript combined with TypeScript.

logging.d.ts:

declare var log: log4javascript.Logger;

log-declaration.js:

log = null;

initalize-app.ts

import './log-declaration.js';

// Call stuff to actually setup log.  
// Similar to this:
log = functionToSetupLog();

This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.

NOTE: I think this only works because I have the allowJs TypeScript option set to true.

If someone posts an pure TypeScript solution, I will accept that.

Finding element's position relative to the document

If you don't mind using jQuery, then you can use offset() function. Refer to documentation if you want to read up more about this function.

How to redirect verbose garbage collection output to a file?

From the output of java -X:

    -Xloggc:<file>    log GC status to a file with time stamps

Documented here:

-Xloggc:filename

Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of -verbose:gc with the time elapsed since the first GC event preceding each logged event. The -Xloggc option overrides -verbose:gc if both are given with the same java command.

Example:

    -Xloggc:garbage-collection.log

So the output looks something like this:

0.590: [GC 896K->278K(5056K), 0.0096650 secs]
0.906: [GC 1174K->774K(5056K), 0.0106856 secs]
1.320: [GC 1670K->1009K(5056K), 0.0101132 secs]
1.459: [GC 1902K->1055K(5056K), 0.0030196 secs]
1.600: [GC 1951K->1161K(5056K), 0.0032375 secs]
1.686: [GC 1805K->1238K(5056K), 0.0034732 secs]
1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs]
1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
connect_four: |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |
      +-|-+
   p: | | |
      +---+

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
{
    triangle[i] = new int[5 - i];
}

// ...

for (int i = 0; i < 5; ++i)
{
    delete[] triangle[i];
}

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
          +---+---+---+---+---+

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
    p[i] = new int[n - i];
}

// ...

for (int i = 0; i < n; ++i)
{
    delete[] p[i];
}
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
          | | | | | | | | | | |
          +---+---+---+---+---+
            ^
            |
            |
          +-|-+
       p: | | |
          +---+

Conversions

Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = connect_four[i];
}

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);
}

// ...

for (int i = 0; i < 6; ++i)
{
    delete[] p[i];
}
delete[] p;