Programs & Examples On #Array difference

How to get the difference between two arrays in JavaScript?

var result = [];
var arr1 = [1,2,3,4];
var arr2 = [2,3];
arr1.forEach(function(el, idx) {
    function unEqual(element, index, array) {
        var a = el;
        return (element!=a);
    }
    if (arr2.every(unEqual)) {
        result.push(el);
    };
});
alert(result);

Compare 2 arrays which returns difference

/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                    difference.push(array1[i]);
        }
    }

    return difference;
}   

You can then call the function anywhere in your code.

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

Display alert message and redirect after click on accept

echo "<script>
window.location.href='admin/ahm/panel';
alert('There are no fields to generate a report');
</script>";

Try out this way it works...

First assign the window with the new page where the alert box must be displayed then show the alert box.

phpmyadmin logs out after 1440 secs

There seems to be UI for changing phpmyadmin configurations Start apache and click the following link

http://localhost/phpmyadmin/setup/index.php?page=form&formset=Features#tab_Security

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

I just had the same question and noticed the answer in some kind of tutorial. In general you need to use the second form of the split method, using the

split(regex, limit)

Here is the full tutorial http://www.rgagnon.com/javadetails/java-0438.html

If you set some negative number for the limit parameter you will get empty strings in the array where the actual values are missing. To use this your initial string should have two copies of the delimiter i.e. you should have \t\t where the values are missing.

Hope this helps :)

Can I check if Bootstrap Modal Shown / Hidden?

I try like this with function then calling if needed a this function. Has been worked for me.

function modal_fix() {
var a = $(".modal"),
    b = $("body");
a.on("shown.bs.modal", function () {
    b.hasClass("modal-open") || b.addClass("modal-open");
});
}

How to fit Windows Form to any screen resolution?

simply set Autoscroll = true for ur windows form.. (its not good solution but helpful)..

try for panel also(Autoscroll property = true)

Alternative to Intersect in MySQL

SELECT
  campo1,
  campo2,
  campo3,
  campo4
FROM tabela1
WHERE CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
NOT IN
(SELECT CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
FROM tabela2);

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>

Start and stop a timer PHP

class Timer
{
    private $startTime = null;

    public function __construct($showSeconds = true)
    {
        $this->startTime = microtime(true);
        echo 'Working - please wait...' . PHP_EOL;
    }

    public function __destruct()
    {
        $endTime = microtime(true);
        $time = $endTime - $this->startTime;

        $hours = (int)($time / 60 / 60);
        $minutes = (int)($time / 60) - $hours * 60;
        $seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
        $timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));

        echo 'Job finished in ' . $timeShow . PHP_EOL;
    }
}

$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in h:m:s"

Changing background colour of tr element on mouseover

You could try:

tr:hover {
    background-color: #000;
}

tr:hover td {
    background-color: transparent; /* or #000 */
}

JS Fiddle demo.

What is the non-jQuery equivalent of '$(document).ready()'?

There is a standards based replacement,DOMContentLoaded that is supported by over 90%+ of browsers, but not IE8 (So below code use by JQuery for browser support):

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

jQuery's native function is much more complicated than just window.onload, as depicted below.

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}

How to make fixed header table inside scrollable div?

I needed the same and this solution worked the most simple and straightforward way:

http://www.farinspace.com/jquery-scrollable-table-plugin/

I just give an id to the table I want to scroll and put one line in Javascript. That's it!

By the way, first I also thought I want to use a scrollable div, but it is not necessary at all. You can use a div and put it into it, but this solution does just what we need: scrolls the table.

How to schedule a stored procedure in MySQL

I used this query and it worked for me:

CREATE EVENT `exec`
  ON SCHEDULE EVERY 5 SECOND
  STARTS '2013-02-10 00:00:00'
  ENDS '2015-02-28 00:00:00'
  ON COMPLETION NOT PRESERVE ENABLE
DO 
  call delete_rows_links();

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

Increasing the maximum number of TCP/IP connections in Linux

Maximum number of connections are impacted by certain limits on both client & server sides, albeit a little differently.

On the client side: Increase the ephermal port range, and decrease the tcp_fin_timeout

To find out the default values:

sysctl net.ipv4.ip_local_port_range
sysctl net.ipv4.tcp_fin_timeout

The ephermal port range defines the maximum number of outbound sockets a host can create from a particular I.P. address. The fin_timeout defines the minimum time these sockets will stay in TIME_WAIT state (unusable after being used once). Usual system defaults are:

  • net.ipv4.ip_local_port_range = 32768 61000
  • net.ipv4.tcp_fin_timeout = 60

This basically means your system cannot consistently guarantee more than (61000 - 32768) / 60 = 470 sockets per second. If you are not happy with that, you could begin with increasing the port_range. Setting the range to 15000 61000 is pretty common these days. You could further increase the availability by decreasing the fin_timeout. Suppose you do both, you should see over 1500 outbound connections per second, more readily.

To change the values:

sysctl net.ipv4.ip_local_port_range="15000 61000"
sysctl net.ipv4.tcp_fin_timeout=30

The above should not be interpreted as the factors impacting system capability for making outbound connections per second. But rather these factors affect system's ability to handle concurrent connections in a sustainable manner for large periods of "activity."

Default Sysctl values on a typical Linux box for tcp_tw_recycle & tcp_tw_reuse would be

net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_tw_reuse=0

These do not allow a connection from a "used" socket (in wait state) and force the sockets to last the complete time_wait cycle. I recommend setting:

sysctl net.ipv4.tcp_tw_recycle=1
sysctl net.ipv4.tcp_tw_reuse=1 

This allows fast cycling of sockets in time_wait state and re-using them. But before you do this change make sure that this does not conflict with the protocols that you would use for the application that needs these sockets. Make sure to read post "Coping with the TCP TIME-WAIT" from Vincent Bernat to understand the implications. The net.ipv4.tcp_tw_recycle option is quite problematic for public-facing servers as it won’t handle connections from two different computers behind the same NAT device, which is a problem hard to detect and waiting to bite you. Note that net.ipv4.tcp_tw_recycle has been removed from Linux 4.12.

On the Server Side: The net.core.somaxconn value has an important role. It limits the maximum number of requests queued to a listen socket. If you are sure of your server application's capability, bump it up from default 128 to something like 128 to 1024. Now you can take advantage of this increase by modifying the listen backlog variable in your application's listen call, to an equal or higher integer.

sysctl net.core.somaxconn=1024

txqueuelen parameter of your ethernet cards also have a role to play. Default values are 1000, so bump them up to 5000 or even more if your system can handle it.

ifconfig eth0 txqueuelen 5000
echo "/sbin/ifconfig eth0 txqueuelen 5000" >> /etc/rc.local

Similarly bump up the values for net.core.netdev_max_backlog and net.ipv4.tcp_max_syn_backlog. Their default values are 1000 and 1024 respectively.

sysctl net.core.netdev_max_backlog=2000
sysctl net.ipv4.tcp_max_syn_backlog=2048

Now remember to start both your client and server side applications by increasing the FD ulimts, in the shell.

Besides the above one more popular technique used by programmers is to reduce the number of tcp write calls. My own preference is to use a buffer wherein I push the data I wish to send to the client, and then at appropriate points I write out the buffered data into the actual socket. This technique allows me to use large data packets, reduce fragmentation, reduces my CPU utilization both in the user land and at kernel-level.

Jump to function definition in vim

Use ctags. Generate a tags file, and tell vim where it is using the :tags command. Then you can just jump to the function definition using Ctrl-]

There are more tags tricks and tips in this question.

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

You should, as a rule, leave timestamps in the database in GMT, and only convert them to/from local time on input/output, when you can convert them to the user's (not server's) local timestamp.

It would be nice if you could do the following:

SELECT DATETIME(col, 'PDT')

...to output the timestamp for a user on Pacific Daylight Time. Unfortunately, that doesn't work. According to this SQLite tutorial, however (scroll down to "Other Date and Time Commands"), you can ask for the time, and then apply an offset (in hours) at the same time. So, if you do know the user's timezone offset, you're good.

Doesn't deal with daylight saving rules, though...

How do I change the android actionbar title and icon

The action bar title will, by default, use the label of the current activity, but you can also set it programmatically via ActionBar.setTitle().

To implement the "Back" (more precisely, "Up") button functionality you're talking about, read the "Using the App Icon for Navigation" section of the Action Bar developer guide.

Finally, to change the icon, the guide covers that as well. In short, the action bar will display the image supplied in android:icon in your manifest's application or activity element, if there is one. The typical practice is to create an application icon (in all of the various densities you'll need) named ic_launcher.png, and place it in your drawable-* directories.

Android open camera from button

 Button b = (Button)findViewById(R.id.Button01);

    b.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
             Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
             startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_PIC_REQUEST) {
          Bitmap image = (Bitmap) data.getExtras().get("data");
          ImageView imageview = (ImageView) findViewById(R.id.ImageView01); //sets imageview as the bitmap
          imageview.setImageBitmap(image);
    }
}

How to easily map c++ enums to strings

I'd be tempted to have a map m - and embedd this into the enum.

setup with m[MyEnum.VAL1] = "Value 1";

and all is done.

Regex that matches integers in between whitespace or start/end of string only

I would add this as a comment to the other good answers, but I need more reputation to do so. Be sure to allow for scientific notation if necessary, i.e. 3e4 = 30000. This is default behavior in many languages. I found the following regex to work:

/^[-+]?\d+([Ee][+-]?\d+)?$/;
//          ^^              If 'e' is present to denote exp notation, get it
//             ^^^^^          along with optional sign of exponent
//                  ^^^       and the exponent itself
//        ^            ^^     The entire exponent expression is optional

Cannot implicitly convert type from Task<>

Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

How does lock work exactly?

The part within the lock statement can only be executed by one thread, so all other threads will wait indefinitely for it the thread holding the lock to finish. This can result in a so-called deadlock.

Can I style an image's ALT text with CSS?

Yes, image alt text can be styled using any style property you use for regular text, such as font-size, font-weight, line-height, color, background-color,etc. The line-height (of text) or vertical-align (if display:table-cell used) could also be used to vertically align alt text within an image element or image wrapping container, i.e. div.

To prevent accessibility issues regarding contrast, and inheriting the browser's default black font color when you've set a dark blue background-color, always set both the color of your font and its background-color at the same time.

for some more useful info, visit Alternate text for background images or The Ultimate Guide to Styled ALT Text in Email

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

If you download the 64 bit version of Eclipse; it will look for the 64 bit version of JRE. If you download the 32 bit version of Eclipse; it will look for the 32 bit version of JRE

What I did was to install the both the 32 and 64 bit version of JRE. You can get that from the SUN Oracle site. The JAVA site seems to automatically install the 32 bit version of Java. I guess that's because of the web browser.

How to upload files on server folder using jsp

Below code is working on my live server as well as in my own Lapy.

Note:

Please Create data folder in WebContent and put in any single image or any file(jsp or html file).

Add jar files

commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar

upload.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>

UploadServlet.java

package com.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }

            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(
                    request, response);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }

}

web.xml

  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>

done.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>

How to check that a string is parseable to a double?

Apache, as usual, has a good answer from Apache Commons-Lang in the form of NumberUtils.isCreatable(String).

Handles nulls, no try/catch block required.

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

'git status' shows changed files, but 'git diff' doesn't

I've just run in a similar issue. git diff file showed nothing because I added file to the Git index with some part of its name in uppercase: GeoJSONContainer.js.

Afterwards, I've renamed it to GeoJsonContainer.js and changes stopped being tracked. git diff GeoJsonContainer.js was showing nothing. I had to remove the file from the index with a force flag, and add the file again:

git rm -f GeoJSONContainer.js
git add GeoJSONContainer.js

Installing Android Studio, does not point to a valid JVM installation error

1) Just remove \bin from Java_home environmental Variable. This worked for me .
2) Also make sure you are using the correct versions of android studio and Java (32/64 bit)

Regular expression negative lookahead

If you revise your regular expression like this:

drupal-6.14/(?=sites(?!/all|/default)).*
             ^^

...then it will match all inputs that contain drupal-6.14/ followed by sites followed by anything other than /all or /default. For example:

drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall

Changing ?= to ?! to match your original regex simply negates those matches:

drupal-6.14/(?!sites(?!/all|/default)).*
             ^^

So, this simply means that drupal-6.14/ now cannot be followed by sites followed by anything other than /all or /default. So now, these inputs will satisfy the regex:

drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42

But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/ is followed by anything other than sites as well. For example:

drupal-6.14/foo
drupal-6.14/xsites

Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14 except those subdirectories of sites whose name begins with anything other than all or default.

What does (function($) {})(jQuery); mean?

Just small addition to explanation

This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:

(function($) {
  // do something
})(jQuery);

this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.

How to import and use image in a Vue single file component?

I came across this issue recently, and i'm using Typescript. If you're using Typescript like I am, then you need to import assets like so:

<img src="@/assets/images/logo.png" alt="">

Having Django serve downloadable files

For the "best of both worlds" you could combine S.Lott's solution with the xsendfile module: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you've set up mod_xsendfile, integrating with your view takes a few lines of code:

from django.utils.encoding import smart_str

response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
# It's usually a good idea to set the 'Content-Length' header too.
# You can also set any other required headers: Cache-Control, etc.
return response

Of course, this will only work if you have control over your server, or your hosting company has mod_xsendfile already set up.

EDIT:

mimetype is replaced by content_type for django 1.7

response = HttpResponse(content_type='application/force-download')  

EDIT: For nginx check this, it uses X-Accel-Redirect instead of apache X-Sendfile header.

How can I see the specific value of the sql_mode?

It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:

mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
|            |
+------------+
1 row in set (0.00 sec)

mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                                           |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

Add single element to array in numpy

Let's say a=[1,2,3] and you want it to be [1,2,3,1].

You may use the built-in append function

np.append(a,1)

Here 1 is an int, it may be a string and it may or may not belong to the elements in the array. Prints: [1,2,3,1]

Get all dates between two dates in SQL Server

My first suggestion would be use your calendar table, if you don't have one, then create one. They are very useful. Your query is then as simple as:

DECLARE @MinDate DATE = '20140101',
        @MaxDate DATE = '20140106';

SELECT  Date
FROM    dbo.Calendar
WHERE   Date >= @MinDate
AND     Date < @MaxDate;

If you don't want to, or can't create a calendar table you can still do this on the fly without a recursive CTE:

DECLARE @MinDate DATE = '20140101',
        @MaxDate DATE = '20140106';

SELECT  TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
FROM    sys.all_objects a
        CROSS JOIN sys.all_objects b;

For further reading on this see:

With regard to then using this sequence of dates in a cursor, I would really recommend you find another way. There is usually a set based alternative that will perform much better.

So with your data:

  date   | it_cd | qty 
24-04-14 |  i-1  | 10 
26-04-14 |  i-1  | 20

To get the quantity on 28-04-2014 (which I gather is your requirement), you don't actually need any of the above, you can simply use:

SELECT  TOP 1 date, it_cd, qty 
FROM    T
WHERE   it_cd = 'i-1'
AND     Date <= '20140428'
ORDER BY Date DESC;

If you don't want it for a particular item:

SELECT  date, it_cd, qty 
FROM    (   SELECT  date, 
                    it_cd, 
                    qty, 
                    RowNumber = ROW_NUMBER() OVER(PARTITION BY ic_id 
                                                    ORDER BY date DESC)
            FROM    T
            WHERE   Date  <= '20140428'
        ) T
WHERE   RowNumber = 1;

Regular expression to match a dot

to escape non-alphanumeric characters of string variables, including dots, you could use re.escape:

import re

expression = 'whatever.v1.dfc'
escaped_expression = re.escape(expression)
print(escaped_expression)

output:

whatever\.v1\.dfc

you can use the escaped expression to find/match the string literally.

How to change font-color for disabled input?

input[disabled], input[disabled]:hover { background-color:#444; }

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Export a list into a CSV or TXT file in R

cat(capture.output(print(my.list), file="test.txt"))

from R: Export and import a list to .txt file https://stackoverflow.com/users/1855677/42 is the only thing that worked for me. This outputs the list of lists as it is in the text file

UTF-8: General? Bin? Unicode?

  • utf8_bin compares the bits blindly. No case folding, no accent stripping.
  • utf8_general_ci compares one byte with one byte. It does case folding and accent stripping, but no 2-character comparisions: ij is not equal ? in this collation.
  • utf8_*_ci is a set of language-specific rules, but otherwise like unicode_ci. Some special cases: Ç, C, ch, ll
  • utf8_unicode_ci follows an old Unicode standard for comparisons. ij=?, but ae != æ
  • utf8_unicode_520_ci follows an newer Unicode standard. ae = æ

See collation chart for details on what is equal to what in various utf8 collations.

utf8, as defined by MySQL is limited to the 1- to 3-byte utf8 codes. This leaves out Emoji and some of Chinese. So you should really switch to utf8mb4 if you want to go much beyond Europe.

The above points apply to utf8mb4, after suitable spelling change. Going forward, utf8mb4 and utf8mb4_unicode_520_ci are preferred.

  • utf16 and utf32 are variants on utf8; there is virtually no use for them.
  • ucs2 is closer to "Unicode" than "utf8"; there is virtually no use for it.

Determining whether an object is a member of a collection in VBA

It requires some additional adjustments in case the items in the collection are not Objects, but Arrays. Other than that it worked fine for me.

Public Function CheckExists(vntIndexKey As Variant) As Boolean
    On Error Resume Next
    Dim cObj As Object

    ' just get the object
    Set cObj = mCol(vntIndexKey)

    ' here's the key! Trap the Error Code
    ' when the error code is 5 then the Object is Not Exists
    CheckExists = (Err <> 5)

    ' just to clear the error
    If Err <> 0 Then Call Err.Clear
    Set cObj = Nothing
End Function

Source: http://coderstalk.blogspot.com/2007/09/visual-basic-programming-how-to-check.html

Using a SELECT statement within a WHERE clause

It's called correlated subquery. It has it's uses.

Difference in boto3 between resource, client, and session?

I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.

Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )

sqs = boto3.client('sqs')
s3 = boto3.resource('s3')

Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.

# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')

# you have two choices of create custom client session. 
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')

Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.

import boto3 
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket') 
video_bucket = video_s3.Bucket('videobucket')

# just pass the instantiated bucket object
def list_bucket_contents(bucket):
   for object in bucket.objects.all():
      print(object.key)

list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)

Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.

For example, if you only deal with the default session, this looks similar to boto3.resource.

import boto3 
s3 = boto3.client('s3')

def list_bucket_contents(bucket_name):
   for object in s3.list_objects_v2(Bucket=bucket_name) :
      print(object.key)

list_bucket_contents('Mybucket') 

However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.

import boto3 
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')

# you must pass boto3.Session.client and the bucket name 
def list_bucket_contents(s3session, bucket_name):
   response = s3session.list_objects_v2(Bucket=bucket_name)
   if 'Contents' in response:
     for obj in response['Contents']:
        print(obj['key'])

list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket') 

How do I send an HTML Form in an Email .. not just MAILTO

I actually use ASP C# to send my emails now, with something that looks like :

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form.Count > 0)
    {
        string formEmail = "";
        string fromEmail = "[email protected]";
        string defaultEmail = "[email protected]";

        string sendTo1 = "";

        int x = 0;

        for (int i = 0; i < Request.Form.Keys.Count; i++)
        {
            formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
            formEmail += ": " + Request.Form[i] + "<br/>";
            if (Request.Form.Keys[i] == "Email")
            {
                if (Request.Form[i].ToString() != string.Empty)
                {
                    fromEmail = Request.Form[i].ToString();
                }
                formEmail += "<br/>";
            }

        }
        System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
        SmtpClient smtpClient = new SmtpClient();

        try
        {
            myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
            myMsg.IsBodyHtml = true;
            myMsg.Body = formEmail;
            myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
            myMsg.Subject = "Sent using Gmail Smtp";
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pward");

            smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);

        }
        catch (Exception ee)
        {
            debug.Text += ee.Message;
        }
    }
}

This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.

Applying styles to tables with Twitter Bootstrap

you can Add contextual classes to every single row as follows:

<tr class="table-success"></tr>
<tr class="table-error"></tr>
<tr class="table-warning"></tr>
<tr class="table-info"></tr>
<tr class="table-danger"></tr>

You can also add them to table data same as above

You can set your table size by setting classes as table-sm and so on.

You can add custom classes and add your own styling:

<table class="table">
  <thead style = "color:red;background-color:blue">
    <tr>
      <th></th>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>   
      <td>Asdf</td>
      <td>qwerty</td>
    </tr>
  </tbody>
</table>

This way you can add custom styling. I have showed inline styling just for example how it works, you can add classes and call them in your css as well.

$(window).scrollTop() vs. $(document).scrollTop()

They are both going to have the same effect.

However, as pointed out in the comments: $(window).scrollTop() is supported by more web browsers than $('html').scrollTop().

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

How to remove duplicates from a list?

private void removeTheDuplicates(List<Customer>myList) {
    for(ListIterator<Customer>iterator = myList.listIterator(); iterator.hasNext();) {
        Customer customer = iterator.next();
        if(Collections.frequency(myList, customer) > 1) {
            iterator.remove();
        }
    }
    System.out.println(myList.toString());

}

How do you return the column names of a table?

set fmtonly on
select * from yourTable

Offline Speech Recognition In Android (JellyBean)

I was dealing with this and I noticed that you need to install the offline package for your Language. My language setting was "Español (Estados Unidos)" but there is not offline package for that language, so when I turned off all network connectivity I was getting an alert from RecognizerIntent saying that can't reach Google, then I change the language to "English (US)" (because I already have the offline package) and launched the RecognizerIntent it just worked out.

Keys: Language setting == Offline Voice Recognizer Package

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

    // pop back stack all the way
    final FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
    int entryCount = fm.getBackStackEntryCount(); 
    while (entryCount-- > 0) {
        fm.popBackStack();
    }

Make a nav bar stick

Give headercss position fixed.

.headercss {
    width: 100%;
    height: 320px;
    background-color: #000000;
    position: fixed;
    top:0
}

Then give the content container a 320px padding-top, so it doesn't get behind the header.

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

Convert string to List<string> in one line?

Use the Stringify.Library nuget package

//Default delimiter is ,
var split = new StringConverter().ConvertTo<List<string>>(names);

//You can also have your custom delimiter for e.g. ;
var split = new StringConverter().ConvertTo<List<string>>(names, new ConverterOptions { Delimiter = ';' });

Free Barcode API for .NET

There is a "3 of 9" control on CodeProject: Barcode .NET Control

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

Get access to parent control from user control - C#

You can get the Parent of a control via

myControl.Parent

See MSDN: Control.Parent

how to set font size based on container size?

If you want to scale it depending on the element width, you can use this web component:
https://github.com/pomber/full-width-text

Check the demo here:
https://pomber.github.io/full-width-text/

The usage is like this:

<full-width-text>Lorem Ipsum</full-width-text>

Generating random integer from a range

How about the Mersenne Twister? The boost implementation is rather easy to use and is well tested in many real-world applications. I've used it myself in several academic projects such as artificial intelligence and evolutionary algorithms.

Here's their example where they make a simple function to roll a six-sided die:

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

boost::mt19937 gen;

int roll_die() {
    boost::uniform_int<> dist(1, 6);
    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(gen, dist);
    return die();
}

Oh, and here's some more pimping of this generator just in case you aren't convinced you should use it over the vastly inferior rand():

The Mersenne Twister is a "random number" generator invented by Makoto Matsumoto and Takuji Nishimura; their website includes numerous implementations of the algorithm.

Essentially, the Mersenne Twister is a very large linear-feedback shift register. The algorithm operates on a 19,937 bit seed, stored in an 624-element array of 32-bit unsigned integers. The value 2^19937-1 is a Mersenne prime; the technique for manipulating the seed is based on an older "twisting" algorithm -- hence the name "Mersenne Twister".

An appealing aspect of the Mersenne Twister is its use of binary operations -- as opposed to time-consuming multiplication -- for generating numbers. The algorithm also has a very long period, and good granularity. It is both fast and effective for non-cryptographic applications.

What is the best way to conditionally apply a class?

Ternary operator has just been added to angular parser in 1.1.5.

So the simplest way to do this is now :

ng:class="($index==selectedIndex)? 'selected' : ''"

How do I escape double and single quotes in sed?

My problem was that I needed to have the "" outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the " inside the sed regex with [\"].

So my complete bash is:

RELEASE_VERSION="0.6.6"

sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml

Here is:

# is the sed separator

[\"] = " in regex

value = \"tags/$RELEASE_VERSION\" = my replacement string, important it has just the \" for the quotes

Namespace not recognized (even though it is there)

Check to make sure that your project isn't set up to use the .NET Framework 4 Client Profile.

You can check/change this by right-clicking your project (not the solution), select Properties -> Application -> Target framework. The target framework is a dropdown on that page.

This is a problem in Visual Studio (I would even go so far as to call it a bug). AutoMapper requires assemblies that are excluded from the .NET Framework 4 Client Profile. Since your project is using that version of the framework it breaks.

A similar error will propagate to the build process when the .NET Framework version for the project you are referencing is higher than the project making the reference. i.e. A project targeting 4.5 that references a project targeting 4.5.1 will give you this same error.

There needs to be a better error message when this happens because there is no rational explanation as to why it would not build as the error message tells you to reference an assembly you have clearly referenced.

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

Why use a READ UNCOMMITTED isolation level?

It can be used for a simple table, for example in an insert-only audit table, where there is no update to existing row, and no fk to other table. The insert is a simple insert, which has no or little chance of rollback.

How to terminate a python subprocess launched with shell=True

what i feel like we could use:

import os
import signal
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

os.killpg(os.getpgid(pro.pid), signal.SIGINT)

this will not kill all your task but the process with the p.pid

Send string to stdin

cat | /my/bash/script

Enables one to type multiple lines into a program, without that input being saved in history, nor visible in ps. Just press Ctrl + C when finished typing to end cat.

Rails: select unique values from a column

Model.select(:rating)

The result of this is a collection of Model objects. Not plain ratings. And from uniq's point of view, they are completely different. You can use this:

Model.select(:rating).map(&:rating).uniq

or this (most efficient):

Model.uniq.pluck(:rating)

Rails 5+

Model.distinct.pluck(:rating)

Update

Apparently, as of rails 5.0.0.1, it works only on "top level" queries, like above. Doesn't work on collection proxies ("has_many" relations, for example).

Address.distinct.pluck(:city) # => ['Moscow']
user.addresses.distinct.pluck(:city) # => ['Moscow', 'Moscow', 'Moscow']

In this case, deduplicate after the query

user.addresses.pluck(:city).uniq # => ['Moscow']

Sort an array of objects in React and render them

You will need to sort your object before mapping over them. And it can be done easily with a sort() function with a custom comparator definition like

var obj = [...this.state.data];
obj.sort((a,b) => a.timeM - b.timeM);
obj.map((item, i) => (<div key={i}> {item.matchID}  
                      {item.timeM} {item.description}</div>))

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

Changing Tint / Background color of UITabBar

iOS 5 has added some new appearance methods for customising the look of most UI elements.

You can target every instance of a UITabBar in your app by using the appearance proxy.

For iOS 5 + 6:

[[UITabBar appearance] setTintColor:[UIColor redColor]];

For iOS 7 and above, please use the following:

[[UITabBar appearance] setBarTintColor:[UIColor redColor]];

Using the appearance proxy will change any tab bar instance throughout the app. For a specific instance, use one of the new properties on that class:

UIColor *tintColor; // iOS 5+6
UIColor *barTintColor; // iOS 7+
UIColor *selectedImageTintColor;
UIImage *backgroundImage;
UIImage *selectionIndicatorImage;

Insert default value when parameter is null

With enough defaults on a table, you can simply say:

INSERT t DEFAULT VALUES

Note that this is quite an unlikely case, however.

I've only had to use it once in a production environment. We had two closely related tables, and needed to guarantee that neither table had the same UniqueID, so we had a separate table which just had an identity column, and the best way to insert into it was with the syntax above.

scrollable div inside container

i have just added (overflow:scroll;) in (div3) with fixed height.

see the fiddle:- http://jsfiddle.net/fMs67/10/

Detect a finger swipe through JavaScript on the iPhone and Android

Used two:

jQuery mobile: work in most of cases and specially when you are developing applicaion which uses other jQuery plugin then better to use jQuery mobile controls for this. Visit it here: https://www.w3schools.com/jquerymobile/jquerymobile_events_touch.asp

Hammer Time ! one of the best,lightweight and fast javascript based library. Visit it here: https://hammerjs.github.io/

XMLHttpRequest status 0 (responseText is empty)

Open javascript console. You'll see an error message there. In my case it was CORS.

Forms authentication timeout vs sessionState timeout

From what I understand they are independent of one another. By keeping the session timeout less than or equal to the authentication timeout, you can make sure any user-specific session variables are not persisted after the authentication has timed out (if that is your concern, which I think is the normal one when asking this question). Of course, you'll have to manually handle the disposal of session variables upon log-out.

Here is a decent response that may answer your question or at least point you in the right direction:

C# Ignore certificate errors?

To disable ssl cert validation in client configuration.

<behaviors>
   <endpointBehaviors>
      <behavior name="DisableSSLCertificateValidation">
         <clientCredentials>
             <serviceCertificate>
                <sslCertificateAuthentication certificateValidationMode="None" />
              </serviceCertificate>
           </clientCredentials>
        </behavior>

System.loadLibrary(...) couldn't find native library in my case

For reference, I had this error message and the solution was that when you specify the library you miss the 'lib' off the front and the '.so' from the end.

So, if you have a file libmyfablib.so, you need to call:

   System.loadLibrary("myfablib"); // this loads the file 'libmyfablib.so' 

Having looked in the apk, installed/uninstalled and tried all kinds of complex solutions I couldn't see the simple problem that was right in front of my face!

In plain English, what does "git reset" do?

In general, git reset's function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. More concretely, if your master branch (currently checked out) is like this:

- A - B - C (HEAD, master)

and you realize you want master to point to B, not C, you will use git reset B to move it there:

- A - B (HEAD, master)      # - C is still here, but there's no branch pointing to it anymore

Digression: This is different from a checkout. If you'd run git checkout B, you'd get this:

- A - B (HEAD) - C (master)

You've ended up in a detached HEAD state. HEAD, work tree, index all match B, but the master branch was left behind at C. If you make a new commit D at this point, you'll get this, which is probably not what you want:

- A - B - C (master)
       \
        D (HEAD)

Remember, reset doesn't make commits, it just updates a branch (which is a pointer to a commit) to point to a different commit. The rest is just details of what happens to your index and work tree.

Use cases

I cover many of the main use cases for git reset within my descriptions of the various options in the next section. It can really be used for a wide variety of things; the common thread is that all of them involve resetting the branch, index, and/or work tree to point to/match a given commit.

Things to be careful of

  • --hard can cause you to really lose work. It modifies your work tree.

  • git reset [options] commit can cause you to (sort of) lose commits. In the toy example above, we lost commit C. It's still in the repo, and you can find it by looking at git reflog show HEAD or git reflog show master, but it's not actually accessible from any branch anymore.

  • Git permanently deletes such commits after 30 days, but until then you can recover C by pointing a branch at it again (git checkout C; git branch <new branch name>).

Arguments

Paraphrasing the man page, most common usage is of the form git reset [<commit>] [paths...], which will reset the given paths to their state from the given commit. If the paths aren't provided, the entire tree is reset, and if the commit isn't provided, it's taken to be HEAD (the current commit). This is a common pattern across git commands (e.g. checkout, diff, log, though the exact semantics vary), so it shouldn't be too surprising.

For example, git reset other-branch path/to/foo resets everything in path/to/foo to its state in other-branch, git reset -- . resets the current directory to its state in HEAD, and a simple git reset resets everything to its state in HEAD.

The main work tree and index options

There are four main options to control what happens to your work tree and index during the reset.

Remember, the index is git's "staging area" - it's where things go when you say git add in preparation to commit.

  • --hard makes everything match the commit you've reset to. This is the easiest to understand, probably. All of your local changes get clobbered. One primary use is blowing away your work but not switching commits: git reset --hard means git reset --hard HEAD, i.e. don't change the branch but get rid of all local changes. The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard.

  • --mixed is the default, i.e. git reset means git reset --mixed. It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status. Use this when you realize you made some bad commits, but you want to keep all the work you've done so you can fix it up and recommit. In order to commit, you'll have to add files to the index again (git add ...).

  • --soft doesn't touch the index or work tree. All your files are intact as with --mixed, but all the changes show up as changes to be committed with git status (i.e. checked in in preparation for committing). Use this when you realize you've made some bad commits, but the work's all good - all you need to do is recommit it differently. The index is untouched, so you can commit immediately if you want - the resulting commit will have all the same content as where you were before you reset.

  • --merge was added recently, and is intended to help you abort a failed merge. This is necessary because git merge will actually let you attempt a merge with a dirty work tree (one with local modifications) as long as those modifications are in files unaffected by the merge. git reset --merge resets the index (like --mixed - all changes show up as local modifications), and resets the files affected by the merge, but leaves the others alone. This will hopefully restore everything to how it was before the bad merge. You'll usually use it as git reset --merge (meaning git reset --merge HEAD) because you only want to reset away the merge, not actually move the branch. (HEAD hasn't been updated yet, since the merge failed)

    To be more concrete, suppose you've modified files A and B, and you attempt to merge in a branch which modified files C and D. The merge fails for some reason, and you decide to abort it. You use git reset --merge. It brings C and D back to how they were in HEAD, but leaves your modifications to A and B alone, since they weren't part of the attempted merge.

Want to know more?

I do think man git reset is really quite good for this - perhaps you do need a bit of a sense of the way git works for them to really sink in though. In particular, if you take the time to carefully read them, those tables detailing states of files in index and work tree for all the various options and cases are very very helpful. (But yes, they're very dense - they're conveying an awful lot of the above information in a very concise form.)

Strange notation

The "strange notation" (HEAD^ and HEAD~1) you mention is simply a shorthand for specifying commits, without having to use a hash name like 3ebe3f6. It's fully documented in the "specifying revisions" section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things:

  • HEAD~ is short for HEAD~1 and means the commit's first parent. HEAD~2 means the commit's first parent's first parent. Think of HEAD~n as "n commits before HEAD" or "the nth generation ancestor of HEAD".
  • HEAD^ (or HEAD^1) also means the commit's first parent. HEAD^2 means the commit's second parent. Remember, a normal merge commit has two parents - the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).
  • The ^ and ~ operators can be strung together, as in HEAD~3^2, the second parent of the third-generation ancestor of HEAD, HEAD^^2, the second parent of the first parent of HEAD, or even HEAD^^^, which is equivalent to HEAD~3.

caret and tilde

How to SELECT a dropdown list item by value programmatically

I prefer

if(ddl.Items.FindByValue(string) != null)
{
    ddl.Items.FindByValue(string).Selected = true;
}

Replace ddl with the dropdownlist ID and string with your string variable name or value.

Problem in running .net framework 4.0 website on iis 7.0

  1. Go to the IIS Manager.
  2. open the server name like (PC-Name)\.
  3. then double click on the ISAPI and CGI Restriction.
  4. then select ASP.NET v4.0.30319(32-bit) Restriction allowed.

Converting int to bytes in Python 3

If the question is how to convert an integer itself (not its string equivalent) into bytes, I think the robust answer is:

>>> i = 5
>>> i.to_bytes(2, 'big')
b'\x00\x05'
>>> int.from_bytes(i.to_bytes(2, 'big'), byteorder='big')
5

More information on these methods here:

  1. https://docs.python.org/3.8/library/stdtypes.html#int.to_bytes
  2. https://docs.python.org/3.8/library/stdtypes.html#int.from_bytes

SQL Query - Change date format in query to DD/MM/YYYY

SELECT CONVERT(varchar(11),Getdate(),105)

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

Need to install urllib2 for Python 3.5.1

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can't, and you don't need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

How to remove all line breaks from a string

Try the following code. It works on all platforms.

var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';

break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'

How to create dynamic href in react render function?

You can use ES6 backtick syntax too

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Early exit from function?

I dislike answering things that aren't a real solution...

...but when I encountered this same problem, I made below workaround:

function doThis() {
  var err=0
  if (cond1) { alert('ret1'); err=1; }
  if (cond2) { alert('ret2'); err=1; }
  if (cond3) { alert('ret3'); err=1; }
  if (err < 1) {
    // do the rest (or have it skipped)
  }
}

Hope it can be useful for anyone.

In Python, how do I index a list with another list?

My problem: Find indexes of list.

L = makelist() # Returns a list of different objects
La = np.array(L, dtype = object) # add dtype!
for c in chunks:
    L_ = La[c] # Since La is array, this works.

Calculating the area under a curve given a set of coordinates, without knowing the function

You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.

Python script that calculates Simpsons rule:

def integrate(y_vals, h):
    i = 1
    total = y_vals[0] + y_vals[-1]
    for y in y_vals[1:-1]:
        if i % 2 == 0:
            total += 2 * y
        else:
            total += 4 * y
        i += 1
    return total * (h / 3.0)

h is the offset (or gap) between y values, and y_vals is an array of well, y values.

Example (In same file as above function):

y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)

adb remount permission denied, but able to access super user in shell -- android

you can use:

adb shell su -c "your command here"

only rooted devices with su works.

How to crop an image using PIL?

An easier way to do this is using crop from ImageOps. You can feed the number of pixels you want to crop from each side.

from PIL import ImageOps

border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

None of the above worked.

  • The "Unblock" option is not present in the explorer properties.
  • Recreating file, adding folder (and resx file) to Tools->Options->Trust Settings does not work.

The solution was to copy the project locally (from the network drive).

invalid command code ., despite escaping periods, using sed

Probably your new domain contain / ? If so, try using separator other than / in sed, e.g. #, , etc.

find ./ -type f -exec sed -i 's#192.168.20.1#new.domain.com#' {} \;

It would also be good to enclose s/// in single quote rather than double quote to avoid variable substitution or any other unexpected behaviour

ValueError: invalid literal for int () with base 10

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read.

Something like this should work:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here

Determine a string's encoding in C#

My solution is to use built-in stuffs with some fallbacks.

I picked the strategy from an answer to another similar question on stackoverflow but I can't find it now.

It checks the BOM first using the built-in logic in StreamReader, if there's BOM, the encoding will be something other than Encoding.Default, and we should trust that result.

If not, it checks whether the bytes sequence is valid UTF-8 sequence. if it is, it will guess UTF-8 as the encoding, and if not, again, the default ASCII encoding will be the result.

static Encoding getEncoding(string path) {
    var stream = new FileStream(path, FileMode.Open);
    var reader = new StreamReader(stream, Encoding.Default, true);
    reader.Read();

    if (reader.CurrentEncoding != Encoding.Default) {
        reader.Close();
        return reader.CurrentEncoding;
    }

    stream.Position = 0;

    reader = new StreamReader(stream, new UTF8Encoding(false, true));
    try {
        reader.ReadToEnd();
        reader.Close();
        return Encoding.UTF8;
    }
    catch (Exception) {
        reader.Close();
        return Encoding.Default;
    }
}

Where does Anaconda Python install on Windows?

You can search for "Anaconda prompt" in installed programs and run it.
When it opens, it shows the directory anaconda is working from.
enter image description here

As you can see c:\programdata\anaconda2 is my installed directory.
*side note: programdata folder is hidden in windows so you'll have to enter its path in the folder explorer to access it.

Error: the entity type requires a primary key

This worked for me:

using System.ComponentModel.DataAnnotations;

[Key]
public int ID { get; set; }

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

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

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

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

Creating a JSON array in C#

new {var_data[counter] =new [] { 
                new{  "S NO":  "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
        }
    };

What's the difference between faking, mocking, and stubbing?

I am surprised that this question has been around for so long and nobody has as yet provided an answer based on Roy Osherove's "The Art of Unit Testing".

In "3.1 Introducing stubs" defines a stub as:

A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.

And defines the difference between stubs and mocks as:

The main thing to remember about mocks versus stubs is that mocks are just like stubs, but you assert against the mock object, whereas you do not assert against a stub.

Fake is just the name used for both stubs and mocks. For example when you don't care about the distinction between stubs and mocks.

The way Osherove's distinguishes between stubs and mocks, means that any class used as a fake for testing can be both a stub or a mock. Which it is for a specific test depends entirely on how you write the checks in your test.

  • When your test checks values in the class under test, or actually anywhere but the fake, the fake was used as a stub. It just provided values for the class under test to use, either directly through values returned by calls on it or indirectly through causing side effects (in some state) as a result of calls on it.
  • When your test checks values of the fake, it was used as a mock.

Example of a test where class FakeX is used as a stub:

const pleaseReturn5 = 5;
var fake = new FakeX(pleaseReturn5);
var cut = new ClassUnderTest(fake);

cut.SquareIt;

Assert.AreEqual(25, cut.SomeProperty);

The fake instance is used as a stub because the Assert doesn't use fake at all.

Example of a test where test class X is used as a mock:

const pleaseReturn5 = 5;
var fake = new FakeX(pleaseReturn5);
var cut = new ClassUnderTest(fake);

cut.SquareIt;

Assert.AreEqual(25, fake.SomeProperty);

In this case the Assert checks a value on fake, making that fake a mock.

Now, of course these examples are highly contrived, but I see great merit in this distinction. It makes you aware of how you are testing your stuff and where the dependencies of your test are.

I agree with Osherove's that

from a pure maintainability perspective, in my tests using mocks creates more trouble than not using them. That has been my experience, but I’m always learning something new.

Asserting against the fake is something you really want to avoid as it makes your tests highly dependent upon the implementation of a class that isn't the one under test at all. Which means that the tests for class ActualClassUnderTest can start breaking because the implementation for ClassUsedAsMock changed. And that sends up a foul smell to me. Tests for ActualClassUnderTest should preferably only break when ActualClassUnderTest is changed.

I realize that writing asserts against the fake is a common practice, especially when you are a mockist type of TDD subscriber. I guess I am firmly with Martin Fowler in the classicist camp (See Martin Fowler's "Mocks aren't Stubs") and like Osherove avoid interaction testing (which can only be done by asserting against the fake) as much as possible.

For fun reading on why you should avoid mocks as defined here, google for "fowler mockist classicist". You'll find a plethora of opinions.

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

Example of waitpid() in use?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(2);
        exit(EXIT_SUCCESS);
    }

//Comment from here to...
    //Parent waits process pid (child)
    waitpid(pid, &status, 0);
    //Option is 0 since I check it later

    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
//To Here and see the difference
    printf("Parent: %d\n", getpid());

    return 0;
}

Separators for Navigation

Add the separator to the li background and make sure the link doesn't expand to cover the separator, which means the separator won't be click-able.

Group by month and year in MySQL

You are grouping by month only, you have to add YEAR() to the group by

Nullable types: better way to check for null or zero in c#

class Item{  
 bool IsNullOrZero{ get{return ((this.Rate ?? 0) == 0);}}
}

How to append elements into a dictionary in Swift?

There is no function to append the data in dictionary. You just assign the value against new key in existing dictionary. it will automatically add value to the dictionary.

var param  = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)

The output will be like

["Name":"Aloha","user" : "Aloha 2","questions" : ""Are you mine"?"]

How do I declare an array variable in VBA?

The Array index only accepts a long value.

You declared iCounter as an integer. You should declare it as a long.

Select rows of a matrix that meet a condition

If your matrix is called m, just use :

R> m[m$three == 11, ]

Oracle: Call stored procedure inside the package

To those that are incline to use GUI:

Click Right mouse button on procecdure name then select Test

enter image description here

Then in new window you will see script generated just add the parameters and click on Start Debugger or F9

enter image description here

Hope this saves you some time.

How does RewriteBase work in .htaccess

This command can explicitly set the base URL for your rewrites. If you wish to start in the root of your domain, you would include the following line before your RewriteRule:

RewriteBase /

How to create own dynamic type or dynamic object in C#?

 var data = new { studentId = 1, StudentName = "abc" };  

Or value is present

  var data = new { studentId, StudentName };

How do I cancel a build that is in progress in Visual Studio?

You can hit Ctrl+Break on the keyboard to cancel/stop a build that is currently in progress.

Defining a percentage width for a LinearLayout?

i know another solution, that work with weight:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent" 
              android:weightSum="10" 
              android:gravity="center_horizontal">

    <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" 
            android:layout_weight="7">
    </LinearLayout>
</LinearLayout>

What is a Maven artifact?

In general software terms, an "artifact" is something produced by the software development process, whether it be software related documentation or an executable file.

In Maven terminology, the artifact is the resulting output of the maven build, generally a jar or war or other executable file. Artifacts in maven are identified by a coordinate system of groupId, artifactId, and version. Maven uses the groupId, artifactId, and version to identify dependencies (usually other jar files) needed to build and run your code.

Reading CSV files using C#

To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser or the string.Split method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.

I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.

I deserialize my CSV file with the following method:

public static IEnumerable<T> ReadCsvFileTextFieldParser<T>(string fileFullPath, string delimiter = ";") where T : new()
{
    if (!File.Exists(fileFullPath))
    {
        return null;
    }

    var list = new List<T>();
    var csvFields = GetAllFieldOfClass<T>();
    var fieldDict = new Dictionary<int, MemberInfo>();

    using (TextFieldParser parser = new TextFieldParser(fileFullPath))
    {
        parser.SetDelimiters(delimiter);

        bool headerParsed = false;

        while (!parser.EndOfData)
        {
            //Processing row
            string[] rowFields = parser.ReadFields();
            if (!headerParsed)
            {
                for (int i = 0; i < rowFields.Length; i++)
                {
                    // First row shall be the header!
                    var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
                    if (csvField != null)
                    {
                        fieldDict.Add(i, csvField);
                    }
                }
                headerParsed = true;
            }
            else
            {
                T newObj = new T();
                for (int i = 0; i < rowFields.Length; i++)
                {
                    var csvFied = fieldDict[i];
                    var record = rowFields[i];

                    if (csvFied is FieldInfo)
                    {
                        ((FieldInfo)csvFied).SetValue(newObj, record);
                    }
                    else if (csvFied is PropertyInfo)
                    {
                        var pi = (PropertyInfo)csvFied;
                        pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
                    }
                    else
                    {
                        throw new Exception("Unhandled case.");
                    }
                }
                if (newObj != null)
                {
                    list.Add(newObj);
                }
            }
        }
    }
    return list;
}

public static IEnumerable<MemberInfo> GetAllFieldOfClass<T>()
{
    return
        from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
        where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
        let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
        orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
        select mi;            
}

Installing Git on Eclipse

It's Very Easy To Install By Following Below Steps In Eclipse JUNO version

Help-->Eclipse Marketplace-->Find: beside Textbox u can type "Egit"-->select Egit-git team provider intall button-->follow next steps and finally click finish

How to reload or re-render the entire page using AngularJS

Well maybe you forgot to add "$route" when declaring the dependencies of your Controller:

app.controller('NameCtrl', ['$scope','$route', function($scope,$route) {   
   // $route.reload(); Then this should work fine.
}]);

How do I trim whitespace from a string?

Well seeing this thread as a beginner got my head spinning. Hence came up with a simple shortcut.

Though str.strip() works to remove leading & trailing spaces it does nothing for spaces between characters.

words=input("Enter the word to test")
# If I have a user enter discontinous threads it becomes a problem
# input = "   he llo, ho w are y ou  "
n=words.strip()
print(n)
# output "he llo, ho w are y ou" - only leading & trailing spaces are removed 

Instead use str.replace() to make more sense plus less error & more to the point. The following code can generalize the use of str.replace()

def whitespace(words):
    r=words.replace(' ','') # removes all whitespace
    n=r.replace(',','|') # other uses of replace
    return n
def run():
    words=input("Enter the word to test") # take user input
    m=whitespace(words) #encase the def in run() to imporve usability on various functions
    o=m.count('f') # for testing
    return m,o
print(run())
output- ('hello|howareyou', 0)

Can be helpful while inheriting the same in diff. functions.

How do I get the different parts of a Flask request's url?

you should try:

request.url 

It suppose to work always, even on localhost (just did it).

When to use setAttribute vs .attribute= in JavaScript?

These answers aren't really addressing the large confusion with between properties and attributes. Also, depending on the Javascript prototype, sometimes you can use a an element's property to access an attributes and sometimes you can't.

First, you have to remember that an HTMLElement is a Javascript object. Like all objects, they have properties. Sure, you can create a property called nearly anything you want inside HTMLElement, but it doesn't have to do anything with the DOM (what's on the page). The dot notation (.) is for properties. Now, there some special properties that are mapped to attributes, and at the time or writing there are only 4 that are guaranteed (more on that later).

All HTMLElements include a property called attributes. HTMLElement.attributes is a live NamedNodeMap Object that relates to the elements in the DOM. "Live" means that when the node changes in the DOM, they change on the JavaScript side, and vice versa. DOM attributes, in this case, are the nodes in question. A Node has a .nodeValue property that you can change. NamedNodeMap objects have a function called setNamedItem where you can change the entire node. You can also directly access the node by the key. For example, you can say .attributes["dir"] which is the same as .attributes.getNamedItem('dir'); (Side note, NamedNodeMap is case-insensitive, so you can also pass 'DIR');

There's a similar function directly in HTMLElement where you can just call setAttribute which will automatically create a node if it doesn't exist and set the nodeValue. There are also some attributes you can access directly as properties in HTMLElement via special properties, such as dir. Here's a rough mapping of what it looks like:

HTMLElement {
  attributes: {
    setNamedItem: function(attr, newAttr) { 
      this[attr] = newAttr;
    },    
    getNamedItem: function(attr) {
      return this[attr];
    },
    myAttribute1: {
      nodeName: 'myAttribute1',
      nodeValue: 'myNodeValue1'
    },
    myAttribute2: {
      nodeName: 'myAttribute2',
      nodeValue: 'myNodeValue2'
    },
  }
  setAttribute: function(attr, value) { 
    let item = this.attributes.getNamedItem(attr);
    if (!item) {
      item = document.createAttribute(attr);
      this.attributes.setNamedItem(attr, item);
    }
    item.nodeValue = value;
  },
  getAttribute: function(attr) { 
    return this.attributes[attr] && this.attributes[attr].nodeValue;
  },
  dir: // Special map to attributes.dir.nodeValue || ''
  id:  // Special map to attributes.id.nodeValue || ''
  className: // Special map to attributes.class.nodeValue || '' 
  lang: // Special map to attributes.lang.nodeValue || ''

}

So you can change the dir attributes 6 ways:

  // 1. Replace the node with setNamedItem
  const newAttribute = document.createAttribute('dir');
  newAttribute.nodeValue = 'rtl';
  element.attributes.setNamedItem(newAttribute);

  // 2. Replace the node by property name;
  const newAttribute2 = document.createAttribute('dir');
  newAttribute2.nodeValue = 'rtl';
  element.attributes['dir'] = newAttribute2;
  // OR
  element.attributes.dir = newAttribute2;

  // 3. Access node with getNamedItem and update nodeValue
  // Attribute must already exist!!!
  element.attributes.getNamedItem('dir').nodeValue = 'rtl';

  // 4. Access node by property update nodeValue
  // Attribute must already exist!!!
  element.attributes['dir'].nodeValue = 'rtl';
  // OR
  element.attributes.dir.nodeValue = 'rtl';

  // 5. use setAttribute()  
  element.setAttribute('dir', 'rtl');
  
  // 6. use the UNIQUELY SPECIAL dir property
  element["dir"] = 'rtl';
  element.dir = 'rtl';

You can update all properties with methods #1-5, but only dir, id, lang, and className with method #6.

Extensions of HTMLElement

HTMLElement has those 4 special properties. Some elements are extended classes of HTMLElement have even more mapped properties. For example, HTMLAnchorElement has HTMLAnchorElement.href, HTMLAnchorElement.rel, and HTMLAnchorElement.target. But, beware, if you set those properties on elements that do not have those special properties (like on a HTMLTableElement) then the attributes aren't changed and they are just, normal custom properties. To better understand, here's an example of its inheritance:

HTMLAnchorElement extends HTMLElement {
  // inherits all of HTMLElement
  href:    // Special map to attributes.href.nodeValue || ''
  target:  // Special map to attributes.target.nodeValue || ''
  rel:     // Special map to attributes.ref.nodeValue || '' 
}

Custom Properties

Now the big warning: Like all Javascript objects, you can add custom properties. But, those won't change anything on the DOM. You can do:

  const newElement = document.createElement('div');
  // THIS WILL NOT CHANGE THE ATTRIBUTE
  newElement.display = 'block';

But that's the same as

  newElement.myCustomDisplayAttribute = 'block';

This means that adding a custom property will not be linked to .attributes[attr].nodeValue.

Performance

I've built a jsperf test case to show the difference: https://jsperf.com/set-attribute-comparison. Basically, In order:

  1. Custom properties because they don't affect the DOM and are not attributes.
  2. Special mappings provided by the browser (dir, id, className).
  3. If attributes already exists, element.attributes.ATTRIBUTENAME.nodeValue =
  4. setAttribute();
  5. If attributes already exists, element.attributes.getNamedItem(ATTRIBUTENAME).nodeValue = newValue
  6. element.attributes.ATTRIBUTENAME = newNode
  7. element.attributes.setNamedItem(ATTRIBUTENAME) = newNode

Conclusion (TL;DR)

  • Use the special property mappings from HTMLElement: element.dir, element.id, element.className, or element.lang.

  • If you are 100% sure the element is an extended HTMLElement with a special property, use that special mapping. (You can check with if (element instanceof HTMLAnchorElement)).

  • If you are 100% sure the attribute already exists, use element.attributes.ATTRIBUTENAME.nodeValue = newValue.

  • If not, use setAttribute().

Force GUI update from UI Thread

At first I wondered why the OP hadn't already marked one of the responses as the answer, but after trying it myself and still have it not work, I dug a little deeper and found there's much more to this issue then I'd first supposed.

A better understanding can be gained by reading from a similar question: Why won't control update/refresh mid-process

Lastly, for the record, I was able to get my label to update by doing the following:

private void SetStatus(string status) 
{
    lblStatus.Text = status;
    lblStatus.Invalidate();
    lblStatus.Update();
    lblStatus.Refresh();
    Application.DoEvents();
}

Though from what I understand this is far from an elegant and correct approach to doing it. It's a hack that may or may not work depending upon how busy the thread is.

Is there a limit on number of tcp/ip connections between machines on linux?

The quick answer is 2^16 TCP ports, 64K.

The issues with system imposed limits is a configuration issue, already touched upon in previous comments.

The internal implications to TCP is not so clear (to me). Each port requires memory for it's instantiation, goes onto a list and needs network buffers for data in transit.

Given 64K TCP sessions the overhead for instances of the ports might be an issue on a 32-bit kernel, but not a 64-bit kernel (correction here gladly accepted). The lookup process with 64K sessions can slow things a bit and every packet hits the timer queues, which can also be problematic. Storage for in transit data can theoretically swell to the window size times ports (maybe 8 GByte).

The issue with connection speed (mentioned above) is probably what you are seeing. TCP generally takes time to do things. However, it is not required. A TCP connect, transact and disconnect can be done very efficiently (check to see how the TCP sessions are created and closed).

There are systems that pass tens of gigabits per second, so the packet level scaling should be OK.

There are machines with plenty of physical memory, so that looks OK.

The performance of the system, if carefully configured should be OK.

The server side of things should scale in a similar fashion.

I would be concerned about things like memory bandwidth.

Consider an experiment where you login to the local host 10,000 times. Then type a character. The entire stack through user space would be engaged on each character. The active footprint would likely exceed the data cache size. Running through lots of memory can stress the VM system. The cost of context switches could approach a second!

This is discussed in a variety of other threads: https://serverfault.com/questions/69524/im-designing-a-system-to-handle-10000-tcp-connections-per-second-what-problems

How to determine one year from now in Javascript

Use this:

var startDate = new Date();
    startDate.setFullYear(startDate.getFullYear() - 1);

Add common prefix to all cells in Excel

  1. Enter the function of = CONCATENATE("X",A1) in one cell other than A say D
  2. Click the Cell D1, and drag the fill handle across the range that you want to fill.All the cells should have been added the specific prefix text.

You can see the changes made to the repective cells.

How can I format a String number to have commas and round?

I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)

It supports:

  • Comma Formatting E.g. 1234567 becomes 1,234,567.
  • Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
  • Precision of 0 through 15.
  • Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
  • Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).

The code can be found here. You call it like this:

public static void main(String[])
{
   int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
   String formatted = ValueFormat.format(1234567, settings);
}

I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.

How do I specify the platform for MSBuild?

In Visual Studio 2019, version 16.8.4, you can just add

<Prefer32Bit>false</Prefer32Bit>

Failed to locate the winutils binary in the hadoop binary path

I used "hbase-1.3.0" and "hadoop-2.7.3" versions. Setting HADOOP_HOME environment variable and copying 'winutils.exe' file under HADOOP_HOME/bin folder solves the problem on a windows os. Attention to set HADOOP_HOME environment to the installation folder of hadoop(/bin folder is not necessary for these versions). Additionally I preferred using cross platform tool cygwin to settle linux os functionality (as possible as it can) because Hbase team recommend linux/unix env.

Javascript - Get Image height

I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache.

Finally I found a solution to get the image height and width even if the image does not exist in the browser cache:

<script type="text/javascript">

  var imgHeight;
  var imgWidth;

  function findHHandWW() {
    imgHeight = this.height;
    imgWidth = this.width;
    return true;
  }

  function showImage(imgPath) {
    var myImage = new Image();
    myImage.name = imgPath;
    myImage.onload = findHHandWW;
    myImage.src = imgPath;
  }
</script>

Thanks,

Binod Suman

http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html

What does !important mean in CSS?

The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.

So, if you have the following:

.class {
   color: red !important;
}
.outerClass .class {
   color: blue;
}

the rule with the important will be the one applied (not counting specificity)

I believe !important appeared in CSS1 so every browser supports it (IE4 to IE6 with a partial implementation, IE7+ full)

Also, it's something that you don't want to use pretty often, because if you're working with other people you can override other properties.

Add attribute 'checked' on click jquery

$( this ).attr( 'checked', 'checked' )

just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />

Edit:

Based on comments, a more appropriate manipulation would be:

$( this ).attr( 'checked', true )

And a straight javascript method, more appropriate and efficient:

this.checked = true;

Thanks @Andy E for that.

Compare two files line by line and generate the difference in another file

The Unix utility diff is meant for exactly this purpose.

$ diff -u file1 file2 > file3

See the manual and the Internet for options, different output formats, etc.

JavaScript math, round to two decimal places

To get the result with two decimals, you can do like this :

var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;

The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.

Call Javascript function from URL/address bar

/test.html#alert('heello')

test.html
<button onClick="eval(document.location.hash.substring(1))">do it</button>

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

iOS 7 status bar overlapping UI

Place this code snippet in your MainViewController.m file in the phonegap project.

- (void)viewDidLayoutSubviews{

    if ([self respondsToSelector:@selector(topLayoutGuide)]) // iOS 7 or above
    {
        CGFloat top = self.topLayoutGuide.length;
        if(self.webView.frame.origin.y == 0){
            // We only want to do this once, or 
            // if the view has somehow been "restored" by other    code.
            self.webView.frame = CGRectMake(self.webView.frame.origin.x,
                                           self.webView.frame.origin.y + top,
                                           self.webView.frame.size.width,
                                           self.webView.frame.size.height-top);
        } 
    } 
}

Difference between View and table in sql

SQL Views:

View is a virtual table based on the result-set of an SQL statement and that is Stored in the database with some name.

SQL Table:

SQL table is database instance consists of fields (columns), and rows.

Check following post, author listed around seven differences between views and table

https://codechef4u.com/post/2015/09/03/sql-views-vs-tables

Angular2 set value for formGroup

For set value when your control is FormGroup can use this example

this.clientForm.controls['location'].setValue({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude
    });

Your password does not satisfy the current policy requirements

I had the same Problem and the Answer is just Right in front of you, remember when you ran the script while installing mysql like

sudo mysql_secure_installation

there somewhere you chose which password type would you like to chose

There are three levels of password validation policy:

LOW Length >= 8 MEDIUM Length >= 8, numeric, mixed case, and special characters STRONG Length >= 8, numeric, mixed case, special characters and dictionary file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:

you have to give a password to same policy

here are some sample examples for your passwords:
for type 0: abcdabcd
for type 1: abcd1234
for type 2: ancd@1234

Does my application "contain encryption"?

Short answer: Yes, but you don't have to do anything

I was searching the web for this for some hours. Actually it is pretty easy and you can verify this in itunes connect:

1. All you have to do

If your app uses only HTTPS or uses encryption only for authentication, tokens, etc., there is nothing you have to do, just include

<key>ITSAppUsesNonExemptEncryption</key><false/>

in your Info.plist and you are done.

2. Verification

You can verify this in itunes connect.

  • select your app
  • chose features
  • chose encryption
  • click "+"
  • follow the dialog
  • for https or authentication the answer is yes and yes

In any case you should of course read yourself carefully through the dialog.


A very helpful article can be found here:

https://www.cocoanetics.com/2017/02/itunes-connect-encryption-info/

Converting a double to an int in Javascript without rounding

Use parseInt().

var num = 2.9
console.log(parseInt(num, 10)); // 2

You can also use |.

var num = 2.9
console.log(num | 0); // 2

How to remove all callbacks from a Handler?

As josh527 said, handler.removeCallbacksAndMessages(null); can work.
But why?
If you have a look at the source code, you can understand it more clearly. There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):

  1. remove by callback (and token)
  2. remove by message.what (and token)
  3. remove by token

Handler.java (leave some overload method)

/**
 * Remove any pending posts of Runnable <var>r</var> with Object
 * <var>token</var> that are in the message queue.  If <var>token</var> is null,
 * all callbacks will be removed.
 */
public final void removeCallbacks(Runnable r, Object token)
{
    mQueue.removeMessages(this, r, token);
}

/**
 * Remove any pending posts of messages with code 'what' and whose obj is
 * 'object' that are in the message queue.  If <var>object</var> is null,
 * all messages will be removed.
 */
public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

/**
 * Remove any pending posts of callbacks and sent messages whose
 * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
 * all callbacks and messages will be removed.
 */
public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

MessageQueue.java do the real work:

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeMessages(Handler h, Runnable r, Object object) {
    if (h == null || r == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.callback == r
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.callback == r
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h
                && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

Set cookies for cross origin requests

What you need to do

To allow receiving & sending cookies by a CORS request successfully, do the following.

Back-end (server): Set the HTTP header Access-Control-Allow-Credentials value to true. Also, make sure the HTTP headers Access-Control-Allow-Origin and Access-Control-Allow-Headers are set and not with a wildcard *.

Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None and Secure. See MDN documentation

For more info on setting CORS in express js read the docs here

Front-end (client): Set the XMLHttpRequest.withCredentials flag to true, this can be achieved in different ways depending on the request-response library used:

Or

Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.

If you for whatever reason don't avoid it. The solution is above.

It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost (without port) is not a problem. Many thanks to Erwin for this tip!

Filter object properties by key in ES6

You can now make it shorter and simpler by using the Object.fromEntries method (check browser support):

const raw = { item1: { prop:'1' }, item2: { prop:'2' }, item3: { prop:'3' } };

const allowed = ['item1', 'item3'];

const filtered = Object.fromEntries(
   Object.entries(raw).filter(
      ([key, val])=>allowed.includes(key)
   )
);

read more about: Object.fromEntries

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

Display string as html in asp.net mvc view

I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field. Example: input field: "The quick brown fox" Displayed value: "The"

The resolution was to put the variable in quotes in the value statement as follows:

<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
       onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit">

Determine the process pid listening on a certain port

Short version which you can pass to kill command:

lsof -i:80 -t

Merging two images in C#/.NET

After all this, I found a new easier method try this ..

It can join multiple photos together:

public static System.Drawing.Bitmap CombineBitmap(string[] files)
{
    //read all images into memory
    List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>();
    System.Drawing.Bitmap finalImage = null;

    try
    {
        int width = 0;
        int height = 0;

        foreach (string image in files)
        {
            //create a Bitmap from the file and add it to the list
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);

            //update the size of the final bitmap
            width += bitmap.Width;
            height = bitmap.Height > height ? bitmap.Height : height;

            images.Add(bitmap);
        }

        //create a bitmap to hold the combined image
        finalImage = new System.Drawing.Bitmap(width, height);

        //get a graphics object from the image so we can draw on it
        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
        {
            //set background color
            g.Clear(System.Drawing.Color.Black);

            //go through each image and draw it on the final image
            int offset = 0;
            foreach (System.Drawing.Bitmap image in images)
            {
                g.DrawImage(image,
                  new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
                offset += image.Width;
            }
        }

        return finalImage;
    }
    catch (Exception ex)
    {
        if (finalImage != null)
            finalImage.Dispose();

        throw ex;
    }
    finally
    {
        //clean up memory
        foreach (System.Drawing.Bitmap image in images)
        {
            image.Dispose();
        }
    }
}

Calculating the sum of two variables in a batch script

here is mine

echo Math+ 
ECHO First num:
 SET /P a= 
ECHO Second num:
 SET /P b=
 set /a s=%a%+%b% 
echo Result: %s%

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

How can I remove the extension of a filename in a shell script?

As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/in.path.name). A possible solution is:

a=this.path/with.dots/in.path.name/filename.tar.gz
echo $(dirname $a)/$(basename $a | cut -d. -f1)

Reading specific XML elements from XML file

Alternatively, you can use XPath query via XPathSelectElements method:

var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");

Search all tables, all columns for a specific value SQL Server

I published one here: FullParam SQL Blog

/* Reto Egeter, fullparam.wordpress.com */

DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
    )
    IF @TableName IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''' + @TableName + ''', 2)
                AND TABLE_NAME  = PARSENAME(''' + @TableName + ''', 1)
                AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
                AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END  + ',COLUMN_NAME)'
        INSERT INTO @ColumnNameTable
        EXEC (@sql)
        WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
        BEGIN
            PRINT @ColumnName
            SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
            SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),''' 
            WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
            ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + ''' 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
            INSERT INTO #Results
            EXEC(@sql)
            IF @@ROWCOUNT > 0 IF @FullRowResult = 1 
            BEGIN
                SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
                    ' FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
                EXEC(@sql)
            END
            DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
        END 
    END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType

remove item from stored array in angular 2

That work for me

 this.array.pop(index);

 for example index = 3 

 this.array.pop(3);

'const int' vs. 'int const' as function parameters in C++ and C

I think in this case they are the same, but here is an example where order matters:

const int* cantChangeTheData;
int* const cantChangeTheAddress;

Where are the python modules stored?

On python command line, first import that module for which you need location.

import module_name

Then type:

print(module_name.__file__)

For example to find out "pygal" location:

import pygal
print(pygal.__file__)

Output:

/anaconda3/lib/python3.7/site-packages/pygal/__init__.py

Extracting specific columns from a data frame

There are two obvious choices: Joshua Ulrich's df[,c("A","B","E")] or

df[,c(1,2,5)]

as in

> df <- data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,7),E=c(8,8),F=c(9,9)) 
> df
  A B C D E F
1 1 3 5 7 8 9
2 2 4 6 7 8 9
> df[,c(1,2,5)]
  A B E
1 1 3 8
2 2 4 8
> df[,c("A","B","E")]
  A B E
1 1 3 8
2 2 4 8

How to copy file from host to container using Dockerfile

For those who get this (terribly unclear) error:

COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory

There could be loads of reasons, including:

  • For docker-compose users, remember that the docker-compose.yml context overwrites the context of the Dockerfile. Your COPY statements now need to navigate a path relative to what is defined in docker-compose.yml instead of relative to your Dockerfile.
  • Trailing comments or a semicolon on the COPY line: COPY abc.txt /app #This won't work
  • The file is in a directory ignored by .dockerignore or .gitignore files (be wary of wildcards)
  • You made a typo

Sometimes WORKDIR /abc followed by COPY . xyz/ works where COPY /abc xyz/ fails, but it's a bit ugly.

Git on Mac OS X v10.7 (Lion)

There are a couple of points to this answer.

Firstly, you don't need to install Xcode. The Git installer works perfectly well. However, if you want to use Git from within Xcode - it expects to find an installation under /usr/local/bin. If you have your own Git installed elsewhere - I've got a script that fixes this.

Second is to do with the path. My Git path used to be kept under /etc/paths.d/ However, a Mac OS X v10.7 (Lion) install overwrites the contents of this folder and the /etc/paths file as well. That's what happened to me and I got the same error. Recreating the path file fixed the problem.

How to center a Window in Java?

The order of the calls is important:

first -

pack();

second -

setLocationRelativeTo(null);

C++ Compare char array with string

You're not working with strings. You're working with pointers. var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.

So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).

Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.

IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.

The C way of doing this is to use the strcmp function:

strcmp(var1, "dev");

This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)

So to compare for equality you need to do one of these:

if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}

However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:

std::string var1 = getenv("myEnvVar");

if(var1 == "dev")
{
   // do stuff
}

Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.

How to export html table to excel using javascript

I think you can also think of alternative architectures. Sometimes something can be done in another way much more easier. If the producer of HTML file is you, then you can write an HTTP handler to create an Excel document on the server (which is much more easier than in JavaScript) and send a file to the client. If you receive that HTML file from somewhere (like an HTML version of a report), then you still can use a server side language like C# or PHP to create the Excel file still very easily. I mean, you may have other ways too. :)

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.

  • Even worse, while the delete cascade is going on, the tables involved are locked so those tables (and potentially your whole database) is unusable.
  • Still worse, it's hard to get postgres to tell you what it's doing during the delete cascade. If it's taking a long time, which table or tables is making it slow? Perhaps it's somewhere in the pg_stats information? It's hard to tell.

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

How to return a boolean method in java?

try this:

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            return true;
        }

}

if (verifyPwd()==true){
    addNewUser();
}
else {
    // passwords do not match
}

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

Update 24.3.2016

I have found this guide from VP https://knowhow.visual-paradigm.com/technical-support/running-vp-in-android-studio/ created on September 8, 2015.

Good to know - it is possible to integrate VP into Android studio (in my case 1.5.1) now. Do not forget to backup your Android Studio settings (you can find them in Users%userName/.AndroidStudioX.X on Windows) ahead of installation.

I was trying to make it work, but created vp project did not contain any diagrams. Maybe someone else will have more luck.


I was using this manual http://www.visual-paradigm.com/support/documents/vpuserguide/2381/2385/66578_creatingauml.html to make Visual Paradigm working in Android studio, but action in 2. did not invoke dialogue in 3. So I Have asked Visual Paradigm support for help and they replied that Android Studio integration is not supported right now.

Reply from Visual paradigm reply from Apr 17 2015:

Thank you for your inquiry and I'm very sorry that at the moment we only support integrate with the standard IntelliJ IDEA, but not integrate with the Android Studio. We may consider to support it in our future release, and I'll keep you post once there any update on this topics. Feel free to contact me for any questions and wish you have a good day!

This post was deleted, so I will try to make it more clear.

As such I am considering previous answers as misleading and not useful. Therefore I thing that it is important for others to know that, before they lose their time trying to make it working.

How do I select last 5 rows in a table without sorting?

If you do not want to arrange the table in ascending or descending order. Use this.

select * from table limit 5 offset (select count(*) from table) - 5;

Using boolean values in C

First things first. C, i.e. ISO/IEC 9899 has had a boolean type for 19 years now. That is way longer time than the expected length of the C programming career with amateur/academic/professional parts combined when visiting this question. Mine does surpass that by mere perhaps 1-2 years. It means that during the time that an average reader has learnt anything at all about C, C actually has had the boolean data type.

For the datatype, #include <stdbool.h>, and use true, false and bool. Or do not include it, and use _Bool, 1 and 0 instead.


There are various dangerous practices promoted in the other answers to this thread. I will address them:

typedef int bool;
#define true 1
#define false 0

This is no-no, because a casual reader - who did learn C within those 19 years - would expect that bool refers to the actual bool data type and would behave similarly, but it doesn't! For example

double a = ...;
bool b = a;

With C99 bool/ _Bool, b would be set to false iff a was zero, and true otherwise. C11 6.3.1.2p1

  1. When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1. 59)

Footnotes

59) NaNs do not compare equal to 0 and thus convert to 1.

With the typedef in place, the double would be coerced to an int - if the value of the double isn't in the range for int, the behaviour is undefined.

Naturally the same applies to if true and false were declared in an enum.

What is even more dangerous is declaring

typedef enum bool {
    false, true
} bool;

because now all values besides 1 and 0 are invalid, and should such a value be assigned to a variable of that type, the behaviour would be wholly undefined.

Therefore iff you cannot use C99 for some inexplicable reason, for boolean variables you should use:

  • type int and values 0 and 1 as-is; and carefully do domain conversions from any other values to these with double negation !!
  • or if you insist you don't remember that 0 is falsy and non-zero truish, at least use upper case so that they don't get confused with the C99 concepts: BOOL, TRUE and FALSE!

Determine which MySQL configuration file is being used

Just in case you are running mac this can be also achieved by:

sudo dtruss mysqld 2>&1 | grep cnf

CSS rule to apply only if element has BOTH classes

div.abc.xyz {
    /* rules go here */
}

... or simply:

.abc.xyz {
    /* rules go here */
}

How to build splash screen in windows forms application?

First you should create a form with or without Border (border-less is preferred for these things)

public class SplashForm : Form
{
    Form _Parent;
    BackgroundWorker worker;
    public SplashForm(Form parent)
    {
         InitializeComponent();
         BackgroundWorker worker = new BackgroundWorker();
         this.worker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.worker _DoWork);
         backgroundWorker1.RunWorkerAsync();
         _Parent = parent;
    }
    private void worker _DoWork(object sender, DoWorkEventArgs e)
    {
         Thread.sleep(500);
         this.hide();
         _Parent.show();
    }     
}

At Main you should use that

   static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new SplashForm());
            }
        }

How to connect to MongoDB in Windows?

Create default db folder.

c:\data\db

and also log folder

c:\data\log\mongo.log

or use following commands in command-prompt

mkdir c:\data\log    
mkdir c:\data\db

How do I mount a remote Linux folder in Windows through SSH?

Apparently the free NetDrive software from Novell can access SFTP file servers.

How to disable HTML links

I think a lot of these are over thinking. Add a class of whatever you want, like disabled_link.
Then make the css have .disabled_link { display: none }
Boom now the user can't see the link so you won't have to worry about them clicking it. If they do something to satisfy the link being clickable, simply remove the class with jQuery:
$("a.disabled_link").removeClass("super_disabled"). Boom done!

Auto start print html page using javascript

Add the following code in your HTML page, and it will show print preview on page load.

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<script type="text/javascript">

$(document).ready(function () {
    window.print();
});

</script>

jQuery append() - return appended elements

// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);

// append to the DOM
$("#myDiv").append($elements);

// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);

How to use _CRT_SECURE_NO_WARNINGS

Visual Studio 2019 with CMake

Add the following to CMakeLists.txt:

add_definitions(-D_CRT_SECURE_NO_WARNINGS)

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Syntax errors is not checked easily in external servers, just runtime errors.

What I do? Just like you, I use

ini_set('display_errors', 'On');
error_reporting(E_ALL);

However, before run I check syntax errors in a PHP file using an online PHP syntax checker.

The best, IMHO is PHP Code Checker

I copy all the source code, paste inside the main box and click the Analyze button.

It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely

How do I check if a cookie exists?

function hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}

Note: The author wanted the function to return false if the cookie is empty i.e. cookie=; this is achieved with the && !!value condition. Remove it if you consider an empty cookie is still an existing cookie…

What are the use cases for selecting CHAR over VARCHAR in SQL?

It's the classic space versus performance tradeoff.

In MS SQL 2005, Varchar (or NVarchar for lanuagues requiring two bytes per character ie Chinese) are variable length. If you add to the row after it has been written to the hard disk it will locate the data in a non-contigious location to the original row and lead to fragmentation of your data files. This will affect performance.

So, if space is not an issue then Char are better for performance but if you want to keep the database size down then varchars are better.

Python Pandas counting and summing specific conditions

You can first make a conditional selection, and sum up the results of the selection using the sum function.

>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()   
a    5
dtype: int64

Having more than one condition:

>> df[(df.a > 1) & (df.a < 3)].sum()
a    2
dtype: int64

How to test if a string contains one of the substrings in a list, in pandas?

One option is just to use the regex | character to try to match each of the substrings in the words in your Series s (still using str.contains).

You can construct the regex by joining the words in searchfor with |:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $ and ^ which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.

You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

The strings with in this new list will match each character literally when used with str.contains.

AngularJS HTTP post to PHP and undefined

You need to deserialize your form data before passing it as the second parameter to .post (). You can achieve this using jQuery's $.param (data) method. Then you will be able to on server side to reference it like $.POST ['email'];

How to remove the arrow from a select element in Firefox

A lot of Discussions Happening here & there but I don't see some proper solution for this problem. Finally Ended up by writing a small Jquery + CSS code for doing this HACK on IE & Firefox.

Calculate Element Width (SELECT Element) using Jquery. Add a Wrapper Around Select Element and Keep overflow hidden for this element. Make sure that Width of this wrapper is appox. 25px less as that of SELECT Element. This could be easily done with Jquery. So Now Our Icon is Gone..! and it is time for adding our image icon on SELECT element...!!! Just add few simple lines for adding background and you are all Done..!! Make sure to use overflow hidden for outer wrapper,

Here is a Sample of Code which was done for Drupal. However could be used for others also by removing few lines of code which is Drupal Specific.

/*
 * Jquery Code for Removing Dropdown Arrow.
 * @by: North Web Studio
 */
(function($) {
  Drupal.behaviors.nwsJS = {
    attach: function(context, settings) {
      $('.form-select').once('nws-arrow', function() {
        $wrap_width = $(this).outerWidth();
        $element_width = $wrap_width + 20;
        $(this).css('width', $element_width);
        $(this).wrap('<div class="nws-select"></div>');
        $(this).parent('.nws-select').css('width', $wrap_width);
      });
    }
  };
})(jQuery);
/*
 * CSS Code for Removing Dropdown Arrow.
 * @by: North Web Studio
 */

.nws-select {
  border: 1px solid #ccc;
  overflow: hidden;
  background: url('../images/icon.png') no-repeat 95% 50%;
}
.nws-select .form-select {
  border: none;
  background: transparent;
}

Solution works on All Browsers IE, Chrome & Firefox No need of Adding fixed Widths Hacks Using CSS. It is all being handled Dynamically using JQuery.!

More Described at:- http://northwebstudio.com/blogs/1/jquery/remove-drop-down-arrow-html-select-element-using-jquery-and-css

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

How an 'if (A && B)' statement is evaluated?

yes, if( (A) && (B) ) will fail on the first clause, if (A) evaluates false.

this applies to any language btw, not just C derivatives. For threaded and parallel processing this is a different story ;)

Parsing JSON using C

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.

Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.

The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).

JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

What is the App_Data folder used for in Visual Studio?

App_Data is essentially a storage point for file-based data stores (as opposed to a SQL server database store for example). Some simple sites make use of it for content stored as XML for example, typically where hosting charges for a DB are expensive.

How to [recursively] Zip a directory in PHP?

Try this link <-- MORE SOURCE CODE HERE

/** Include the Pear Library for Zip */
include ('Archive/Zip.php');

/** Create a Zipping Object...
* Name of zip file to be created..
* You can specify the path too */
$obj = new Archive_Zip('test.zip');
/**
* create a file array of Files to be Added in Zip
*/
$files = array('black.gif',
'blue.gif',
);

/**
* creating zip file..if success do something else do something...
* if Error in file creation ..it is either due to permission problem (Solution: give 777 to that folder)
* Or Corruption of File Problem..
*/

if ($obj->create($files)) {
// echo 'Created successfully!';
} else {
//echo 'Error in file creation';
}

?>; // We'll be outputting a ZIP
header('Content-type: application/zip');

// It will be called test.zip
header('Content-Disposition: attachment; filename="test.zip"');

//read a file and send
readfile('test.zip');
?>;

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

Show a number to two decimal places

round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function.

However, my guess is doing this: number_format($number, 2);

What are good ways to prevent SQL injection?

SQL injection can be a tricky problem but there are ways around it. Your risk is reduced your risk simply by using an ORM like Linq2Entities, Linq2SQL, NHibrenate. However you can have SQL injection problems even with them.

The main thing with SQL injection is user controlled input (as is with XSS). In the most simple example if you have a login form (I hope you never have one that just does this) that takes a username and password.

SELECT * FROM Users WHERE Username = '" + username + "' AND password = '" + password + "'"

If a user were to input the following for the username Admin' -- the SQL Statement would look like this when executing against the database.

SELECT * FROM Users WHERE Username = 'Admin' --' AND password = ''

In this simple case using a paramaterized query (which is what an ORM does) would remove your risk. You also have a the issue of a lesser known SQL injection attack vector and that's with stored procedures. In this case even if you use a paramaterized query or an ORM you would still have a SQL injection problem. Stored procedures can contain execute commands, and those commands themselves may be suceptable to SQL injection attacks.

CREATE PROCEDURE SP_GetLogin @username varchar(100), @password varchar(100) AS
DECLARE @sql nvarchar(4000)
SELECT @sql = ' SELECT * FROM users' +
              ' FROM Product Where username = ''' + @username + ''' AND password = '''+@password+''''

EXECUTE sp_executesql @sql

So this example would have the same SQL injection problem as the previous one even if you use paramaterized queries or an ORM. And although the example seems silly you'd be surprised as to how often something like this is written.

My recommendations would be to use an ORM to immediately reduce your chances of having a SQL injection problem, and then learn to spot code and stored procedures which can have the problem and work to fix them. I don't recommend using ADO.NET (SqlClient, SqlCommand etc...) directly unless you have to, not because it's somehow not safe to use it with parameters but because it's that much easier to get lazy and just start writing a SQL query using strings and just ignoring the parameters. ORMS do a great job of forcing you to use parameters because it's just what they do.

Next Visit the OWASP site on SQL injection https://www.owasp.org/index.php/SQL_Injection and use the SQL injection cheat sheet to make sure you can spot and take out any issues that will arise in your code. https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet finally I would say put in place a good code review between you and other developers at your company where you can review each others code for things like SQL injection and XSS. A lot of times programmers miss this stuff because they're trying to rush out some feature and don't spend too much time on reviewing their code.

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

Seems like you want to move around. Try this:

ActiveSheet.UsedRange.select

results in....

enter image description here

If you want to move that selection 3 rows up then try this

ActiveSheet.UsedRange.offset(-3).select

does this...

enter image description here