Programs & Examples On #Keyfilter

How can I align text in columns using Console.WriteLine?

Just to add to roya's answer. In c# 6.0 you can now use string interpolation:

Console.WriteLine($"{customer[DisplayPos],10}" +
                  $"{salesFigures[DisplayPos],10}" +
                  $"{feePayable[DisplayPos],10}" +
                  $"{seventyPercentValue,10}" +
                  $"{thirtyPercentValue,10}");

This can actually be one line without all the extra dollars, I just think it makes it a bit easier to read like this.

And you could also use a static import on System.Console, allowing you to do this:

using static System.Console;

WriteLine(/* write stuff */);

How to leave space in HTML

Use white-space: pre:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<span style="white-space: pre">    My spaces   </span>_x000D_
<br>_x000D_
<span>     My spaces   </span>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SQLRecoverableException: I/O Exception: Connection reset

I want to produce a complementary answer of nacho-soriano's solution ...

I recently search to solve a problem where a Java written application (a Talend ELT job in fact) want to connect to an Oracle database (11g and over) then randomly fail. OS is both RedHat Enterprise and CentOS. Job run very quily in time (no more than half a minute) and occur very often (approximately one run each 5 minutes).

Some times, during night-time as work-time, during database intensive-work usage as lazy work usage, in just a word randomly, connection fail with this message:

Exception in component tOracleConnection_1
java.sql.SQLRecoverableException: Io exception: Connection reset
        at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:101)
        at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:229)
        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:458)
        at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:411)
        at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:490)
        at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:202)
        at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
        at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:465)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:208)
    and StackTrace follow ...

Problem explanation:

As detailed here

Oracle connection needs some random numbers to assume a good level of security. Linux random number generator produce some numbers bases keyboard and mouse activity (among others) and place them in a stack. You will grant me, on a server, there is not a big amount of such activity. So it can occur that softwares use more random number than generator can produce.

When the pool is empty, reads from /dev/random will block until additional environmental noise is gathered. And Oracle connection fall in timeout (60 seconds by default).

Solution 1 - Specific for one app solution

The solution is to give add two parameters given to the JVM while starting:

-Djava.security.egd=file:/dev/./urandom
-Dsecurerandom.source=file:/dev/./urandom

Note: the '/./' is important, do not drop it !

So the launch command line could be:

java -Djava.security.egd=file:/dev/./urandom -Dsecurerandom.source=file:/dev/./urandom -cp <classpath directives> appMainClass <app options and parameters>

One drawback of this solution is that numbers generated are a little less secure as randomness is impacted. If you don't work in a military or secret related industry this solution can be your.

Solution 2 - General Java JVM solution

As explained here

Both directives given in solution 1 can be put in Java security setting file.

Take a look at $JAVA_HOME/jre/lib/security/java.security

Change the line

securerandom.source=file:/dev/random

to

securerandom.source=file:/dev/urandom

Change is effective immediately for new running applications.

As for solution #1, one drawback of this solution is that numbers generated are a little less secure as randomness is impacted. This time, it's a global JVM impact. As for solution #1, if you don't work in a military or secret related industry this solution can be your.

We ideally should use "file:/dev/./urandom" after Java 5 as previous path will again point to /dev/random.

Reported Bug : https://bugs.openjdk.java.net/browse/JDK-6202721

Solution 3 - Hardware solution

Disclamer: I'm not linked to any of hardware vendor or product ...

If your need is to reach a high quality randomness level, you can replace your Linux random number generator software by a piece of hardware.

Some information are available here.

Regards

Thomas

Sum of values in an array using jQuery

If you want it to be a jquery method, you can do it like this :

$.sum = function(arr) {
    var r = 0;
    $.each(arr, function(i, v) {
        r += +v;
    });
    return r;
}

and call it like this :

var sum = $.sum(["20", "40", "80", "400"]);

How to append strings using sprintf?

For safety (buffer overflow) I recommend to use snprintf()

const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);

int length = 0;
length += snprintf(Buffer+length, MAX_BUF-length, "Hello World");
length += snprintf(Buffer+length, MAX_BUF-length, "Good Morning");
length += snprintf(Buffer+length, MAX_BUF-length, "Good Afternoon");

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date -j -f "%Y-%m-%d %H:%M:%S" "2020-04-07 00:00:00" "+%s"

It will print the dynamic seconds when without %H:%M:%S and 00:00:00.

How to replace all strings to numbers contained in each string in Notepad++?

In Notepad++ to replace, hit Ctrl+H to open the Replace menu.

Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines

value="4"
value="403"
value="200"
value="201"
value="116"
value="15"

using the .*"\d+" pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses ( and ), like that: .*"(\d+)". So now in your replacement you can simply write $1, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)", $1 will return the string value and $2 will return the number.

So by using:

Find: .*"(\d+)"

Replace: $1

It will return you

4
403
200
201
116
15

Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)" would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)

What does enumerate() mean?

The enumerate() function adds a counter to an iterable.

So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.

Demo:

>>> elements = ('foo', 'bar', 'baz')
>>> for elem in elements:
...     print elem
... 
foo
bar
baz
>>> for count, elem in enumerate(elements):
...     print count, elem
... 
0 foo
1 bar
2 baz

By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:

>>> for count, elem in enumerate(elements, 42):
...     print count, elem
... 
42 foo
43 bar
44 baz

If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:

from itertools import count

def enumerate(it, start=0):
    # return an iterator that adds a counter to each element of it
    return zip(count(start), it)

and

def enumerate(it, start=0):
    count = start
    for elem in it:
        yield (count, elem)
        count += 1

The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).

$ is not a function - jQuery error

<script type="text/javascript">
    $("ol li:nth-child(1)").addClass('olli1');
    $("ol li:nth-child(2)").addClass("olli2");
    $("ol li:nth-child(3)").addClass("olli3");
    $("ol li:nth-child(4)").addClass("olli4");
    $("ol li:nth-child(5)").addClass("olli5");
    $("ol li:nth-child(6)").addClass("olli6");
    $("ol li:nth-child(7)").addClass("olli7");
    $("ol li:nth-child(8)").addClass("olli8");
    $("ol li:nth-child(9)").addClass("olli9");
    $("ol li:nth-child(10)").addClass("olli10");
    $("ol li:nth-child(11)").addClass("olli11");
    $("ol li:nth-child(12)").addClass("olli12");
    $("ol li:nth-child(13)").addClass("olli13");
    $("ol li:nth-child(14)").addClass("olli14");
    $("ol li:nth-child(15)").addClass("olli15");
    $("ol li:nth-child(16)").addClass("olli16");
    $("ol li:nth-child(17)").addClass("olli17");
    $("ol li:nth-child(18)").addClass("olli18");
    $("ol li:nth-child(19)").addClass("olli19");
    $("ol li:nth-child(20)").addClass("olli20"); 
</script>

change this to

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
        $("ol li:nth-child(1)").addClass('olli1');
        $("ol li:nth-child(2)").addClass("olli2");
        $("ol li:nth-child(3)").addClass("olli3");
        $("ol li:nth-child(4)").addClass("olli4");
        $("ol li:nth-child(5)").addClass("olli5");
        $("ol li:nth-child(6)").addClass("olli6");
        $("ol li:nth-child(7)").addClass("olli7");
        $("ol li:nth-child(8)").addClass("olli8");
        $("ol li:nth-child(9)").addClass("olli9");
        $("ol li:nth-child(10)").addClass("olli10");
        $("ol li:nth-child(11)").addClass("olli11");
        $("ol li:nth-child(12)").addClass("olli12");
        $("ol li:nth-child(13)").addClass("olli13");
        $("ol li:nth-child(14)").addClass("olli14");
        $("ol li:nth-child(15)").addClass("olli15");
        $("ol li:nth-child(16)").addClass("olli16");
        $("ol li:nth-child(17)").addClass("olli17");
        $("ol li:nth-child(18)").addClass("olli18");
        $("ol li:nth-child(19)").addClass("olli19");
        $("ol li:nth-child(20)").addClass("olli20"); 
     });
    </script>

Show div when radio button selected

$('input[name=test]').click(function () {
    if (this.id == "watch-me") {
        $("#show-me").show('slow');
    } else {
        $("#show-me").hide('slow');
    }
});

http://jsfiddle.net/2SsAk/2/

In jQuery, what's the best way of formatting a number to 2 decimal places?

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

Changing iframe src with Javascript

Here is my updated code. It works fine and it can help you.

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Untitled 1</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script type="text/javascript">
  function go(loc) {
    document.getElementById('calendar').src = loc;
  }
  </script>
</head>

<body>
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>

  <form method="post">
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
  </form>

</body>

</html>

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I had the same error. Resizing the images resolved the issue. However, I used online tools to resize the images because using pillow to resize them did not solve my problem.

How to get all selected values from <select multiple=multiple>?

Update October 2019

The following should work "stand-alone" on all modern browsers without any dependencies or transpilation.

<!-- display a pop-up with the selected values from the <select> element -->

<script>
 const showSelectedOptions = options => alert(
   [...options].filter(o => o.selected).map(o => o.value)
 )
</script>

<select multiple onchange="showSelectedOptions(this.options)">
  <option value='1'>one</option>
  <option value='2'>two</option>
  <option value='3'>three</option>
  <option value='4'>four</option>
</select>

How to mark-up phone numbers?

The tel: scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel: on the iPhone was not an arbitrary decision.

callto:, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.

Me? I'd just start including properly-formed tel: URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .

Example:

_x000D_
_x000D_
<a href="tel:+18475555555">1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

Extracting text OpenCV

@dhanushka's approach showed the most promise but I wanted to play around in Python so went ahead and translated it for fun:

import cv2
import numpy as np
from cv2 import boundingRect, countNonZero, cvtColor, drawContours, findContours, getStructuringElement, imread, morphologyEx, pyrDown, rectangle, threshold

large = imread(image_path)
# downsample and use it for processing
rgb = pyrDown(large)
# apply grayscale
small = cvtColor(rgb, cv2.COLOR_BGR2GRAY)
# morphological gradient
morph_kernel = getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = morphologyEx(small, cv2.MORPH_GRADIENT, morph_kernel)
# binarize
_, bw = threshold(src=grad, thresh=0, maxval=255, type=cv2.THRESH_BINARY+cv2.THRESH_OTSU)
morph_kernel = getStructuringElement(cv2.MORPH_RECT, (9, 1))
# connect horizontally oriented regions
connected = morphologyEx(bw, cv2.MORPH_CLOSE, morph_kernel)
mask = np.zeros(bw.shape, np.uint8)
# find contours
im2, contours, hierarchy = findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# filter contours
for idx in range(0, len(hierarchy[0])):
    rect = x, y, rect_width, rect_height = boundingRect(contours[idx])
    # fill the contour
    mask = drawContours(mask, contours, idx, (255, 255, 2555), cv2.FILLED)
    # ratio of non-zero pixels in the filled region
    r = float(countNonZero(mask)) / (rect_width * rect_height)
    if r > 0.45 and rect_height > 8 and rect_width > 8:
        rgb = rectangle(rgb, (x, y+rect_height), (x+rect_width, y), (0,255,0),3)

Now to display the image:

from PIL import Image
Image.fromarray(rgb).show()

Not the most Pythonic of scripts but I tried to resemble the original C++ code as closely as possible for readers to follow.

It works almost as well as the original. I'll be happy to read suggestions how it could be improved/fixed to resemble the original results fully.

enter image description here

enter image description here

enter image description here

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.

// capture ctrl+c and stop CPU profiler                            
c := make(chan os.Signal, 1)                                       
signal.Notify(c, os.Interrupt)                                     
go func() {                                                        
  for sig := range c {                                             
    log.Printf("captured %v, stopping profiler and exiting..", sig)
    pprof.StopCPUProfile()                                         
    os.Exit(1)                                                     
  }                                                                
}()    

How can I get a value from a map?

How can I get the value from the map, which is passed as a reference to a function?

Well, you can pass it as a reference. The standard reference wrapper that is.

typedef std::map<std::string, std::string> MAP;
// create your map reference type
using map_ref_t = std::reference_wrapper<MAP>;

// use it 
void function(map_ref_t map_r)
{
    // get to the map from inside the
    // std::reference_wrapper
    // see the alternatives behind that link
    MAP & the_map = map_r;
    // take the value from the map
    // by reference
    auto & value_r = the_map["key"];
    // change it, "in place"
    value_r = "new!";
}

And the test.

    void test_ref_to_map() {

    MAP valueMap;
    valueMap["key"] = "value";
    // pass it by reference
    function(valueMap);
    // check that the value has changed
    assert( "new!" == valueMap["key"] );
}

I think this is nice and simple. Enjoy ...

Java Date vs Calendar

Date should be re-developed. Instead of being a long interger, it should hold year, month, date, hour, minute, second, as separate fields. It might be even good to store the calendar and time zone this date is associated with.

In our natural conversation, if setup an appointment at Nov. 1, 2013 1pm NY Time, this is a DateTime. It is NOT a Calendar. So we should be able to converse like this in Java as well.

When Date is stored as a long integer (of mili seconds since Jan 1 1970 or something), calculating its current date depends on the calendar. Different calendars will give different date. This is from the prospective of giving an absolute time (eg 1 trillion seconds after Big Bang). But often we also need a convenient way of conversation, like an object encapsulating year, month etc.

I wonder if there are new advances in Java to reconcile these 2 objectives. Maybe my java knowledge is too old.

Cannot open include file with Visual Studio

I found this post because I was having the same error in Microsoft Visual C++. (Though it seems it's cause was a little different, than the above posted question.)

I had placed the file, I was trying to include, in the same directory, but it still could not be found.

My include looked like this: #include <ftdi.h>

But When I changed it to this: #include "ftdi.h" then it found it.

.autocomplete is not a function Error

My issue ended up being visual studio catching an unhandled exception and preventing the script from running any further. Because I was running in the IDE, it looked like there was an issue when there wasn't. Autocomplete was working just fine. I added a try/catch block and that made the IDE happy.

 $.ajax({
            url: "/MyController/MyAction",
            type: "POST",
            dataType: "json",
            data: { prefix: request.term },
            success: function (data) {
                try {
                    response($.map(data, function (item) {
                        return { label: item.Name, value: item.Name };
                    }))
                } catch (err) { }

            }
        })

How do I change the IntelliJ IDEA default JDK?

Change JDK version to 1.8

  1. Language level File -> project Structure -> Modules -> Sources -> Language level -> 8-Lambdas, type annotations etc. enter image description here
  2. Project SDk File -> project Structure -> Project 1.8 enter image description here

  3. Java compiler File -> Settings -> Build, Executions, Deployment -> Compiler -> Java compiler enter image description here

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

How to make an HTTP request + basic auth in Swift

my solution works as follows:

import UIKit


class LoginViewController: UIViewController, NSURLConnectionDataDelegate {

  @IBOutlet var usernameTextField: UITextField
  @IBOutlet var passwordTextField: UITextField

  @IBAction func login(sender: AnyObject) {
    var url = NSURL(string: "YOUR_URL")
    var request = NSURLRequest(URL: url)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

  }

  func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {

    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)

    }

}

  func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
    // 200? Yeah authentication was successful
  }


  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }  
}

You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.

Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to

  • Add the protocol NSURLConnectionDataDelegate to the class
  • Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge" This is used for adding the credentials to the request
  • Implement the protocols' function "connection:didReceiveResponse" This will check the http response status code

How do you run multiple programs in parallel from a bash script?

If you want to be able to easily run and kill multiple process with ctrl-c, this is my favorite method: spawn multiple background processes in a (…) subshell, and trap SIGINT to execute kill 0, which will kill everything spawned in the subshell group:

(trap 'kill 0' SIGINT; prog1 & prog2 & prog3)

You can have complex process execution structures, and everything will close with a single ctrl-c (just make sure the last process is run in the foreground, i.e., don't include a & after prog1.3):

(trap 'kill 0' SIGINT; prog1.1 && prog1.2 & (prog2.1 | prog2.2 || prog2.3) & prog1.3)

How to Parse a JSON Object In Android

In your JSON format, it do not have starting JSON object

Like :

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}

Above Json starts with info as JSON object. So while executing :

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

Now, we can access result field :

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

I think this was missing and so the problem was solved while we use JSONTokener like answer of yours.

Your answer is very fine. Just i think i add this information so i answered

Thank you

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Sum a list of numbers in Python

import numpy as np    
x = [1,2,3,4,5]
[(np.mean((x[i],x[i+1]))) for i in range(len(x)-1)]
# [1.5, 2.5, 3.5, 4.5]

iOS UIImagePickerController result image orientation after upload

I used this page when designing my app that takes pictures and I found that the following method will correct the orientation and use less memory and processor than previous answers:

CGImageRef cgRef = image.CGImage;
image = [[UIImage alloc] initWithCGImage:cgRef scale:1.0 orientation:UIImageOrientationUp];

This basically just rewraps the actual image data with a new orientation. I was using @an0's code but it makes a new image in memory which can be taxing on a 3264x2448 image that you might get from a camera.

How to locate the php.ini file (xampp)

In the documentation http://www.apachefriends.org/en/xampp-windows.html (Configuration files section, near the bottom of the page): \xampp\php\php.ini

Rails :include vs. :joins

I was recently reading more on difference between :joins and :includes in rails. Here is an explaination of what I understood (with examples :))

Consider this scenario:

  • A User has_many comments and a comment belongs_to a User.

  • The User model has the following attributes: Name(string), Age(integer). The Comment model has the following attributes:Content, user_id. For a comment a user_id can be null.

Joins:

:joins performs a inner join between two tables. Thus

Comment.joins(:user)

#=> <ActiveRecord::Relation [#<Comment id: 1, content: "Hi I am Aaditi.This is my first   comment!", user_id: 1, created_at: "2014-11-12 18:29:24", updated_at: "2014-11-12 18:29:24">, 
     #<Comment id: 2, content: "Hi I am Ankita.This is my first comment!", user_id: 2, created_at: "2014-11-12 18:29:29", updated_at: "2014-11-12 18:29:29">,    
     #<Comment id: 3, content: "Hi I am John.This is my first comment!", user_id: 3, created_at: "2014-11-12 18:30:25", updated_at: "2014-11-12 18:30:25">]>

will fetch all records where user_id (of comments table) is equal to user.id (users table). Thus if you do

Comment.joins(:user).where("comments.user_id is null")

#=> <ActiveRecord::Relation []>

You will get a empty array as shown.

Moreover joins does not load the joined table in memory. Thus if you do

comment_1 = Comment.joins(:user).first

comment_1.user.age
#=>?[1m?[36mUser Load (0.0ms)?[0m  ?[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1?[0m  [["id", 1]]
#=> 24

As you see, comment_1.user.age will fire a database query again in the background to get the results

Includes:

:includes performs a left outer join between the two tables. Thus

Comment.includes(:user)

#=><ActiveRecord::Relation [#<Comment id: 1, content: "Hi I am Aaditi.This is my first comment!", user_id: 1, created_at: "2014-11-12 18:29:24", updated_at: "2014-11-12 18:29:24">,
   #<Comment id: 2, content: "Hi I am Ankita.This is my first comment!", user_id: 2, created_at: "2014-11-12 18:29:29", updated_at: "2014-11-12 18:29:29">,
   #<Comment id: 3, content: "Hi I am John.This is my first comment!", user_id: 3, created_at: "2014-11-12 18:30:25", updated_at: "2014-11-12 18:30:25">,    
   #<Comment id: 4, content: "Hi This is an anonymous comment!", user_id: nil, created_at: "2014-11-12 18:31:02", updated_at: "2014-11-12 18:31:02">]>

will result in a joined table with all the records from comments table. Thus if you do

Comment.includes(:user).where("comment.user_id is null")
#=> #<ActiveRecord::Relation [#<Comment id: 4, content: "Hi This is an anonymous comment!", user_id: nil, created_at: "2014-11-12 18:31:02", updated_at: "2014-11-12 18:31:02">]>

it will fetch records where comments.user_id is nil as shown.

Moreover includes loads both the tables in the memory. Thus if you do

comment_1 = Comment.includes(:user).first

comment_1.user.age
#=> 24

As you can notice comment_1.user.age simply loads the result from memory without firing a database query in the background.

how to check if object already exists in a list

Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains or myList.Any; the run-time will be quadratic. You might want to consider using a better data structure. For example,

 public class MyClass
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }

    }

    public class MyClassComparer : EqualityComparer<MyClass>
    {
        public override bool Equals(MyClass x, MyClass y)
        {
            if(x == null || y == null)
               return x == y;

            return x.Property1 == y.Property1 && x.Property2 == y.Property2;
        }

        public override int GetHashCode(MyClass obj)
        {
            return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
        }
    }

You could use a HashSet in the following manner:

  var set = new HashSet<MyClass>(new MyClassComparer());
  foreach(var myClass in ...)
     set.Add(myClass);

Of course, if this definition of equality for MyClass is 'universal', you needn't write an IEqualityComparer implementation; you could just override GetHashCode and Equals in the class itself.

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

Calculating the distance between 2 points

the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25

Convert object to JSON in Android

public class Producto {

int idProducto;
String nombre;
Double precio;



public Producto(int idProducto, String nombre, Double precio) {

    this.idProducto = idProducto;
    this.nombre = nombre;
    this.precio = precio;

}
public int getIdProducto() {
    return idProducto;
}
public void setIdProducto(int idProducto) {
    this.idProducto = idProducto;
}
public String getNombre() {
    return nombre;
}
public void setNombre(String nombre) {
    this.nombre = nombre;
}
public Double getPrecio() {
    return precio;
}
public void setPrecio(Double precio) {
    this.precio = precio;
}

public String toJSON(){

    JSONObject jsonObject= new JSONObject();
    try {
        jsonObject.put("id", getIdProducto());
        jsonObject.put("nombre", getNombre());
        jsonObject.put("precio", getPrecio());

        return jsonObject.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }

}

Loop until a specific user input

As an alternative to @Mark Byers' approach, you can use while True:

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

What and When to use Tuple?

Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.

The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.

Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.

How to exclude particular class name in CSS selector?

One way is to use the multiple class selector (no space as that is the descendant selector):

_x000D_
_x000D_
.reMode_hover:not(.reMode_selected):hover _x000D_
{_x000D_
   background-color: #f0ac00;_x000D_
}
_x000D_
<a href="" title="Design" class="reMode_design  reMode_hover">_x000D_
    <span>Design</span>_x000D_
</a>_x000D_
_x000D_
<a href="" title="Design" _x000D_
 class="reMode_design  reMode_hover reMode_selected">_x000D_
    <span>Design</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

Is it possible to change the package name of an Android app on Google Play?

If you are referring to com.example.app, no I understand you can't it would be considered a new app

How to get unique device hardware id in Android?

Update: 19 -11-2019

The below answer is no more relevant to present day.

So for any one looking for answers you should look at the documentation linked below

https://developer.android.com/training/articles/user-data-ids


Old Answer - Not relevant now. You check this blog in the link below

http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

ANDROID_ID

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                    Secure.ANDROID_ID); 

The above is from the link @ Is there a unique Android device ID?

More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.

ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.

The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.

You get the imei number of the device using the below

  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  telephonyManager.getDeviceId();

http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29

Add this is manifest

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Open Sublime Text from Terminal in macOS

Assuming:

  • You have already installed Homebrew.
  • /usr/local/bin is in your $PATH.
  • You are on Yosemite or El Capitain.

MacOS Sierra 10.12.5 works as well confirmed by David Rawson and MacOS Sierra 10.12.6 confirmed by Alexander K.

Run the following script in Terminal to create the specific symlink.

ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

Then:

subl .

Hit Return and it should instantly open Sublime Text.

How to send and retrieve parameters using $state.go toParams and $stateParams?

None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.

In the state add your params to end of state and define the params:

url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}

In your controller your go statement will look like this:

$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' });

Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):

var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!

addEventListener vs onclick

As far as I know, the DOM "load" event still does only work very limited. That means it'll only fire for the window object, images and <script> elements for instance. The same goes for the direct onload assignment. There is no technical difference between those two. Probably .onload = has a better cross-browser availabilty.

However, you cannot assign a load event to a <div> or <span> element or whatnot.

Best way to strip punctuation from a string

Remove stop words from the text file using Python

print('====THIS IS HOW TO REMOVE STOP WORS====')

with open('one.txt','r')as myFile:

    str1=myFile.read()

    stop_words ="not", "is", "it", "By","between","This","By","A","when","And","up","Then","was","by","It","If","can","an","he","This","or","And","a","i","it","am","at","on","in","of","to","is","so","too","my","the","and","but","are","very","here","even","from","them","then","than","this","that","though","be","But","these"

    myList=[]

    myList.extend(str1.split(" "))

    for i in myList:

        if i not in stop_words:

            print ("____________")

            print(i,end='\n')

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)

nx.draw(g,with_labels=True)
plt.draw()
plt.show()

This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.

Note: It's just a simple representation. Weighted Edges could be added like

g.add_edges_from([(1,2),(2,5)], weight=2)

and hence plotted again.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Use of alloc init instead of new

Very old question, but I've written some example just for fun — maybe you'll find it useful ;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

In main function both statements:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

result in the same output:

2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating...
2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...

Pass values of checkBox to controller action in asp.net mvc4

If you want your value to be read by MVT controller when you submit the form and you don't what to deal with hidden inputs. What you can do is add value attribute to your checkbox and set it to true or false.

MVT will not recognize viewModel property myCheckbox as true here

<input type="checkbox" name="myCheckbox" checked="checked" />

but will if you add

<input type="checkbox" name="myCheckbox" checked="checked" value="true" />

Script that does it:

$(document).on("click", "[type='checkbox']", function(e) {
        if (this.checked) {
            $(this).attr("value", "true");
        } else {
            $(this).attr("value","false");}
    });

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

The HTTP Content-Type for .ogg should be application/ogg (video/ogg for .ogv) and for .mp4 it should be video/mp4. You can check using the Web Sniffer.

Is there a sleep function in JavaScript?

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

$_SERVER['REMOTE_ADDR'] gives the IP address from which the request was sent to the web server. This is typically the visitor's address, but in your case, it sounds like there is some kind of proxy sitting right before the web server that intercepts the requests, hence to the web server it appears as though the requests are originating from there.

Difference between JSON.stringify and JSON.parse

The real confusion here is not about parse vs stringify, it's about the data type of the data parameter of the success callback.

data can be either the raw response, i.e a string, or it can be an JavaScript object, as per the documentation:

success

Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified;<..>

And the dataType defaults to a setting of 'intelligent guess'

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

'IF' in 'SELECT' statement - choose output value based on column values

SELECT CompanyName, 
    CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
         WHEN Country = 'Brazil' THEN 'South America'
         ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;

PHP convert string to hex and hex to string

PHP :

string to hex:

implode(unpack("H*", $string));

hex to string:

pack("H*", $hex);

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

Change

 mAdapter = new RecordingsListAdapter(this, recordings);

to

 mAdapter = new RecordingsListAdapter(getActivity(), recordings);

and also make sure that recordings!=null at mAdapter = new RecordingsListAdapter(this, recordings);

HTTP Error 503, the service is unavailable

In my case, the problem was that another application was using the port that I had bound to my web site.

I found it by running the following command from a command line, which lists all of the listening ports and the executable involved:

netstat -b

Include .so library in apk in android studio

I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526

It says:

for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"

That should fix your problem.

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

how to access iFrame parent page using jquery?

To find in the parent of the iFrame use:

$('#parentPrice', window.parent.document).html();

The second parameter for the $() wrapper is the context in which to search. This defaults to document.

Why is char[] preferred over String for passwords?

String in java is immutable. So whenever a string is created, it will remain in the memory until it is garbage collected. So anyone who has access to the memory can read the value of the string.
If the value of the string is modified then it will end up creating a new string. So both the original value and the modified value stay in the memory until it is garbage collected.

With the character array, the contents of the array can be modified or erased once the purpose of the password is served. The original contents of the array will not be found in memory after it is modified and even before the garbage collection kicks in.

Because of the security concern it is better to store password as a character array.

How can I show figures separately in matplotlib?

Sure. Add an Axes using add_subplot. (Edited import.) (Edited show.)

import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()

Alternatively, use add_axes.

ax1 = f1.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(range(0,10))
ax2 = f2.add_axes([0.1,0.1,0.8,0.8])
ax2.plot(range(10,20))

Creating temporary files in bash

Is there any advantage in creating a temporary file in a more careful way

The temporary files are usually created in the temporary directory (such as /tmp) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).


You could use the following approach to create the temporary directory:

TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"

or temporary file:

TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"

However it is still predictable and not considered safe.

As per man mktemp, we can read:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.

So to be safe, it is recommended to use mktemp command to create unique temporary file or directory (-d).

Determine Whether Two Date Ranges Overlap

Below query gives me the ids for which the supplied date range (start and end dates overlaps with any of the dates (start and end dates) in my table_name

select id from table_name where (START_DT_TM >= 'END_DATE_TIME'  OR   
(END_DT_TM BETWEEN 'START_DATE_TIME' AND 'END_DATE_TIME'))

How to call external url in jquery?

JQuery and PHP

In PHP file "contenido.php":

<?php
$mURL = $_GET['url'];

echo file_get_contents($mURL);
?>

In html:

<script type="text/javascript" src="js/jquery/jquery.min.js"></script>
<script type="text/javascript">
    function getContent(pUrl, pDivDestino){
        var mDivDestino = $('#'+pDivDestino);

        $.ajax({
            type : 'GET',
            url : 'contenido.php',
            dataType : 'html',
            data: {
                url : pUrl
            },
            success : function(data){                                               
                mDivDestino.html(data);
            }   
        });
    }
</script>

<a href="#" onclick="javascript:getContent('http://www.google.com/', 'contenido')">Get Google</a>
<div id="contenido"></div>

Understanding the results of Execute Explain Plan in Oracle SQL Developer

FULL is probably referring to a full table scan, which means that no indexes are in use. This is usually indicating that something is wrong, unless the query is supposed to use all the rows in a table.

Cost is a number that signals the sum of the different loads, processor, memory, disk, IO, and high numbers are typically bad. The numbers are added up when moving to the root of the plan, and each branch should be examined to locate the bottlenecks.

You may also want to query v$sql and v$session to get statistics about SQL statements, and this will have detailed metrics for all kind of resources, timings and executions.

List all the files and folders in a Directory with PHP recursive function

here I have example for that

List all the files and folders in a Directory csv(file) read with PHP recursive function

<?php

/** List all the files and folders in a Directory csv(file) read with PHP recursive function */
function getDirContents($dir, &$results = array()){
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            //$results[] = $path;
        }
    }

    return $results;
}





$files = getDirContents('/xampp/htdocs/medifree/lab');//here folder name where your folders and it's csvfile;


foreach($files as $file){
$csv_file =$file;
$foldername =  explode(DIRECTORY_SEPARATOR,$file);
//using this get your folder name (explode your path);
print_r($foldername);

if (($handle = fopen($csv_file, "r")) !== FALSE) {

fgetcsv($handle); 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
}
fclose($handle);
}

}

?>

http://myphpinformation.blogspot.in/2016/05/list-all-files-and-folders-in-directory-csv-file-read-with-php-recursive.html

Retrieving a random item from ArrayList

public static Item getRandomChestItem(List<Item> items) {
    return items.get(new Random().nextInt(items.size()));
}

What is the difference between x86 and x64

The difference is that Java binaries compiled as x86 (32-bit) or x64 (64-bit) applications respectively.

On a 64-bit Windows you can use either version, since x86 will run in WOW64 mode. On a 32-bit Windows you should use only x86 obviously.

For a Linux you should select appropriate type x86 for 32-bit OS, and x64 for 64-bit OS.

How to create a drop shadow only on one side of an element?

I think this is what you're after?

_x000D_
_x000D_
.shadow {_x000D_
  -webkit-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  -moz-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
}
_x000D_
<div class="shadow">wefwefwef</div>
_x000D_
_x000D_
_x000D_

Newtonsoft JSON Deserialize

You can implement a class that holds the fields you have in your JSON

class MyData
{
    public string t;
    public bool a;
    public object[] data;
    public string[][] type;
}

and then use the generic version of DeserializeObject:

MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
    // Do something with typeStr
}

Documentation: Serializing and Deserializing JSON

C# - Winforms - Global Variables

The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.

static class Program
{
    public static string globalString = "This is a global string.";

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

And use it as such:

public partial class Form1 : Form
{
    public Form1()
    {
        Program.globalString = "Accessible in Form1.";

        InitializeComponent();
    }
}

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

I just encountered the same issue but here it seemed to come from the fact that I declared the ID-column to be UNsigned and that in combination with an ID-value of '0' (zero) caused the import to fail...

So by changing the value of every ID (PK-column) that I'd declared '0' and every corresponding FK to the new value, my issue was solved.

What is __main__.py?

You create __main__.py in yourpackage to make it executable as:

$ python -m yourpackage

Onchange open URL via select - jQuery

Another way:

    <script type="text/javascript">
        function change_url(val) {
            window.location=val;
        }
    </script>            
    <select style="width:130px;" onchange="change_url(this.value);">
            <option value="http://www.url1.com">Option 1</option>
            <option value="http://www.url2.com">Option 2</option>
     </select>

What does EntityManager.flush do and why do I need to use it?

So when you call EntityManager.persist(), it only makes the entity get managed by the EntityManager and adds it (entity instance) to the Persistence Context. An Explicit flush() will make the entity now residing in the Persistence Context to be moved to the database (using a SQL).

Without flush(), this (moving of entity from Persistence Context to the database) will happen when the Transaction to which this Persistence Context is associated is committed.

How does the Spring @ResponseBody annotation work?

The first basic thing to understand is the difference in architectures.

One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:

Browser <---> Controller <---> Model
               |      |
               +-View-+

The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.

On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.

But when we use @ResponseBody, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use

@RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)

to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces to MediaType.APPLICATION_XML_VALUE and I believe you need to configure the HttpMessageConverter for JAXB. As for the JSON MappingJacksonHttpMessageConverter configured, when we have Jackson on the classpath.

I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.

Where does the .gitignore file belong?

As the other answers stated, you can place .gitignore within any directory in a Git repository. However, if you need to have a private version of .gitignore, you can add the rules to .git/info/exclude file.

Limit characters displayed in span

You can use the CSS property max-width and use it with ch unit.
And, as this is a <span>, use a display: inline-block; (or block).

Here is an example:

<span style="
  display:inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>

Which outputs:

Lorem ipsum...

_x000D_
_x000D_
<span style="_x000D_
  display:inline-block;_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
_x000D_
_x000D_

2D character array initialization in C

char **options[2][100];

declares a size-2 array of size-100 arrays of pointers to pointers to char. You'll want to remove one *. You'll also want to put your string literals in double quotes.

How to format DateTime columns in DataGridView?

You can set the format you want:

dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn

Installing specific laravel version with composer create-project

Try via Composer Create-Project

You may also install Laravel by issuing the Composer create-project command in your terminal:

composer create-project laravel/laravel {directory} "5.0.*" --prefer-dist

How do I add space between two variables after a print in Python

A simple way would be:

print str(count) + '  ' + str(conv)

If you need more spaces, simply add them to the string:

print str(count) + '    ' + str(conv)

A fancier way, using the new syntax for string formatting:

print '{0}  {1}'.format(count, conv)

Or using the old syntax, limiting the number of decimals to two:

print '%d  %.2f' % (count, conv)

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

Bootstrap navbar Active State not working

This worked perfectly for me, because "window.location.pathname" also contains data before the real page name, e.g. directory/page.php. So the actual navbar link will only be set to active if the url contains this link.

$(document).ready(function() {
    $.each($('#navbar').find('li'), function() {
        $(this).toggleClass('active', 
            window.location.pathname.indexOf($(this).find('a').attr('href')) > -1);
    }); 
});

What is the connection string for localdb for version 11

This is a fairly old thread, but since I was reinstalling my Visual Studio 2015 Community today, I thought I might add some info on what to use on VS2015, or what might work in general.

To see which instances were installed by default, type sqllocaldb info inside a command prompt. On my machine, I get two instances, the first one named MSSQLLocalDB.

C:\>sqllocaldb info
MSSQLLocalDB
ProjectsV13

You can also create a new instance if you wish, using sqllocaldb create "some_instance_name", but the default one will work just fine:

// if not using a verbatim string literal, don't forget to escape backslashes
@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"

'\r': command not found - .bashrc / .bash_profile

I am using cygwin and Windows7, the trick was NOT to put the set -o igncr into your .bashrc but put the whole SHELLOPTS into you environment variables under Windows. (So nothing with unix / cygwin...) I think it does not work from .bashrc because "the drops is already sucked" as we would say in german. ;-) So my SHELLOPTS looks like this

braceexpand:emacs:hashall:histexpand:history:igncr:interactive-comments:monitor

How to validate Google reCAPTCHA v3 on server side?

Check below example

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
         document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}

</script>
<form autocomplete="off" method="post" action=submit.php">

    <input type="text" name="name">
    <input type="text" name="email">
    <div class="g-recaptcha" id="rcaptcha"  data-sitekey="site key"></div>
    <span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
    <input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>

What is String pool in Java?

I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.

String s1 = "Arul"; //case 1 
String s2 = "Arul"; //case 2 

In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.

if(s1 == s2) System.out.println("equal"); //Prints equal. 

String n1 = new String("Arul"); 
String n2 = new String("Arul"); 
if(n1 == n2) System.out.println("equal"); //No output.  

http://p2p.wrox.com/java-espanol/29312-string-pooling.html

Generics/templates in python?

Fortunately there has been some efforts for the generic programming in python . There is a library : generic

Here is the documentation for it: http://generic.readthedocs.org/en/latest/

It hasn't progress over years , but you can have a rough idea how to use & make your own library.

Cheers

How do I upgrade PHP in Mac OS X?

You can use curl to update php version.

curl -s http://php-osx.liip.ch/install.sh | bash -s 7.3

Last Step:

export PATH=/usr/local/php5/bin:$PATH

Check the upgraded version

php -v

jquery - fastest way to remove all rows from a very large table

if you want to remove only fast.. you can do like below..

$( "#tableId tbody tr" ).each( function(){
  this.parentNode.removeChild( this ); 
});

but, there can be some event-binded elements in table,

in that case,

above code is not prevent memory leak in IE... T-T and not fast in FF...

sorry....

Get the string representation of a DOM node

if using react:

const html = ReactDOM.findDOMNode(document.getElementsByTagName('html')[0]).outerHTML;

How do I use jQuery to redirect?

I found out why this happening.

After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.

Thank you everyone for trying to solve this. :)

How to hide element label by element id in CSS?

This is worked for me.

#_account_id{
        display: none;
    }
    label[for="_account_id"] { display: none !important; }

how to programmatically fake a touch event to a UIButton?

An update to this answer for Swift

buttonObj.sendActionsForControlEvents(.TouchUpInside)

EDIT: Updated for Swift 3

buttonObj.sendActions(for: .touchUpInside)

Transfer data from one HTML file to another

Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.

Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:

  1. Session Cookies
  2. HTML5 LocalStorage
  3. POST the variable in the url and retrieve them in next.html via window object

Copy multiple files with Ansible

You can loop through variable with list of directories:

- name: Copy files from several directories
  copy:
    src: "{{ item }}"
    dest: "/etc/fooapp/"
    owner: root
    mode: "0600"
  loop: "{{ files }}"
  vars:
    files:
      - "dir1/"
      - "dir2/"

document.getElementById vs jQuery $()

Not exactly!!

document.getElementById('contents'); //returns a HTML DOM Object

var contents = $('#contents');  //returns a jQuery Object

In jQuery, to get the same result as document.getElementById, you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).

var contents = $('#contents')[0]; //returns a HTML DOM Object

how to implement a long click listener on a listview

or try this code:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int index, long arg3) {

    Toast.makeText(list.this,myList.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
                return false;
            }
}); 

Some projects cannot be imported because they already exist in the workspace error in Eclipse

delete it from eclipse......u might have closed the project in eclipse by "(Rightclick)-->close project".....so even if you delete this project from workspace folder....it stays there in eclipse IDE as closed project.....you should delete it from Eclipse IDE...!!!

pip or pip3 to install packages for Python 3?

I think pip, pip2 and pip3 are not soft links to the same executable file path. Note these commands and results in my Linux terminal:

mrz@mrz-pc ~ $ ls -l `which pip`
-rwxr-xr-x 1 root root 292 Nov 10  2016 /usr/bin/pip
mrz@mrz-pc ~ $ ls -l `which pip2`
-rwxr-xr-x 1 root root 283 Nov 10  2016 /usr/bin/pip2
mrz@mrz-pc ~ $ ls -l `which pip3`
-rwxr-xr-x 1 root root 293 Nov 10  2016 /usr/bin/pip3
mrz@mrz-pc ~ $ pip -V
pip 9.0.1 from /home/mrz/.local/lib/python2.7/site-packages (python 2.7)
mrz@mrz-pc ~ $ pip2 -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
mrz@mrz-pc ~ $ pip3 -V
pip 9.0.1 from /home/mrz/.local/lib/python3.5/site-packages (python 3.5)

As you see they exist in different paths.

pip3 always operates on the Python3 environment only, as pip2 does with Python2. pip operates in whichever environment is appropriate to the context. For example, if you are in a Python3 venv, pip will operate on the Python3 environment.

Selecting data frame rows based on partial string match in a column

Try str_detect() from the stringr package, which detects the presence or absence of a pattern in a string.

Here is an approach that also incorporates the %>% pipe and filter() from the dplyr package:

library(stringr)
library(dplyr)

CO2 %>%
  filter(str_detect(Treatment, "non"))

   Plant        Type  Treatment conc uptake
1    Qn1      Quebec nonchilled   95   16.0
2    Qn1      Quebec nonchilled  175   30.4
3    Qn1      Quebec nonchilled  250   34.8
4    Qn1      Quebec nonchilled  350   37.2
5    Qn1      Quebec nonchilled  500   35.3
...

This filters the sample CO2 data set (that comes with R) for rows where the Treatment variable contains the substring "non". You can adjust whether str_detect finds fixed matches or uses a regex - see the documentation for the stringr package.

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

All you have to do is to edit the httpd-xampp.conf

from Require local to Require all granted in the LocationMatch tag.

That's it!

jQuery Popup Bubble/Tooltip

QTip has bug with jQuery 1.4.2. I had to switch to jQuery Bubble Pop up http://www.vegabit.com/jquery_bubble_popup_v2/#examples and it works great!

python inserting variable string as file name

you can do something like

filename = "%s.csv" % name
f = open(filename , 'wb')

or f = open('%s.csv' % name, 'wb')

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

The answer of @alexandre with base64 does the trick.

The explanation why that works for IE is here

https://en.m.wikipedia.org/wiki/Data_URI_scheme

Under header 'format' where it says

Some browsers (Chrome, Opera, Safari, Firefox) accept a non-standard ordering if both ;base64 and ;charset are supplied, while Internet Explorer requires that the charset's specification must precede the base64 token.

How to create threads in nodejs

I needed real multithreading in Node.js and what worked for me was the threads package. It spawns another process having it's own Node.js message loop, so they don't block each other. The setup is easy and the documentation get's you up and running fast. Your main program and the workers can communicate in both ways and worker "threads" can be killed if needed.

Since multithreading and Node.js is a complicated and widely discussed topic it was quite difficult to find a package that works for my specific requirement. For the record these did not work for me:

  • tiny-worker allowed spawning workers, but they seemed to share the same message loop (but it might be I did something wrong - threads had more documentation giving me confidence it really used multiple processes, so I kept going until it worked)
  • webworker-threads didn't allow require-ing modules in workers which I needed

And for those asking why I needed real multi-threading: For an application involving the Raspberry Pi and interrupts. One thread is handling those interrupts and another takes care of storing the data (and more).

Creating a selector from a method name with parameters

SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:

-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);

-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here

-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted

Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:

-(void)someMethod:(NSTimer*)timer;

So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:

@implementation MyObject

-(void)myTimerCallback:(NSTimer*)timer
{
    // do some computations
    if( timerShouldEnd ) {
      [timer invalidate];
    }
}

@end

// ...

int main(int argc, const char **argv)
{
    // do setup stuff
    MyObject* obj = [[MyObject alloc] init];
    SEL mySelector = @selector(myTimerCallback:);
    [NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
    // do some tear-down
    return 0;
}

In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.

How to schedule a task to run when shutting down windows

You can run a batch file that calls your program, check out the discussion here for how to do it: http://www.pcworld.com/article/115628/windows_tips_make_windows_start_and_stop_the_way_you_want.html

(from google search: windows schedule task run at shut down)

How to use systemctl in Ubuntu 14.04

I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.

If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.

For enable, the generic looks to be the following:

update-rc.d <service> enable

Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers

AngularJS - How can I do a redirect with a full page load?

I had the same issue. When I use window.location, $window.location or even <a href="..." target="_self"> the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload() after window.location to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:

  $scope.openPage = function (pageName) {
      window.location = '#/html/pages/' + pageName;
      window.location.reload();
  };

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

Counting DISTINCT over multiple columns

Hope this works i am writing on prima vista

SELECT COUNT(*) 
FROM DocumentOutputItems 
GROUP BY DocumentId, DocumentSessionId

Can I force a UITableView to hide the separator between empty cells?

For iOS 7.* and iOS 6.1

The easiest method is to set the tableFooterView property:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    // This will remove extra separators from tableview
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

For previous versions

You could add this to your TableViewController (this will work for any number of sections):

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
     // This will create a "invisible" footer
     return 0.01f;
 }

and if it is not enough, add the following code too:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{        
    return [UIView new];

    // If you are not using ARC:
    // return [[UIView new] autorelease];
}

Change DIV content using ajax, php and jQuery

This works for me and you don't need the inline script:

Javascript:

    $(document).ready(function() {
    $('.showme').bind('click', function() {

        var id=$(this).attr("id");
        var num=$(this).attr("class");
        var poststr="request="+num+"&moreinfo="+id;
        $.ajax({
              url:"testme.php",
              cache:0,
              data:poststr,
              success:function(result){
                     document.getElementById("stuff").innerHTML=result;
               }
        }); 
    });
 });

HTML:

    <div class='request_1 showme' id='rating_1'>More stuff 1</div>
    <div class='request_2 showme' id='rating_2'>More stuff 2</div>
    <div class='request_3 showme' id='rating_3'>More stuff 3</div>

    <div id="stuff">Here is some stuff that will update when the links above are clicked</div>

The request is sent to testme.php:

    header("Cache-Control: no-cache");
    header("Pragma: nocache");

    $request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
    $request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);

    if($request_id=="1")
    {
        echo "show 1";
    }
    elseif($request_id=="2")
    {
        echo "show 2";
    }
    else
    {
        echo "show 3";
    }

A fast way to delete all rows of a datatable at once

If you are really concerned about speed and not worried about the data you can do a Truncate. But this is assuming your DataTable is on a database and not just a memory object.

TRUNCATE TABLE tablename

The difference is this removes all rows without logging the row deletes making the transaction faster.

Does GPS require Internet?

There are two issues:

  1. Getting the current coordinates (longitude, latitude, perhaps altitude) based on some external signals received by your device, and
  2. Deriving a human-readable position (address) from the coordinates.

To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.

As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.

Python function global variables?

As others have noted, you need to declare a variable global in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need global.

To go into a bit more detail on that, what "modify" means is this: if you want to re-bind the global name so it points to a different object, the name must be declared global in the function.

Many operations that modify (mutate) an object do not re-bind the global name to point to a different object, and so they are all valid without declaring the name global in the function.

d = {}
l = []
o = type("object", (object,), {})()

def valid():     # these are all valid without declaring any names global!
   d[0] = 1      # changes what's in d, but d still points to the same object
   d[0] += 1     # ditto
   d.clear()     # ditto! d is now empty but it`s still the same object!
   l.append(0)   # l is still the same list but has an additional member
   o.test = 1    # creating new attribute on o, but o is still the same object

Getting each individual digit from a whole integer

Agree with previous answers.

A little correction: There's a better way to print the decimal digits from left to right, without allocating extra buffer. In addition you may want to display a zero characeter if the score is 0 (the loop suggested in the previous answers won't print anythng).

This demands an additional pass:

int div;
for (div = 1; div <= score; div *= 10)
    ;

do
{
    div /= 10;
    printf("%d\n", score / div);
    score %= div;
} while (score);

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

Permissions

You need the s3:GetObject permission for this operation. For more information, see Specifying Permissions in a Policy. If the object you request does not exist, the error Amazon S3 returns depends on whether you also have the s3:ListBucket permission.

If you have the s3:ListBucket permission on the bucket, Amazon S3 returns an HTTP status code 404 ("no such key") error.

If you don’t have the s3:ListBucket permission, Amazon S3 returns an HTTP status code 403 ("access denied") error.

The following operation is related to HeadObject:

GetObject

Source: https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html

How do I find a particular value in an array and return its index?

the fancy answer. Use std::vector and search with std::find

the simple answer

use a for loop

splitting a number into the integer and decimal parts

This variant allows getting desired precision:

>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)

How to stop/shut down an elasticsearch node?

use the following command to know the pid of the node already running.

curl -XGET 'http://localhost:9200/_nodes/process'

It took me an hour to find out the way to kill the node and could finally do it after using this command in the terminal window.

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

Android Camera : data intent returns null

When we capture the image from Camera in Android then Uri or data.getdata() becomes null. We have two solutions to resolve this issue.

  1. Retrieve the Uri path from the Bitmap Image
  2. Retrieve the Uri path from cursor.

This is how to retrieve the Uri from the Bitmap Image. First capture image through Intent that will be the same for both methods:

// Capture Image
captureImg.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, reqcode);
        }
    }
});

Now implement OnActivityResult, which will be the same for both methods:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==reqcode && resultCode==RESULT_OK)
    {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        ImageView.setImageBitmap(photo);

        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);

        // Show Uri path based on Image
        Toast.makeText(LiveImage.this,"Here "+ tempUri, Toast.LENGTH_LONG).show();

        // Show Uri path based on Cursor Content Resolver
        Toast.makeText(this, "Real path for URI : "+getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
    }
}

Now create all above methods to create the Uri from Image and Cursor methods:

Uri path from Bitmap Image:

private Uri getImageUri(Context applicationContext, Bitmap photo) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
    return Uri.parse(path);
}

Uri from Real path of saved image:

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Check if a string is a palindrome

public bool Solution(string content)
    {
        int length = content.Length;

        int half = length/2;

        int isOddLength = length%2;

        // Counter for checking the string from the middle 
        int j = (isOddLength==0) ? half:half+1;

        for(int i=half-1;i>=0;i--)
        {                
            if(content[i] != content[j])
            {
               return false;
            }
            j++;

        }
        return true;
    }

Debug JavaScript in Eclipse

JavaScript is executed in the browser, which is pretty far removed from Eclipse. Eclipse would have to somehow hook into the browser's JavaScript engine to debug it. Therefore there's no built-in debugging of JavaScript via Eclipse, since JS isn't really its main focus anyways.

However, there are plug-ins which you can install to do JavaScript debugging. I believe the main one is the AJAX Toolkit Framework (ATF). It embeds a Mozilla browser in Eclipse in order to do its debugging, so it won't be able to handle cross-browser complications that typically arise when writing JavaScript, but it will certainly help.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Is there any way to call a function periodically in JavaScript?

function test() {
 alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
   clearInterval(id);
}

How to Replace dot (.) in a string in Java

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

Android: checkbox listener

you may also go for a simple View.OnClickListener:

satView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(((CompoundButton) view).isChecked()){
            System.out.println("Checked");
        } else {
            System.out.println("Un-Checked");
        }
    }
});

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

There is the Importing a repository with GitHub Importer

If you have a project hosted on another version control system as Mercurial, you can automatically import it to GitHub using the GitHub Importer tool.

  1. In the upper-right corner of any page, click , and then click Import repository.
  2. Under "Your old repository's clone URL", type the URL of the project you want to import.
  3. Choose your user account or an organization to own the repository, then type a name for the repository on GitHub.
  4. Specify whether the new repository should be public or private.
    • Public repositories are visible to any user on GitHub, so you can benefit from GitHub's collaborative community.
    • Public or private repository radio buttonsPrivate repositories are only available to the repository owner, as well as any collaborators you choose to share with.
  5. Review the information you entered, then click Begin import.

You'll receive an email when the repository has been completely imported.

  1. https://help.github.com/categories/importing-your-projects-to-github
  2. https://help.github.com/articles/importing-a-repository-with-github-importer/

How are software license keys generated?

CD-Keys aren't much of a security for any non-networked stuff, so technically they don't need to be securely generated. If you're on .net, you can almost go with Guid.NewGuid().

Their main use nowadays is for the Multiplayer component, where a server can verify the CD Key. For that, it's unimportant how securely it was generated as it boils down to "Lookup whatever is passed in and check if someone else is already using it".

That being said, you may want to use an algorhithm to achieve two goals:

  • Have a checksum of some sort. That allows your Installer to display "Key doesn't seem valid" message, solely to detect typos (Adding such a check in the installer actually means that writing a Key Generator is trivial as the hacker has all the code he needs. Not having the check and solely relying on server-side validation disables that check, at the risk of annoying your legal customers who don't understand why the server doesn't accept their CD Key as they aren't aware of the typo)
  • Work with a limited subset of characters. Trying to type in a CD Key and guessing "Is this an 8 or a B? a 1 or an I? a Q or an O or a 0?" - by using a subset of non-ambigous chars/digits you eliminate that confusion.

That being said, you still want a large distribution and some randomness to avoid a pirate simply guessing a valid key (that's valid in your database but still in a box on a store shelf) and screwing over a legitimate customer who happens to buy that box.

Pointer vs. Reference

If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.

A better solution in most cases (from a safety perspective) is to use boost::optional. This allows you to pass in optional values by reference and also as a return value.

// Sample method using optional as input parameter
void PrintOptional(const boost::optional<std::string>& optional_str)
{
    if (optional_str)
    {
       cout << *optional_str << std::endl;
    }
    else
    {
       cout << "(no string)" << std::endl;
    }
}

// Sample method using optional as return value
boost::optional<int> ReturnOptional(bool return_nothing)
{
    if (return_nothing)
    {
       return boost::optional<int>();
    }

    return boost::optional<int>(42);
}

.htaccess deny from all

A little alternative to @gasp´s answer is to simply put the actual domain name you are running it from. Docs: https://httpd.apache.org/docs/2.4/upgrading.html

In the following example, there is no authentication and all hosts in the example.org domain are allowed access; all other hosts are denied access.

Apache 2.2 configuration:

Order Deny,Allow
Deny from all
Allow from example.org

Apache 2.4 configuration:

Require host example.org

Sort a Map<Key, Value> by values

Okay, this version works with two new Map objects and two iterations and sorts on values. Hope, the performs well although the map entries must be looped twice:

public static void main(String[] args) {
    Map<String, String> unsorted = new HashMap<String, String>();
    unsorted.put("Cde", "Cde_Value");
    unsorted.put("Abc", "Abc_Value");
    unsorted.put("Bcd", "Bcd_Value");

    Comparator<String> comparer = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }};

    System.out.println(sortByValue(unsorted, comparer));

}

public static <K, V> Map<K,V> sortByValue(Map<K, V> in, Comparator<? super V> compare) {
    Map<V, K> swapped = new TreeMap<V, K>(compare);
    for(Entry<K,V> entry: in.entrySet()) {
        if (entry.getValue() != null) {
            swapped.put(entry.getValue(), entry.getKey());
        }
    }
    LinkedHashMap<K, V> result = new LinkedHashMap<K, V>();
    for(Entry<V,K> entry: swapped.entrySet()) {
        if (entry.getValue() != null) {
            result.put(entry.getValue(), entry.getKey());
        }
    }
    return result;
}

The solution uses a TreeMap with a Comparator and sorts out all null keys and values. First, the ordering functionality from the TreeMap is used to sort upon the values, next the sorted Map is used to create a result as a LinkedHashMap that retains has the same order of values.

Greetz, GHad

Changing the action of a form with JavaScript/jQuery

Just an update to this - I've been having a similar problem updating the action attribute of a form with jQuery.

After some testing it turns out that the command: $('#myForm').attr('action','new_url.html');

silently fails if the action attribute of the form is empty. If i update the action attribute of my form to contain some text, the jquery works.

Mailto links do nothing in Chrome but work in Firefox?

You can use like this also,

<a href="javascript:void(0);" onclick="javascript:window.location.href='mailto:[email protected]'; return false;">[email protected]</a>

I think this is best way to resolved for chrome issues.

Thanks..

XSS prevention in JSP/Servlet web application

There is no easy, out of the box solution against XSS. The OWASP ESAPI API has some support for the escaping that is very usefull, and they have tag libraries.

My approach was to basically to extend the stuts 2 tags in following ways.

  1. Modify s:property tag so it can take extra attributes stating what sort of escaping is required (escapeHtmlAttribute="true" etc.). This involves creating a new Property and PropertyTag classes. The Property class uses OWASP ESAPI api for the escaping.
  2. Change freemarker templates to use the new version of s:property and set the escaping.

If you didn't want to modify the classes in step 1, another approach would be to import the ESAPI tags into the freemarker templates and escape as needed. Then if you need to use a s:property tag in your JSP, wrap it with and ESAPI tag.

I have written a more detailed explanation here.

http://www.nutshellsoftware.org/software/securing-struts-2-using-esapi-part-1-securing-outputs/

I agree escaping inputs is not ideal.

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

The solution, based on this comment: https://stackoverflow.com/a/22409447/2399045 . Just set settings: DB name, temp folder, db files folder. And after run you will have the copy of DB with Name in "sourceDBName_yyyy-mm-dd" format.

-- Settings --
-- New DB name will have name = sourceDB_yyyy-mm-dd
declare @sourceDbName nvarchar(50) = 'MyDbName';
declare @tmpFolder nvarchar(50) = 'C:\Temp\'
declare @sqlServerDbFolder nvarchar(100) = 'C:\Databases\'

--  Execution --
declare @sourceDbFile nvarchar(50);
declare @sourceDbFileLog nvarchar(50);
declare @destinationDbName nvarchar(50) = @sourceDbName + '_' + (select convert(varchar(10),getdate(), 121))
declare @backupPath nvarchar(400) = @tmpFolder + @destinationDbName + '.bak'
declare @destMdf nvarchar(100) = @sqlServerDbFolder + @destinationDbName + '.mdf'
declare @destLdf nvarchar(100) = @sqlServerDbFolder + @destinationDbName + '_log' + '.ldf'

SET @sourceDbFile = (SELECT top 1 files.name 
                    FROM sys.databases dbs 
                    INNER JOIN sys.master_files files 
                        ON dbs.database_id = files.database_id 
                    WHERE dbs.name = @sourceDbName
                        AND files.[type] = 0)

SET @sourceDbFileLog = (SELECT top 1 files.name 
                    FROM sys.databases dbs 
                    INNER JOIN sys.master_files files 
                        ON dbs.database_id = files.database_id 
                    WHERE dbs.name = @sourceDbName
                        AND files.[type] = 1)

BACKUP DATABASE @sourceDbName TO DISK = @backupPath

RESTORE DATABASE @destinationDbName FROM DISK = @backupPath
WITH REPLACE,
   MOVE @sourceDbFile     TO @destMdf,
   MOVE @sourceDbFileLog  TO @destLdf

How can I extract audio from video with ffmpeg?

Just a guess:

-ab 192

should be

-ab 192k

Seems like that could be a problem, but maybe ffmpeg is smart enough to correct it.

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

For me the problem was that I was setting REQUESTS_CA_BUNDLE in my .bash_profile

/Users/westonagreene/.bash_profile:
...
export REQUESTS_CA_BUNDLE=/usr/local/etc/openssl/cert.pem
...

Once I set REQUESTS_CA_BUNDLE to blank (i.e. removed from .bash_profile), requests worked again.

export REQUESTS_CA_BUNDLE=""

The problem only exhibited when executing python requests via a CLI (Command Line Interface). If I ran requests.get(URL, CERT) it resolved just fine.

Mac OS Catalina (10.15.6). Pyenv of 3.6.11. Error message I was getting: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

My answer elsewhere: https://stackoverflow.com/a/64151964/4420657

React Error: Target Container is not a DOM Element

webpack solution

If you got this error while working in React with webpack and HMR.

You need to create template index.html and save it in src folder:

<html>
    <body>
       <div id="root"></root>
    </body>
</html>

Now when we have template with id="root" we need to tell webpack to generate index.html which will mirror our index.html file.

To do that:

plugins: [
    new HtmlWebpackPlugin({
        title: "Application name",
        template: './src/index.html'
    })
],

template property will tell webpack how to build index.html file.

What is the difference between a mutable and immutable string in C#?

String in C# is immutable. If you concatenate it with any string, you are actually making a new string, that is new string object ! But StringBuilder creates mutable string.

Can I store images in MySQL

You will need to store the image in the database as a BLOB.

you will want to create a column called PHOTO in your table and set it as a mediumblob.

Then you will want to get it from the form like so:

    $data = file_get_contents($_FILES['photo']['tmp_name']);

and then set the column to the value in $data.

Of course, this is bad practice and you would probably want to store the file on the system with a name that corresponds to the users account.

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

I had the same problem in my rails project:

Incorrect string value: '\xF0\xA9\xB8\xBDs ...' for column 'subject' at row1

Solution 1: before saving to db convert string to base64 by Base64.encode64(subject) and after fetching from db use Base64.decode64(subject)

Solution 2:

Step 1: Change the character set (and collation) for subject column by

ALTER TABLE t1 MODIFY
subject VARCHAR(255)
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

Step 2: In database.yml use

encoding :utf8mb4

How to change title of Activity in Android?

If you want to change Title of activity when you change activity by clicking on the Button. Declare the necessary variables in MainActivity:

    private static final String TITLE_SIGN = "title_sign";
    ImageButton mAriesButton;

Add onClickListener in onCreate() and make new intent for another activity:

    mTitleButton = (ImageButton) findViewById(R.id.title_button);
    mTitleButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, 
        SignActivity.class);
        String title_act = getText(R.string.simple_text).toString();
        intent.putExtra("title_act", title_act);
        startActivity(intent);
        finish();
        }
    });

SecondActivity code in onCreate():

    String txtTitle = getIntent().getStringExtra("title_act");
    this.setTitle(txtTitle);

Set environment variables on Mac OS X Lion

What worked for me is to create a .launchd.conf with the variables I needed:

setenv FOO barbaz

This file is read by launchd at login. You can add a variable 'on the fly' to the running launchd using:

launchctl setenv FOO barbaz`

In fact, .launchd.cond simply contains launchctl commands.

Variables set this way seem to be present in GUI applications properly.

If you happen to be trying to set your LANG or LC_ variables in this way, and you happen to be using iTerm2, make sure you disable the 'Set locale variables automatically' setting under the Terminal tab of the Profile you're using. That seems to override launchd's environment variables, and in my case was setting a broken LC_CTYPE causing issues on remote servers (which got passed the variable).

(The environment.plist still seems to work on my Lion though. You can use the RCenvironment preference pane to maintain the file instead of manually editing it or required Xcode. Still seems to work on Lion, though it's last update is from the Snow Leopard era. Makes it my personally preferred method.)

Convert varchar to uniqueidentifier in SQL Server

DECLARE @uuid VARCHAR(50)
SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010'
SELECT  CAST(
        SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +
        SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12)
        AS UNIQUEIDENTIFIER)

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

.NET unique object identifier

Checked out the ObjectIDGenerator class? This does what you're attempting to do, and what Marc Gravell describes.

The ObjectIDGenerator keeps track of previously identified objects. When you ask for the ID of an object, the ObjectIDGenerator knows whether to return the existing ID, or generate and remember a new ID.

The IDs are unique for the life of the ObjectIDGenerator instance. Generally, a ObjectIDGenerator life lasts as long as the Formatter that created it. Object IDs have meaning only within a given serialized stream, and are used for tracking which objects have references to others within the serialized object graph.

Using a hash table, the ObjectIDGenerator retains which ID is assigned to which object. The object references, which uniquely identify each object, are addresses in the runtime garbage-collected heap. Object reference values can change during serialization, but the table is updated automatically so the information is correct.

Object IDs are 64-bit numbers. Allocation starts from one, so zero is never a valid object ID. A formatter can choose a zero value to represent an object reference whose value is a null reference (Nothing in Visual Basic).

How to select all columns, except one column in pandas?

Another slight modification to @Salvador Dali enables a list of columns to exclude:

df[[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]

or

df.loc[:,[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]

VMWare Player vs VMWare Workstation

from http://www.vmware.com/products/player/faqs.html:

How does VMware Player compare to VMware Workstation? VMware Player enables you to quickly and easily create and run virtual machines. However, VMware Player lacks many powerful features, remote connections to vSphere, drag and drop upload to vSphere, multiple Snapshots and Clones, and much more.

Not being able to revert snapshots it's a big no for me.

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

MemoryStream - Cannot access a closed Stream

when it gets out from the using statement the Dispose method will be called automatically closing the stream

try the below:

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());
        }
}    

How organize uploaded media in WP?

Best is Enhanced Media Library plugin http://wordpress.org/plugins/enhanced-media-library/ It's adding as many category/ taxonomies you want. Works just great. You can filter media everywhere, plus have the categories in the menu choices, can be usefull also.

Conditional Logic on Pandas DataFrame

In this specific example, where the DataFrame is only one column, you can write this elegantly as:

df['desired_output'] = df.le(2.5)

le tests whether elements are less than or equal 2.5, similarly lt for less than, gt and ge.

Difference between clean, gradlew clean

You can also use

./gradlew clean build (Mac and Linux) -With ./

gradlew clean build (Windows) -Without ./

it removes build folder, as well configure your modules and then build your project.

i use it before release any new app on playstore.

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

I am using Visual Studio 2013 and I have the same issue but it occurs when I try to open a solution that was made using Visual Studio 2010.

The solution for me is to open the solution file (.sln), using notepad and change this line:

[# Visual Studio 2010]

to this:

[# Visual Studio 2013]

How to use jQuery to show/hide divs based on radio button selection?

Update 2015/06

As jQuery has evolved since the question was posted, the recommended approach now is using $.on

$(document).ready(function() {
    $("input[name=group2]").on( "change", function() {

         var test = $(this).val();
         $(".desc").hide();
         $("#"+test).show();
    } );
});

or outside $.ready()

$(document).on( "change", "input[name=group2]", function() { ... } );

Original answer

You should use .change() event handler:

$(document).ready(function(){ 
    $("input[name=group2]").change(function() {
        var test = $(this).val();
        $(".desc").hide();
        $("#"+test).show();
    }); 
});

should work

C# Macro definitions in Preprocessor

You can use a C preprocessor (like mcpp) and rig it into your .csproj file. Then you chnage "build action" on your source file from Compile to Preprocess or whatever you call it. Just add BeforBuild to your .csproj like this:

  <Target Name="BeforeBuild" Inputs="@(Preprocess)" Outputs="@(Preprocess->'%(Filename)_P.cs')">
<Exec Command="..\Bin\cpp.exe @(Preprocess) -P -o %(RelativeDir)%(Filename)_P.cs" />
<CreateItem Include="@(Preprocess->'%(RelativeDir)%(Filename)_P.cs')">
  <Output TaskParameter="Include" ItemName="Compile" />
</CreateItem>

You may have to manually change Compile to Preprocess on at least one file (in a text editor) - then the "Preprocess" option should be available for selection in Visual Studio.

I know that macros are heavily overused and misused but removing them completely is equally bad if not worse. A classic example of macro usage would be NotifyPropertyChanged. Every programmer who had to rewrite this code by hand thousands of times knows how painful it is without macros.

Visual Studio opens the default browser instead of Internet Explorer

You mentioned Visual Studio. This is for Visual Studio 2013. In the "Menu and Tools" in the second line , right below Debug you have a dropdown box giving you the list / option of "Emulators" .Your IE should be in the option , select that and you are good to go. Easy way .

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

I think you're mixed up between PATH and PYTHONPATH. All you have to do to run a 'script' is have it's parental directory appended to your PATH variable. You can test this by running

which myscript.py

Also, if myscripy.py depends on custom modules, their parental directories must also be added to the PYTHONPATH variable. Unfortunately, because the designers of python were clearly on drugs, testing your imports in the repl with the following will not guarantee that your PYTHONPATH is set properly for use in a script. This part of python programming is magic and can't be answered appropriately on stackoverflow.

$python
Python 2.7.8 blahblahblah
...
>from mymodule.submodule import ClassName
>test = ClassName()
>^D
$myscript_that_needs_mymodule.submodule.py
Traceback (most recent call last):
  File "myscript_that_needs_mymodule.submodule.py", line 5, in <module>
    from mymodule.submodule import ClassName
  File "/path/to/myscript_that_needs_mymodule.submodule.py", line 5, in <module>
    from mymodule.submodule import ClassName
ImportError: No module named submodule

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

C# Test if user has write access to a folder

Try this:

try
{
    DirectoryInfo di = new DirectoryInfo(path);
    DirectorySecurity acl = di.GetAccessControl();
    AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));

    WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(currentUser);
    foreach (AuthorizationRule rule in rules)
    {
        FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule;
        if (fsAccessRule == null)
            continue;

        if ((fsAccessRule.FileSystemRights & FileSystemRights.WriteData) > 0)
        {
            NTAccount ntAccount = rule.IdentityReference as NTAccount;
            if (ntAccount == null)
            {
                continue;
            }

            if (principal.IsInRole(ntAccount.Value))
            {
                Console.WriteLine("Current user is in role of {0}, has write access", ntAccount.Value);
                continue;
            }
            Console.WriteLine("Current user is not in role of {0}, does not have write access", ntAccount.Value);                        
        }
    }
}
catch (UnauthorizedAccessException)
{
    Console.WriteLine("does not have write access");
}

Can't connect to docker from docker-compose

sudo systemctl start docker - to start the Docker service.

sudo docker-compose up after that.

I have Fedora 26, and trying to solve the same issue I eventually entered Docker Compose on Fedora Developers' page and then Docker on Fedora Developers' page, which helped me.

Probably, docker service considered by community to start with the system and run in background all the time, but for me it was not so obvious, and that's the reason I can think of why there's no popular answer like this one.

On the Fedora Developers' page there's instruction how to enable Docker to start with the system:

sudo systemctl enable docker

How do I center align horizontal <UL> menu?

Here's a good article on how to do it in a pretty rock-solid way, without any hacks and full cross-browser support. Works for me:

--> http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support

How to format a number 0..9 to display with 2 digits (it's NOT a date)

You can use:

String.format("%02d", myNumber)

See also the javadocs

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Multi-select dropdown list in ASP.NET

You could use the System.Web.UI.WebControls.CheckBoxList control or use the System.Web.UI.WebControls.ListBox control with the SelectionMode property set to Multiple.

Python, creating objects

when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.

class Student:
     def __init__(self):

# creating an object....

   student1=Student()

Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..

class Student:
      def __init__(self,name,age):
            self.name=value
            self.age=value

 # creating an object.......

     student2=Student("smith",25)

How to use group by with union in t-sql

GROUP BY 1

I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).

There's no need to run GROUP BY on the contents when you're using UNION - UNION ensures that duplicates are removed; UNION ALL is faster because it doesn't - and in that case you would need the GROUP BY...

Your query only needs to be:

SELECT a.id,
       a.time
  FROM dbo.TABLE_A a
UNION
SELECT b.id,
       b.time
  FROM dbo.TABLE_B b

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior:

Project B depend on Library A

in Library A:

public class DocSearchResponse<T> {
 private T data;
}

it has service to query data from external source, and use jackson to convert to concrete class

public class ServiceA<T>{
  @Autowired
  private ObjectMapper mapper;
  @Autowired
  private ClientDocSearch searchClient;

  public DocSearchResponse<T> query(Criteria criteria){
      String resultInString = searchClient.search(criteria);
      return convertJson(resultInString)
  }
}

public DocSearchResponse<T> convertJson(String result){
     return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
  }
}

in Project B:

public class Account{
 private String name;
 //come with other attributes
}

and i use ServiceA from library to make query and as well convert data

public class ServiceAImpl extends ServiceA<Account> {
    
}

and make use of that

public class MakingAccountService {
    @Autowired
    private ServiceA service;
    public void execute(Criteria criteria){
      
        DocSearchResponse<Account> result = service.query(criteria);
        Account acc = result.getData(); //  java.util.LinkedHashMap cannot be cast to com.testing.models.Account
    }
}

it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson in Project B to let jackson do its job

public class ServiceAImpl extends ServiceA<Account> {
        @Override
        public DocSearchResponse<T> convertJson(String result){
         return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
      }
    }
 }

How to print a debug log?

A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents('php://stderr', print_r($foo, TRUE)) will nicely dump the value of $foo into the Apache error log.

Using CMake to generate Visual Studio C++ project files

Lots of great answers here but they might be superseded by this CMake support in Visual Studio (Oct 5 2016)

Where do I call the BatchNormalization function in Keras?

Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.

Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().

from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, 
validation_split=0.2, verbose = 2)

How is Batch Normalization applied?

Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity

  1. Using a[l-1] and W[l] we can calculate z[l] for the layer l
  2. Usually in feed-forward propagation we will add bias unit to the z[l] at this stage like this z[l]+b[l], but in Batch Normalization this step of addition of b[l] is not required and no b[l] parameter is used.
  3. Calculate z[l] means and subtract it from each element
  4. Divide (z[l] - mean) using standard deviation. Call it Z_temp[l]
  5. Now define new parameters ? and ß that will change the scale of the hidden layer as follows:

    z_norm[l] = ?.Z_temp[l] + ß

In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.

a[l] = tanh(z_norm[l])

Assigning multiple styles on an HTML element

You needed to do it like this:

_x000D_
_x000D_
<h2 style="text-align: center;font-family: Tahoma">TITLE</h2>
_x000D_
_x000D_
_x000D_

Hope it helped.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Remove a character at a certain position in a string - javascript

you can use substring() method. ex,

var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);

Closing WebSocket correctly (HTML5, Javascript)

The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF] protocol, and then there's the new version using Hybi formatted packets.

The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!

However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88 (better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

FULL OUTER JOIN vs. FULL JOIN

Actually they are the same. LEFT OUTER JOIN is same as LEFT JOIN and RIGHT OUTER JOIN is same as RIGHT JOIN. It is more informative way to compare from INNER Join.

See this Wikipedia article for details.

How do I display a decimal value to 2 decimal places?

There's a very important characteristic of Decimal that isn't obvious:

A Decimal 'knows' how many decimal places it has based upon where it came from

The following may be unexpected :

Decimal.Parse("25").ToString()          =>   "25"
Decimal.Parse("25.").ToString()         =>   "25"
Decimal.Parse("25.0").ToString()        =>   "25.0"
Decimal.Parse("25.0000").ToString()     =>   "25.0000"

25m.ToString()                          =>   "25"
25.000m.ToString()                      =>   "25.000"

Doing the same operations with Double will result in zero decimal places ("25") for all of the above examples.

If you want a decimal to 2 decimal places there's a high likelyhood it's because it's currency in which case this is probably fine for 95% of the time:

Decimal.Parse("25.0").ToString("c")     =>   "$25.00"

Or in XAML you would use {Binding Price, StringFormat=c}

One case I ran into where I needed a decimal AS a decimal was when sending XML to Amazon's webservice. The service was complaining because a Decimal value (originally from SQL Server) was being sent as 25.1200 and rejected, (25.12 was the expected format).

All I needed to do was Decimal.Round(...) with 2 decimal places to fix the problem regardless of the source of the value.

 // generated code by XSD.exe
 StandardPrice = new OverrideCurrencyAmount()
 {
       TypedValue = Decimal.Round(product.StandardPrice, 2),
       currency = "USD"
 }

TypedValue is of type Decimal so I couldn't just do ToString("N2") and needed to round it and keep it as a decimal.

How to change UIPickerView height

I am working with ios 7, Xcode 5. I was able to adjust the height of date picker indirectly by enclosing it in a view. The container views height can be adjusted.