Programs & Examples On #Ischecked

jQuery, checkboxes and .is(":checked")

I'm still experiencing this behavior with jQuery 1.7.2. A simple workaround is to defer the execution of the click handler with setTimeout and let the browser do its magic in the meantime:

$("#myCheckbox").click( function() {
    var that = this;
    setTimeout(function(){
        alert($(that).is(":checked"));
    });
});

How do I remove a CLOSE_WAIT socket connection

As described by Crist Clark.

CLOSE_WAIT means that the local end of the connection has received a FIN from the other end, but the OS is waiting for the program at the local end to actually close its connection.

The problem is your program running on the local machine is not closing the socket. It is not a TCP tuning issue. A connection can (and quite correctly) stay in CLOSE_WAIT forever while the program holds the connection open.

Once the local program closes the socket, the OS can send the FIN to the remote end which transitions you to LAST_ACK while you wait for the ACK of the FIN. Once that is received, the connection is finished and drops from the connection table (if your end is in CLOSE_WAIT you do not end up in the TIME_WAIT state).

Laravel view not found exception

Create the index.blade.php file in the views folder, that should be all

Display a jpg image on a JPanel

ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Downloading a picture via urllib and python

I have found this answer and I edit that in more reliable way

def download_photo(self, img_url, filename):
    try:
        image_on_web = urllib.urlopen(img_url)
        if image_on_web.headers.maintype == 'image':
            buf = image_on_web.read()
            path = os.getcwd() + DOWNLOADED_IMAGE_PATH
            file_path = "%s%s" % (path, filename)
            downloaded_image = file(file_path, "wb")
            downloaded_image.write(buf)
            downloaded_image.close()
            image_on_web.close()
        else:
            return False    
    except:
        return False
    return True

From this you never get any other resources or exceptions while downloading.

Is Google Play Store supported in avd emulators?

It's not officially supported yet.

Edit: It's now supported in modern versions of Android Studio, at least on some platforms.

Old workarounds

If you're using an old version of Android Studio which doesn't support the Google Play Store, and you refuse to upgrade, here are two possible workarounds:

  1. Ask your favorite app's maintainers to upload a copy of their app into the Amazon Appstore. Next, install the Appstore onto your Android device. Finally, use the Appstore to install your favorite app.

  2. Or: Do a Web search to find a .apk file for the software you want. For example, if you want to install SleepBot in your Android emulator, you can do a Google Web search for [ SleepBot apk ]. Then use adb install to install the .apk file.

int to unsigned int conversion

Edit: As has been noted in the other answers, the standard actually guarantees that "the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type)". So even if your platform did not store signed ints as two's complement, the behavior would be the same.


Apparently your signed integer -62 is stored in two's complement (Wikipedia) on your platform:

62 as a 32-bit integer written in binary is

0000 0000 0000 0000 0000 0000 0011 1110

To compute the two's complement (for storing -62), first invert all the bits

1111 1111 1111 1111 1111 1111 1100 0001

then add one

1111 1111 1111 1111 1111 1111 1100 0010

And if you interpret this as an unsigned 32-bit integer (as your computer will do if you cast it), you'll end up with 4294967234 :-)

Send attachments with PHP Mail()?

For PHP 5.5.27 security update

$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// header
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";

if (mail($mailto, $subject, $nmessage, $header)) {
    return true; // Or do something here
} else {
  return false;
}

Autocompletion in Vim

There’s also clang_complete which uses the clang compiler to provide code completion for C++ projects. There’s another question with troubleshooting hints for this plugin.

The plugin seems to work fairly well as long as the project compiles, but is prohibitively slow for large projects (since it attempts a full compilation to generate the tags list).

How to import an existing directory into Eclipse?

The thing that works best for me when that happens is :

  1. Create a new eclipse project(JAVA)

  2. Take your source file (contents of the src folder!!!) and drag from finder and drop into the src folder in eclipse IDE

  3. Make sure you add your external jars and stuff and tada you're done!!

How large is a DWORD with 32- and 64-bit code?

It is defined as:

typedef unsigned long       DWORD;

However, according to the MSDN:

On 32-bit platforms, long is synonymous with int.

Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:

typdef unsigned _int64 DWORD64;

Hope that helps.

Creating Dynamic button with click event in JavaScript

Wow you're close. Edits in comments:

_x000D_
_x000D_
function add(type) {_x000D_
  //Create an input type dynamically.   _x000D_
  var element = document.createElement("input");_x000D_
  //Assign different attributes to the element. _x000D_
  element.type = type;_x000D_
  element.value = type; // Really? You want the default value to be the type string?_x000D_
  element.name = type; // And the name too?_x000D_
  element.onclick = function() { // Note this is a function_x000D_
    alert("blabla");_x000D_
  };_x000D_
_x000D_
  var foo = document.getElementById("fooBar");_x000D_
  //Append the element in page (in span).  _x000D_
  foo.appendChild(element);_x000D_
}_x000D_
document.getElementById("btnAdd").onclick = function() {_x000D_
  add("text");_x000D_
};
_x000D_
<input type="button" id="btnAdd" value="Add Text Field">_x000D_
<p id="fooBar">Fields:</p>
_x000D_
_x000D_
_x000D_

Now, instead of setting the onclick property of the element, which is called "DOM0 event handling," you might consider using addEventListener (on most browsers) or attachEvent (on all but very recent Microsoft browsers) — you'll have to detect and handle both cases — as that form, called "DOM2 event handling," has more flexibility. But if you don't need multiple handlers and such, the old DOM0 way works fine.


Separately from the above: You might consider using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browsers differences like the addEventListener / attachEvent thing, provide useful utility features, and various other things. Obviously there's nothing a library can do that you can't do without one, as the libraries are just JavaScript code. But when you use a good library with a broad user base, you get the benefit of a huge amount of work already done by other people dealing with those browsers differences, etc.

C#: how to get first char of a string?

Following example for getting first character from a string might help someone

string anyNameForString = "" + stringVariableName[0];

Position Relative vs Absolute?

Absolute will make your element out of your flow layout, and it will be positioned to the closest relative parent (all parents are static by default). That's how you use absolute and relative together most of the time.

You can also use relative alone, but that is very rare case.

I have made an video to explain this.

https://www.youtube.com/watch?v=nGN5CohGVTI

Function for Factorial in Python

def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f

Swift how to sort array of custom objects by property value

Sort using KeyPath

you can sort by KeyPath like this:

myArray.sorted(by: \.fileName, <) /* using `<` for ascending sorting */

By implementing this little helpful extension.

extension Collection{
    func sorted<Value: Comparable>(
        by keyPath: KeyPath<Element, Value>,
        _ comparator: (_ lhs: Value, _ rhs: Value) -> Bool) -> [Element] {
        sorted { comparator($0[keyPath: keyPath], $1[keyPath: keyPath]) }
    }
}

Hope Swift add this in the near future in the core of the language.

ASP.NET MVC 3 - redirect to another action

You have to write this code instead of return View(); :

return RedirectToAction("ActionName", "ControllerName");

How to read values from properties file?

I'll recommend reading this link https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html from SpringBoot docs about injecting external configs. They didn't only talk about retrieving from a properties file but also YAML and even JSON files. I found it helpful. I hope you do too.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

With CSS, use "..." for overflowed block of multi-lines

I've found this css (scss) solution that works quite well. On webkit browsers it shows the ellipsis and on other browsers it just truncates the text. Which is fine for my intended use.

$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;

h2 {
  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: $font-size;
  line-height: $line-height;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

An example by the creator: http://codepen.io/martinwolf/pen/qlFdp

Kotlin Android start new Activity

From activity to activity

val intent = Intent(this, YourActivity::class.java)
startActivity(intent)

From fragment to activity

val intent = Intent(activity, YourActivity::class.java)
startActivity(intent)

jQuery 1.9 .live() is not a function

I tend not to use the .on() syntax, if not necessary. For example you can migrate easier like this:

old:

$('.myButton').live('click', function);

new:

$('.myButton').click(function)

Here is a list of valid event handlers: https://api.jquery.com/category/forms/

Equivalent of LIMIT and OFFSET for SQL Server?

You can use ROW_NUMBER in a Common Table Expression to achieve this.

;WITH My_CTE AS
(
     SELECT
          col1,
          col2,
          ROW_NUMBER() OVER(ORDER BY col1) AS row_number
     FROM
          My_Table
     WHERE
          <<<whatever>>>
)
SELECT
     col1,
     col2
FROM
     My_CTE
WHERE
     row_number BETWEEN @start_row AND @end_row

How to display HTML <FORM> as inline element?

Add a inline wrapper.

<div style='display:flex'>
<form>
 <p>Read this sentence</p>
 <input type='submit' value='or push this button' />
</form>
<div>
    <p>Message here</p>
</div>

Difference between signed / unsigned char

The same way -- e.g. if you have an 8-bit char, 7 bits can be used for magnitude and 1 for sign. So an unsigned char might range from 0 to 255, whilst a signed char might range from -128 to 127 (for example).

document .click function for touch device

can you use jqTouch or jquery mobile ? there it's much easier to handle touch events. If not then you need to simulate click on touch device, follow this articles:

iphone-touch-events-in-javascript

A touch demo

More in this thread

JSON: why are forward slashes escaped?

PHP escapes forward slashes by default which is probably why this appears so commonly. I'm not sure why, but possibly because embedding the string "</script>" inside a <script> tag is considered unsafe.

This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES flag but most developers will not use this since the original result is already valid JSON.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

Solution for Eclipse Luna:

  1. Right Click on maven web project
  2. Click 'Properties'menu
  3. Select 'Deployment Assembly' in left side of the popped window
  4. Click 'Add...' Button in right side of the popped up window
  5. Now appear one more popup window(New Assembly Directivies)
  6. Click 'Java Build path entries'
  7. Click 'Next' Button
  8. Click 'Finish' Button, now atomatically close New Assemby Directivies popup window
  9. Now click 'Apply' Button and Ok Button
  10. Run your webapplication

Adding a favicon to a static HTML page

As per OP's update, It was not showing up locally, but as per OP's update, once I uploaded it to the server, it was fine.

Since this is a simple, static html website, I have the luxury of working on it without running a local webserver.
A webserver will generally automatically serve up the favicon, if there is one, by default.

But when not running a webserver, the browser itself will not just read the directory looking for additional files, say a favicon.ico, unless it is listed in the html document.

So, while I had the following items in the head tag:

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/site.webmanifest">

I did not also include a reference for plain 'ol favicon.ico.
Even though, the favicon.ico file was included, in addition to the images listed above.

Once I added the following line:

    <link rel="icon" type="image/x-icon" href="favicon.ico">

It did also show up in my browser, when I viewing the local file, even when not serving it through a local server.

So icon showed up fine when it ran on the live server, but not locally.

I mention this explicitly because the favicon generator I used, kindly supplied the code, icons, manifest, and instructions. However, while it included the favicon.ico image, it did not include a <link> to that file in the code to add to the html document.
I guess that service presumes favicon.ico will automatically be served up and used by all browsers by default, so only the "alternate" versions needed to be explicitly added to the head tag.
Evidently, they don't consider that when viewing files locally (aka not serving them up locally), we aren't interested in seeing the favicon?

PHP/MySQL: How to create a comment section in your website

I'm working on this right now as well. You should also add a datetime of the comment. You'll need this later when you want to sort by most recent.

Here are some of the db fields i'm using.

id (auto incremented)
name
email
text
datetime
approved

Setting POST variable without using form

Yes, simply set it to another value:

$_POST['text'] = 'another value';

This will override the previous value corresponding to text key of the array. The $_POST is superglobal associative array and you can change the values like a normal PHP array.

Caution: This change is only visible within the same PHP execution scope. Once the execution is complete and the page has loaded, the $_POST array is cleared. A new form submission will generate a new $_POST array.

If you want to persist the value across form submissions, you will need to put it in the form as an input tag's value attribute or retrieve it from a data store.

Convert Difference between 2 times into Milliseconds?

VB.net, Desktop application. If you need lapsed time in milliseconds:

Dim starts As Integer = My.Computer.Clock.TickCount
Dim ends As Integer = My.Computer.Clock.TickCount
Dim lapsed As Integer = ends - starts

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

Maybe not very elegant, but it does the job:

exec(open("script.py").read())

How can I comment a single line in XML?

As others have said, there is no way to do a single line comment legally in XML that comments out multiple lines, but, there are ways to make commenting out segments of XML easier.

Looking at the example below, if you add '>' to line one, the XmlTag will be uncommented. Remove the '>' and it's commented out again. This is the simplest way that I've seen to quickly comment/uncomment XML without breaking things.

<!-- --
<XmlTag variable="0" />
<!-- -->

The added benefit is that you only manipulate the top comment, and the bottom comment can just sit there forever. This breaks compatibility with SGML and some XML parsers will barf on it. So long as this isn't a permanent fixture in your XML, and your parsers accept it, it's not really a problem.

Stack Overflow's and Notepad++'s syntax highlighter treat it like a multi-line comment, C++'s Boost library treats it as a multi-line comment, and the only parser I've found so far that breaks is the one in .NET, specifically C#. So, be sure to first test that your tools, IDE, libraries, language, etc. accept it before using it.

If you care about SGML compatibility, simply use this instead:

<!-- -
<XmlTag variable="0" />
<!- -->

Add '->' to the top comment and a '-' to the bottom comment. The downside is having to edit the bottom comment each time, which would probably make it easier to just type in <!-- at the top and --> at the bottom each time.

I also want to mention that other commenters recommend using an XML editor that allows you to right-click and comment/uncomment blocks of XML, which is probably preferable over fancy find/replace tricks (it would also make for a good answer in itself, but I've never used such tools. I just want to make sure the information isn't lost over time). I've personally never had to deal with XML enough to justify having an editor fancier than Notepad++, so this is totally up to you.

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

Replace multiple strings with multiple other strings

All solutions work great, except when applied in programming languages that closures (e.g. Coda, Excel, Spreadsheet's REGEXREPLACE).

Two original solutions of mine below use only 1 concatenation and 1 regex.

Method #1: Lookup for replacement values

The idea is to append replacement values if they are not already in the string. Then, using a single regex, we perform all needed replacements:

_x000D_
_x000D_
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||cat,dog,goat").replace(
   /cat(?=[\s\S]*(dog))|dog(?=[\s\S]*(goat))|goat(?=[\s\S]*(cat))|\|\|\|\|.*$/gi, "$1$2$3");
document.body.innerHTML = str;
_x000D_
_x000D_
_x000D_

Explanations:

  • cat(?=[\s\S]*(dog)) means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise.
  • Same for "dog" that would capture "goat" as group 2, and "goat" that would capture "cat" as group 3.
  • We replace with "$1$2$3" (the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above cases
  • If we manually appended replacements to the string like str+"||||cat,dog,goat", we remove them by also matching \|\|\|\|.*$, in which case the replacement "$1$2$3" will evaluate to "", the empty string.

Method #2: Lookup for replacement pairs

One problem with Method #1 is that it cannot exceed 9 replacements at a time, which is the maximum number of back-propagation groups. Method #2 states not to append just replacement values, but replacements directly:

_x000D_
_x000D_
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||,cat=>dog,dog=>goat,goat=>cat").replace(
   /(\b\w+\b)(?=[\s\S]*,\1=>([^,]*))|\|\|\|\|.*$/gi, "$2");
document.body.innerHTML = str;
_x000D_
_x000D_
_x000D_

Explanations:

  • (str+"||||,cat=>dog,dog=>goat,goat=>cat") is how we append a replacement map to the end of the string.
  • (\b\w+\b) states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else.
  • (?=[\s\S]*...) is a forward lookup that will typically go to the end of the document until after the replacement map.
    • ,\1=> means "you should find the matched word between a comma and a right arrow"
    • ([^,]*) means "match anything after this arrow until the next comma or the end of the doc"
  • |\|\|\|\|.*$ is how we remove the replacement map.

How do SO_REUSEADDR and SO_REUSEPORT differ?

Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.

There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:

{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}

Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.

The protocol of a socket is set when a socket is created with the socket() function. The source address and port are set with the bind() function. The destination address and port are set with the connect() function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.

If you explicitly bind a socket, it is possible to bind it to port 0, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0 in case of IPv4 and :: in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.

By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA to ipA:portA and socketB to ipB:portB is always possible if ipA != ipB holds true, even when portA == portB. E.g. socketA belongs to a FTP server program and is bound to 192.168.0.1:21 and socketB belongs to another FTP server program and is bound to 10.0.0.1:21, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21, regardless which specific IP address it tries to bind to, as 0.0.0.0 conflicts with all existing local IP addresses.

Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.

BSD

SO_REUSEADDR

If SO_REUSEADDR is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.

Without SO_REUSEADDR, binding socketA to 0.0.0.0:21 and then binding socketB to 192.168.0.1:21 will fail (with error EADDRINUSE), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1, too. With SO_REUSEADDR it will succeed, since 0.0.0.0 and 192.168.0.1 are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA and socketB are bound; without SO_REUSEADDR it will always fail, with SO_REUSEADDR it will always succeed.

To give you a better overview, let's make a table here and list all possible combinations:

SO_REUSEADDR       socketA        socketB       Result
---------------------------------------------------------------------
  ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
  ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
  ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
   OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
   OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
   ON              0.0.0.0:21   192.168.1.0:21    OK
   ON          192.168.1.0:21       0.0.0.0:21    OK
  ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)

The table above assumes that socketA has already been successfully bound to the address given for socketA, then socketB is created, either gets SO_REUSEADDR set or not, and finally is bound to the address given for socketB. Result is the result of the bind operation for socketB. If the first column says ON/OFF, the value of SO_REUSEADDR is irrelevant to the result.

Okay, SO_REUSEADDR has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.

A socket has a send buffer and if a call to the send() function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send() call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.

At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit() (pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.

The question is, how does the system treat a socket in state TIME_WAIT? If SO_REUSEADDR is not set, a socket in state TIME_WAIT is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.

There is one final thing you should know about SO_REUSEADDR. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR flag of the socket fed into the bind() call, for all other sockets inspected, this flag is not even looked at.

SO_REUSEPORT

SO_REUSEPORT is what most people would expect SO_REUSEADDR to be. Basically, SO_REUSEPORT allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR the code handling SO_REUSEPORT will not only verify that the currently bound socket has SO_REUSEPORT set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT set when it was bound.

SO_REUSEPORT does not imply SO_REUSEADDR. This means if a socket did not have SO_REUSEPORT set when it was bound and another socket has SO_REUSEPORT set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT state requires either SO_REUSEADDR to be set on that socket or SO_REUSEPORT must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT and SO_REUSEADDR, on a socket.

There is not much more to say about SO_REUSEPORT other than that it was added later than SO_REUSEADDR, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.

Connect() Returning EADDRINUSE?

Most people know that bind() may fail with the error EADDRINUSE, however, when you start playing around with address reuse, you may run into the strange situation that connect() fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?

As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.

So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect() will actually fail with the error EADDRINUSE for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.

Multicast Addresses

Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.

The meaning of SO_REUSEADDR changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR behaves exactly as SO_REUSEPORT for unicast addresses. Actually, the code treats SO_REUSEADDR and SO_REUSEPORT identically for multicast addresses, that means you could say that SO_REUSEADDR implies SO_REUSEPORT for all multicast addresses and the other way round.


FreeBSD/OpenBSD/NetBSD

All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.


macOS (MacOS X)

At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.

iOS / watchOS / tvOS

iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.


Linux

Linux < 3.9

Prior to Linux 3.9, only the option SO_REUSEADDR existed. This option behaves generally the same as in BSD with two important exceptions:

  1. As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.

  2. The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT prior to 3.9, the behavior of SO_REUSEADDR was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.

Linux >= 3.9

Linux 3.9 added the option SO_REUSEPORT to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.

Yet, there are still two differences to SO_REUSEPORT on other systems:

  1. To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND/SO_EXCLUSIVEADDRUSE flags.

  2. Additionally the kernel performs some "special magic" for SO_REUSEPORT sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT to get a very inexpensive load balancing.


Android

Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.


Windows

Windows only knows the SO_REUSEADDR option, there is no SO_REUSEPORT. Setting SO_REUSEADDR on a socket in Windows behaves like setting SO_REUSEPORT and SO_REUSEADDR on a socket in BSD, with one exception:

Prior to Windows 2003, a socket with SO_REUSEADDR could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!

Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE. Setting SO_EXCLUSIVEADDRUSE on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR set.

This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind() calls are made by the same user, and the third one when the bind() calls are made by different users.


Solaris

Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR, there is no SO_REUSEPORT. The SO_REUSEADDR behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.

Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND. If this option is set on a socket prior to binding it, setting SO_REUSEADDR on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA is bound to a wildcard address and socketB has SO_REUSEADDR enabled and is bound to a non-wildcard address and the same port as socketA, this bind will normally succeed, unless socketA had SO_EXCLBIND enabled, in which case it will fail regardless the SO_REUSEADDR flag of socketB.


Other Systems

In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.

All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h and stdbool.h; e.g. gcc supported both long before offering full C99 support).

All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".

It tests all possible combinations you can think of:

  • TCP and UDP protocol
  • Normal sockets, listen (server) sockets, multicast sockets
  • SO_REUSEADDR set on socket1, socket2, or both sockets
  • SO_REUSEPORT set on socket1, socket2, or both sockets
  • All address combinations you can make out of 0.0.0.0 (wildcard), 127.0.0.1 (specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3 in all tests)

and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT, in which case this option is simply not tested.

What the program cannot easily test is how SO_REUSEADDR acts on sockets in TIME_WAIT state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.

Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).

jQuery scroll to element

Easy way to achieve the scroll of page to target div id

var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);

MySQL error: key specification without a key length

DROP that table and again run Spring Project. That might help. Sometime you are overriding foreignKey.

Creating a copy of a database in PostgreSQL

  1. Open the Main Window in pgAdmin and then open another Query Tools Window
  2. In the main windows in pgAdmin,

Disconnect the "templated" database that you want to use as a template.

  1. Goto the Query Tools Window

Run 2 queries as below

SELECT pg_terminate_backend(pg_stat_activity.pid) 
    FROM pg_stat_activity 
    WHERE pg_stat_activity.datname = 'TemplateDB' AND pid <> pg_backend_pid(); 

(The above SQL statement will terminate all active sessions with TemplateDB and then you can now select it as the template to create the new TargetDB database, this avoids getting the already in use error.)

CREATE DATABASE 'TargetDB'
  WITH TEMPLATE='TemplateDB'
       CONNECTION LIMIT=-1;

import .css file into .less file

From the LESS website:

If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:

@import "lib.css"; The directive will just be left as is, and end up in the CSS output.

As jitbit points out in the comments below, this is really only useful for development purposes, as you wouldn't want to have unnecessary @imports consuming precious bandwidth.

How to handle AccessViolationException

Microsoft: "Corrupted process state exceptions are exceptions that indicate that the state of a process has been corrupted. We do not recommend executing your application in this state.....If you are absolutely sure that you want to maintain your handling of these exceptions, you must apply the HandleProcessCorruptedStateExceptionsAttribute attribute"

Microsoft: "Use application domains to isolate tasks that might bring down a process."

The program below will protect your main application/thread from unrecoverable failures without risks associated with use of HandleProcessCorruptedStateExceptions and <legacyCorruptedStateExceptionsPolicy>

public class BoundaryLessExecHelper : MarshalByRefObject
{
    public void DoSomething(MethodParams parms, Action action)
    {
        if (action != null)
            action();
        parms.BeenThere = true; // example of return value
    }
}

public struct MethodParams
{
    public bool BeenThere { get; set; }
}

class Program
{
    static void InvokeCse()
    {
        IntPtr ptr = new IntPtr(123);
        System.Runtime.InteropServices.Marshal.StructureToPtr(123, ptr, true);
    }

    private static void ExecInThisDomain()
    {
        try
        {
            var o = new BoundaryLessExecHelper();
            var p = new MethodParams() { BeenThere = false };
            Console.WriteLine("Before call");

            o.DoSomething(p, CausesAccessViolation);
            Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); //never stops here
        }
        catch (Exception exc)
        {
            Console.WriteLine($"CSE: {exc.ToString()}");
        }
        Console.ReadLine();
    }


    private static void ExecInAnotherDomain()
    {
        AppDomain dom = null;

        try
        {
            dom = AppDomain.CreateDomain("newDomain");
            var p = new MethodParams() { BeenThere = false };
            var o = (BoundaryLessExecHelper)dom.CreateInstanceAndUnwrap(typeof(BoundaryLessExecHelper).Assembly.FullName, typeof(BoundaryLessExecHelper).FullName);         
            Console.WriteLine("Before call");

            o.DoSomething(p, CausesAccessViolation);
            Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); // never gets to here
        }
        catch (Exception exc)
        {
            Console.WriteLine($"CSE: {exc.ToString()}");
        }
        finally
        {
            AppDomain.Unload(dom);
        }

        Console.ReadLine();
    }


    static void Main(string[] args)
    {
        ExecInAnotherDomain(); // this will not break app
        ExecInThisDomain();  // this will
    }
}

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Unexpected end of file means that something else was expected before the PHP parser reached the end of the script.

Judging from your HUGE file, it's probably that you're missing a closing brace (}) from an if statement.

Please at least attempt the following things:

  1. Separate your code from your view logic.
  2. Be consistent, you're using an end ; in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?> vs <?php echo $this->layouts->print_includes() ?>. It's not required, so don't use it (or do, just do one or the other).
  3. Repeated because it's important, separate your concerns. There's no need for all of this code.
  4. Use an IDE, it will help you with errors such as this going forward.

What's the most concise way to read query parameters in AngularJS?

To give a partial answer my own question, here is a working sample for HTML5 browsers:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
  <script>
    angular.module('myApp', [], function($locationProvider) {
      $locationProvider.html5Mode(true);
    });
    function QueryCntl($scope, $location) {
      $scope.target = $location.search()['target'];
    }
  </script>
</head>
<body ng-controller="QueryCntl">

Target: {{target}}<br/>

</body>
</html>

The key was to call $locationProvider.html5Mode(true); as done above. It now works when opening http://127.0.0.1:8080/test.html?target=bob. I'm not happy about the fact that it won't work in older browsers, but I might use this approach anyway.

An alternative that would work with older browsers would be to drop the html5mode(true) call and use the following address with hash+slash instead:

http://127.0.0.1:8080/test.html#/?target=bob

The relevant documentation is at Developer Guide: Angular Services: Using $location (strange that my google search didn't find this...).

What is the difference between :focus and :active?

Using "focus" will give keyboard users the same effect that mouse users get when they hover with a mouse. "Active" is needed to get the same effect in Internet Explorer.

The reality is, these states do not work as they should for all users. Not using all three selectors creates accessibility issues for many keyboard-only users who are physically unable to use a mouse. I invite you to take the #nomouse challenge (nomouse dot org).

Auto increment primary key in SQL Server Management Studio 2012

When you're creating the table, you can create an IDENTITY column as follows:

CREATE TABLE (
  ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
  ...
);

The IDENTITY property will auto-increment the column up from number 1. (Note that the data type of the column has to be an integer.) If you want to add this to an existing column, use an ALTER TABLE command.

Edit:
Tested a bit, and I can't find a way to change the Identity properties via the Column Properties window for various tables. I guess if you want to make a column an identity column, you HAVE to use an ALTER TABLE command.

CSS3 transitions inside jQuery .css()

Step 1) Remove the semi-colon, it's an object you're creating...

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out';
});

to

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out'
});

Step 2) Vendor-prefixes... no browsers use transition since it's the standard and this is an experimental feature even in the latest browsers:

a(this).next().css({
    left             : c,
    WebkitTransition : 'opacity 1s ease-in-out',
    MozTransition    : 'opacity 1s ease-in-out',
    MsTransition     : 'opacity 1s ease-in-out',
    OTransition      : 'opacity 1s ease-in-out',
    transition       : 'opacity 1s ease-in-out'
});

Here is a demo: http://jsfiddle.net/83FsJ/

Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:

$('a').on('click', function () {
    var myTransition = ($.browser.webkit)  ? '-webkit-transition' :
                       ($.browser.mozilla) ? '-moz-transition' : 
                       ($.browser.msie)    ? '-ms-transition' :
                       ($.browser.opera)   ? '-o-transition' : 'transition',
        myCSSObj     = { opacity : 1 };

    myCSSObj[myTransition] = 'opacity 1s ease-in-out';
    $(this).next().css(myCSSObj);
});?

Here is a demo: http://jsfiddle.net/83FsJ/1/

Also note that if you specify in your transition declaration that the property to animate is opacity, setting a left property won't be animated.

is inaccessible due to its protection level

Dan, it's just you're accessing the protected field instead of properties.

See for example this line in your Main(...):

myClub.distance = Console.ReadLine();

myClub.distance is the protected field, while you wanted to set the property mydistance.

I'm just giving you some hint, I'm not going to correct your code, since this is homework! ;)

PHP Curl And Cookies

You can specify the cookie file with a curl opt. You could use a unique file for each user.

curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true );
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, uniquefilename );

The best way to handle it would be to stick your request logic into a curl function and just pass the unique file name in as a parameter.

    function fetch( $url, $z=null ) {
            $ch =  curl_init();

            $useragent = isset($z['useragent']) ? $z['useragent'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';

            curl_setopt( $ch, CURLOPT_URL, $url );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
            curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
            curl_setopt( $ch, CURLOPT_POST, isset($z['post']) );

            if( isset($z['post']) )         curl_setopt( $ch, CURLOPT_POSTFIELDS, $z['post'] );
            if( isset($z['refer']) )        curl_setopt( $ch, CURLOPT_REFERER, $z['refer'] );

            curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
            curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, ( isset($z['timeout']) ? $z['timeout'] : 5 ) );
            curl_setopt( $ch, CURLOPT_COOKIEJAR,  $z['cookiefile'] );
            curl_setopt( $ch, CURLOPT_COOKIEFILE, $z['cookiefile'] );

            $result = curl_exec( $ch );
            curl_close( $ch );
            return $result;
    }

I use this for quick grabs. It takes the url and an array of options.

Angular 2 TypeScript how to find element in Array

from TypeScript you can use native JS array filter() method:

let filteredElements=array.filter(element => element.field == filterValue);

it returns an array with only matching elements from the original array (0, 1 or more)

Reference: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Get text from pressed button

Try this,

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText();

How can I check if my Element ID has focus?

Write below code in script and also add jQuery library

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')
            }
        });
    }

Thank you...

Convert Array to Object

_x000D_
_x000D_
var finalResult = ['a','b','c'].map((item , index) => ({[index] : item}));_x000D_
console.log(finalResult)
_x000D_
_x000D_
_x000D_

How do I calculate the date in JavaScript three months prior to today?

_x000D_
_x000D_
var d = new Date();_x000D_
document.write(d + "<br/>");_x000D_
d.setMonth(d.getMonth() - 6);_x000D_
document.write(d);
_x000D_
_x000D_
_x000D_

Calling a PHP function from an HTML form in the same file

This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.

test.php

<form action="javascript:void(0);" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" />
</form>

<script type="text/javascript">
    $("form").submit(function(){
        var str = $(this).serialize();
        $.ajax('getResult.php', str, function(result){
            alert(result); // The result variable will contain any text echoed by getResult.php
        }
        return(false);
    });
</script>

It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.

getResult.php

<?php
    echo "The name you typed is: " . $_REQUEST['user'];
?>

NOTE

This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.

Convert Unix timestamp to a date string

Put the following in your ~/.bashrc :

function unixts() { date -d "@$1"; }

Example usage:

$ unixts 1551276383

Wed Feb 27 14:06:23 GMT 2019

extract column value based on another column pandas dataframe

df[df['B']==3]['A'], assuming df is your pandas.DataFrame.

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

dataGridView1.Columns is probably of a length less than 5. Accessing dataGridView1.Columns[4] then will be outside the list.

AngularJs $http.post() does not send data

Just updated from angular 1.2 to 1.3, have found a problem in the code. Transforming a resource will lead to an endless-loop because (I think) of the $promise holding again the same object. Maybe it will help someone...

I could fix that by:

[...]
  /**
 * The workhorse; converts an object to x-www-form-urlencoded serialization.
 * @param {Object} obj
 * @return {String}
 */
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

angular.forEach(obj, function(value, name) {
+    if(name.indexOf("$promise") != -1) {
+        return;
+    }

    value = obj[name];
    if (value instanceof Array) {
        for (i = 0; i < value.length; ++i) {
[...]

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.

But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:

{ Id: 1, 
name:'john', 
phones:[{title:'home',number:111111,...},
        {title:'office',number:22222,...}]
}

sends

{ Id: 1, 
name:'john', 
phones:[object object]
phones:[object object]
}

Socket.io + Node.js Cross-Origin Request Blocked

Alright I had some issues getting this to work using a self signed cert for testing so I am going to copy my setup that worked for me. If your not using a self signed cert you probably wont have these issues, hopefully!

To start off depending on your browser Firefox or Chrome you may have different issues and I'll explain in a minute.

First the Setup:

Client

// May need to load the client script from a Absolute Path
<script src="https://www.YOURDOMAIN.com/node/node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var options = {
          rememberUpgrade:true,
          transports: ['websocket'],
          secure:true, 
          rejectUnauthorized: false
              }
var socket = io.connect('https://www.YOURDOMAIN.com:PORT', options);

// Rest of your code here
</script>

Server

var fs = require('fs');

var options = {
  key: fs.readFileSync('/path/to/your/file.pem'),
  cert: fs.readFileSync('/path/to/your/file.crt'),

};
var origins = 'https://www.YOURDOMAIN.com:*';
var app = require('https').createServer(options,function(req,res){

    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', 'https://www.YOURDOMAIN.com:*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    if ( req.method === 'OPTIONS' || req.method === 'GET' ) {
        res.writeHead(200);
        res.end();
        return;
            }

});

var io = require('socket.io')(app);

app.listen(PORT);

For development the options used on the client side are ok in production you would want the option:

 rejectUnauthorized: false

You would more than likely want set to "true"

Next thing is if its a self signed cert you will need to vist your server in a separate page/tab and accept the cert or import it into your browser.

For Firefox I kept getting the error

MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT

The solution for me was to add the following options and accepting the cert in a different page/tab.

{ 
rejectUnauthorized: false
} 

In Chrome I had to open another page and accept the cert but after that everything worked fine with out having to add any options.

Hope this helps.

References:

https://github.com/theturtle32/WebSocket-Node/issues/259

https://github.com/socketio/engine.io-client#methods

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

All you need to do is to go to the control panel > Computer Management > Services and manually start the SQL express or SQL server. It worked for me.

Good luck.

How can I insert vertical blank space into an html document?

i always use this cheap word for vertical spaces.

    <p>Q1</p>
    <br>
    <p>Q2</p>

Merging dictionaries in C#

Merging using an EqualityComparer that maps items for comparison to a different value/type. Here we will map from KeyValuePair (item type when enumerating a dictionary) to Key.

public class MappedEqualityComparer<T,U> : EqualityComparer<T>
{
    Func<T,U> _map;

    public MappedEqualityComparer(Func<T,U> map)
    {
        _map = map;
    }

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

    public override int GetHashCode(T obj)
    {
        return _map(obj).GetHashCode();
    }
}

Usage:

// if dictA and dictB are of type Dictionary<int,string>
var dict = dictA.Concat(dictB)
                .Distinct(new MappedEqualityComparer<KeyValuePair<int,string>,int>(item => item.Key))
                .ToDictionary(item => item.Key, item=> item.Value);

Python and JSON - TypeError list indices must be integers not str

You can simplify your code down to

url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
    print player['firstName']

You were trying to access a list element using dictionary syntax. the equivalent of

foo = [1, 2, 3, 4]
foo["1"]

It can be confusing when you have lists of dictionaries and keeping the nesting in order.

Cannot execute script: Insufficient memory to continue the execution of the program

You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.

I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.

(This is the same answer I provided here)

What is Node.js' Connect, Express and "middleware"?

Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.

Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

What is the most compatible way to install python modules on a Mac?

The most popular way to manage python packages (if you're not using your system package manager) is to use setuptools and easy_install. It is probably already installed on your system. Use it like this:

easy_install django

easy_install uses the Python Package Index which is an amazing resource for python developers. Have a look around to see what packages are available.

A better option is pip, which is gaining traction, as it attempts to fix a lot of the problems associated with easy_install. Pip uses the same package repository as easy_install, it just works better. Really the only time use need to use easy_install is for this command:

easy_install pip

After that, use:

pip install django

At some point you will probably want to learn a bit about virtualenv. If you do a lot of python development on projects with conflicting package requirements, virtualenv is a godsend. It will allow you to have completely different versions of various packages, and switch between them easily depending your needs.

Regarding which python to use, sticking with Apple's python will give you the least headaches, but If you need a newer version (Leopard is 2.5.1 I believe), I would go with the macports python 2.6.

What is the use of a private static variable in Java?

If a variable is defined as public static it can be accessed via its class name from any class.

Usually functions are defined as public static which can be accessed just by calling the implementing class name.

A very good example of it is the sleep() method in Thread class

Thread.sleep(2500);

If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you). The difference between private var_name and private static var_name is that private static variables can be accessed only by static methods of the class while private variables can be accessed by any method of that class(except static methods)

A very good example of it is while defining database connections or constants which require declaring variable as private static .

Another common example is

private static int numberOfCars=10;

public static int returnNumber(){

return numberOfCars;

}

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Why does SSL handshake give 'Could not generate DH keypair' exception?

I use coldfusion 8 on JDK 1.6.45 and had problems with giving me just red crosses instead of images, and also with cfhttp not able to connect to the local webserver with ssl.

my test script to reproduce with coldfusion 8 was

<CFHTTP URL="https://www.onlineumfragen.com" METHOD="get" ></CFHTTP>
<CFDUMP VAR="#CFHTTP#">

this gave me the quite generic error of " I/O Exception: peer not authenticated." I then tried to add certificates of the server including root and intermediate certificates to the java keystore and also the coldfusion keystore, but nothing helped. then I debugged the problem with

java SSLPoke www.onlineumfragen.com 443

and got

javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair

and

Caused by: java.security.InvalidAlgorithmParameterException: Prime size must be
multiple of 64, and can only range from 512 to 1024 (inclusive)
    at com.sun.crypto.provider.DHKeyPairGenerator.initialize(DashoA13*..)
    at java.security.KeyPairGenerator$Delegate.initialize(KeyPairGenerator.java:627)
    at com.sun.net.ssl.internal.ssl.DHCrypt.<init>(DHCrypt.java:107)
    ... 10 more

I then had the idea that the webserver (apache in my case) had very modern ciphers for ssl and is quite restrictive (qualys score a+) and uses strong diffie hellmann keys with more than 1024 bits. obviously, coldfusion and java jdk 1.6.45 can not manage this. Next step in the odysee was to think of installing an alternative security provider for java, and I decided for bouncy castle. see also http://www.itcsolutions.eu/2011/08/22/how-to-use-bouncy-castle-cryptographic-api-in-netbeans-or-eclipse-for-java-jse-projects/

I then downloaded the

bcprov-ext-jdk15on-156.jar

from http://www.bouncycastle.org/latest_releases.html and installed it under C:\jdk6_45\jre\lib\ext or where ever your jdk is, in original install of coldfusion 8 it would be under C:\JRun4\jre\lib\ext but I use a newer jdk (1.6.45) located outside the coldfusion directory. it is very important to put the bcprov-ext-jdk15on-156.jar in the \ext directory (this cost me about two hours and some hair ;-) then I edited the file C:\jdk6_45\jre\lib\security\java.security (with wordpad not with editor.exe!) and put in one line for the new provider. afterwards the list looked like

#
# List of providers and their preference orders (see above):
#
security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
security.provider.2=sun.security.provider.Sun
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=com.sun.net.ssl.internal.ssl.Provider
security.provider.5=com.sun.crypto.provider.SunJCE
security.provider.6=sun.security.jgss.SunProvider
security.provider.7=com.sun.security.sasl.Provider
security.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.9=sun.security.smartcardio.SunPCSC
security.provider.10=sun.security.mscapi.SunMSCAPI

(see the new one in position 1)

then restart coldfusion service completely. you can then

java SSLPoke www.onlineumfragen.com 443 (or of course your url!)

and enjoy the feeling... and of course

what a night and what a day. Hopefully this will help (partially or fully) to someone out there. if you have questions, just mail me at info ... (domain above).

How do you remove the title text from the Android ActionBar?

In your Manifest

<activity android:name=".ActivityHere"
     android:label="">

T-SQL CASE Clause: How to specify WHEN NULL

The issue is that NULL is not considered to be equal to anything even not to itself, but the strange part is that is also not not equal to itself.

Consider the following statements (which is BTW illegal in SQL Server T-SQL but is valid in My-SQL, however this is what ANSI defines for null, and can be verified even in SQL Server by using case statements etc.)

SELECT NULL = NULL -- Results in NULL

SELECT NULL <> NULL -- Results in NULL

So there is no true/false answer to the question, instead the answer is also null.

This has many implications, for example in

  1. CASE statements, in which any null value will always use the ELSE clause unless you use explicitly the WHEN IS NULL condition (NOT the WHEN NULL condition )
  2. String concatenation, as
    SELECT a + NULL -- Results in NULL
  3. In a WHERE IN or WHERE NOT IN clause, as if you want correct results make sure in the correlated sub-query to filter out any null values.

One can override this behavior in SQL Server by specifying SET ANSI_NULLS OFF, however this is NOT recommended and should not be done as it can cause many issues, simply because deviation of the standard.

(As a side note, in My-SQL there is an option to use a special operator <=> for null comparison.)

In comparison, in general programming languages null is treated is a regular value and is equal to itself, however the is the NAN value which is also not equal to itself, but at least it returns 'false' when comparing it to itself, (and when checking for not equals different programming languages have different implementations).

Note however that in the Basic languages (i.e. VB etc.) there is no 'null' keyword and instead one uses the 'Nothing' keyword, which cannot be used in direct comparison and instead one needs to use 'IS' as in SQL, however it is in fact equal to itself (when using indirect comparisons).

Call a stored procedure with another in Oracle

Calling one procedure from another procedure:

One for a normal procedure:

CREATE OR REPLACE SP_1() AS 
BEGIN
/*  BODY */
END SP_1;

Calling procedure SP_1 from SP_2:

CREATE OR REPLACE SP_2() AS
BEGIN
/* CALL PROCEDURE SP_1 */
SP_1();
END SP_2;

Call a procedure with REFCURSOR or output cursor:

CREATE OR REPLACE SP_1
(
oCurSp1 OUT SYS_REFCURSOR
) AS
BEGIN
/*BODY */
END SP_1;

Call the procedure SP_1 which will return the REFCURSOR as an output parameter

CREATE OR REPLACE SP_2 
(
oCurSp2 OUT SYS_REFCURSOR
) AS `enter code here`
BEGIN
/* CALL PROCEDURE SP_1 WITH REF CURSOR AS OUTPUT PARAMETER */
SP_1(oCurSp2);
END SP_2;

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.

Paste this in your custom css file:

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

I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

I faced this problem even after using webdriver manager. I was able to resolve the issue after specifying the exact version of chromedriver that I needed in the webddriver manager.

I was using chrome version 84 and the webdriver manager was installing the latest version of chromedriver, which was 85.0.4183.38.

I made webdriver manager to open the chromedriver version 84.0.4147.30 by writing the following command.

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager(84.0.4147.30).install())

mongodb: insert if not exists

I don't think mongodb supports this type of selective upserting. I have the same problem as LeMiz, and using update(criteria, newObj, upsert, multi) doesn't work right when dealing with both a 'created' and 'updated' timestamp. Given the following upsert statement:

update( { "name": "abc" }, 
        { $set: { "created": "2010-07-14 11:11:11", 
                  "updated": "2010-07-14 11:11:11" }},
        true, true ) 

Scenario #1 - document with 'name' of 'abc' does not exist: New document is created with 'name' = 'abc', 'created' = 2010-07-14 11:11:11, and 'updated' = 2010-07-14 11:11:11.

Scenario #2 - document with 'name' of 'abc' already exists with the following: 'name' = 'abc', 'created' = 2010-07-12 09:09:09, and 'updated' = 2010-07-13 10:10:10. After the upsert, the document would now be the same as the result in scenario #1. There's no way to specify in an upsert which fields be set if inserting, and which fields be left alone if updating.

My solution was to create a unique index on the critera fields, perform an insert, and immediately afterward perform an update just on the 'updated' field.

Syntax error near unexpected token 'fi'

The first problem with your script is that you have to put a space after the [.
Type type [ to see what is really happening. It should tell you that [ is an alias to test command, so [ ] in bash is not some special syntax for conditionals, it is just a command on its own. What you should prefer in bash is [[ ]]. This common pitfall is greatly explained here and here.

Another problem is that you didn't quote "$f" which might become a problem later. This is explained here

You can use arithmetic expressions in if, so you don't have to use [ ] or [[ ]] at all in some cases. More info here

Also there's no need to use \n in every echo, because echo places newlines by default. If you want TWO newlines to appear, then use echo -e 'start\n' or echo $'start\n' . This $'' syntax is explained here

To make it completely perfect you should place -- before arbitrary filenames, otherwise rm might treat it as a parameter if the file name starts with dashes. This is explained here.

So here's your script:

#!/bin/bash
echo "start"
for f in *.jpg
do
    fname="${f##*/}"
    echo "fname is $fname"
    if (( fname % 2 == 1 )); then
        echo "removing $fname"
        rm -- "$f"
    fi
done

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

nginx: send all requests to a single html page

Your original rewrite should almost work. I'm not sure why it would be redirecting, but I think what you really want is just

rewrite ^ /base.html break;

You should be able to put that in a location or directly in the server.

Text not wrapping in p tag

EASY

p{
    word-wrap: break-word;
}

IF function with 3 conditions

Using INDEX and MATCH for binning. Easier to maintain if we have more bins.

=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))

enter image description here

Get the current cell in Excel VB

If you're trying to grab a range with a dynamically generated string, then you just have to build the string like this:

Range(firstcol & firstrow & ":" & secondcol & secondrow).Select

Invoking a jQuery function after .each() has completed

I found a lot of responses dealing with arrays but not with a json object. My solution was simply to iterate through the object once while incrementing a counter and then when iterating through the object to perform your code you can increment a second counter. Then you simply compare the two counters together and get your solution. I know it's a little clunky but I haven't found a more elegant solution so far. This is my example code:

var flag1 = flag2 = 0;

$.each( object, function ( i, v ) { flag1++; });

$.each( object, function ( ky, val ) {

     /*
        Your code here
     */
     flag2++;
});

if(flag1 === flag2) {
   your function to call at the end of the iteration
}

Like I said, it's not the most elegant, but it works and it works well and I haven't found a better solution just yet.

Cheers, JP

How to send a html email with the bash command "sendmail"?

To follow up on the previous answer using mail :

Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:

{ echo -e "<pre>"
echo "Descriptive text here."
shell_command_1_here
another_shell_command
cat <<EOF

This is the ending text.
</pre><br>
</div>
EOF
} | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]

You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.

Use Font Awesome Icon in Placeholder

Teocci solution is as simple as it can be, thus, no need to add any CSS, just add class="fas" for Font Awesome 5, since it adds proper CSS font declaration to the element.

Here's an example for search box within Bootstrap navbar, with search icon added to the both input-group and placeholder (for the sake of demontration, of course, no one would use both at the same time). Image: https://i.imgur.com/v4kQJ77.png "> Code:

<form class="form-inline my-2 my-lg-0">
    <div class="input-group mb-3">
        <div class="input-group-prepend">
            <span class="input-group-text"><i class="fas fa-search"></i></span>
        </div>
        <input type="text" class="form-control fas text-right" placeholder="&#xf002;" aria-label="Search string">
        <div class="input-group-append">
            <button class="btn btn-success input-group-text bg-success text-white border-0">Search</button>
        </div>
    </div>
</form>

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

Correlation heatmap

The code below will produce this plot:

enter image description here

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]

# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]

# A dataframe
df = pd.DataFrame(data)

def CorrMtx(df, dropDuplicates = True):

    # Your dataset is already a correlation matrix.
    # If you have a dateset where you need to include the calculation
    # of a correlation matrix, just uncomment the line below:
    # df = df.corr()

    # Exclude duplicate correlations by masking uper right values
    if dropDuplicates:    
        mask = np.zeros_like(df, dtype=np.bool)
        mask[np.triu_indices_from(mask)] = True

    # Set background color / chart style
    sns.set_style(style = 'white')

    # Set up  matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))

    # Add diverging colormap from red to blue
    cmap = sns.diverging_palette(250, 10, as_cmap=True)

    # Draw correlation plot with or without duplicates
    if dropDuplicates:
        sns.heatmap(df, mask=mask, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
    else:
        sns.heatmap(df, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)


CorrMtx(df, dropDuplicates = False)

I put this together after it was announced that the outstanding seaborn corrplot was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of 0.95173379, try changing to -0.95173379 and you'll get this:

enter image description here

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

What is the email subject length limit?

after some test: If you send an email to an outlook client, and the subject is >77 chars, and it needs to use "=?ISO" inside the subject (in my case because of accents) then OutLook will "cut" the subject in the middle of it and mesh it all that comes after, including body text, attaches, etc... all a mesh!

I have several examples like this one:

Subject: =?ISO-8859-1?Q?Actas de la obra N=BA.20100154 (Expediente N=BA.20100182) "NUEVA RED FERROVIARIA.=

TRAMO=20BEASAIN=20OESTE(Pedido=20PC10/00123-125),=20BEASAIN".?=

To:

As you see, in the subject line it cutted on char 78 with a "=" followed by 2 or 3 line feeds, then continued with the rest of the subject baddly.

It was reported to me from several customers who all where using OutLook, other email clients deal with those subjects ok.

If you have no ISO on it, it doesn't hurt, but if you add it to your subject to be nice to RFC, then you get this surprise from OutLook. Bit if you don't add the ISOs, then iPhone email will not understand it(and attach files with names using such characters will not work on iPhones).

How do I create delegates in Objective-C?

lets say you have a class that you developed and want to declare a delegate property to be able to notify it when some event happens :

@class myClass;

@protocol myClassDelegate <NSObject>

-(void)myClass:(MyClass*)myObject requiredEventHandlerWithParameter:(ParamType*)param;

@optional
-(void)myClass:(MyClass*)myObject optionalEventHandlerWithParameter:(ParamType*)param;

@end


@interface MyClass : NSObject

@property(nonatomic,weak)id< MyClassDelegate> delegate;

@end

so you declare a protocol in MyClass header file (or a separate header file) , and declare the required/optional event handlers that your delegate must/should implement , then declare a property in MyClass of type (id< MyClassDelegate>) which means any objective c class that conforms to the protocol MyClassDelegate , you'll notice that the delegate property is declared as weak , this is very important to prevent retain cycle (most often the delegate retains the MyClass instance so if you declared the delegate as retain, both of them will retain each other and neither of them will ever be released).

you will notice also that the protocol methods passes the MyClass instance to the delegate as parameter , this is best practice in case the delegate want to call some methods on MyClass instance and also helps when the delegate declares itself as MyClassDelegate to multiple MyClass instances , like when you have multiple UITableView's instances in your ViewController and declares itself as a UITableViewDelegate to all of them.

and inside your MyClass you notify the delegate with declared events as follows :

if([_delegate respondsToSelector:@selector(myClass: requiredEventHandlerWithParameter:)])
{
     [_delegate myClass:self requiredEventHandlerWithParameter:(ParamType*)param];
}

you first check if your delegate responds to the protocol method that you are about to call in case the delegate doesn't implement it and the app will crash then (even if the protocol method is required).

One time page refresh after first page load

Please try with the code below

var windowWidth = $(window).width();

$(window).resize(function() {
    if(windowWidth != $(window).width()){
    location.reload();

    return;
    }
});

background-image: url("images/plaid.jpg") no-repeat; wont show up

Most important

Keep in mind that relative URLs are resolved from the URL of your stylesheet.

So it will work if folder images is inside the stylesheets folder.

From you description you would need to change it to either

url("../images/plaid.jpg")

or

url("/images/plaid.jpg") 

Additional 1

Also you cannot have no selector..

CSS is applied through selectors..


Additional 2

You should use either the shorthand background to pass multiple values like this

background: url("../images/plaid.jpg") no-repeat;

or the verbose syntax of specifying each property on its own

background-image: url("../images/plaid.jpg");
background-repeat:no-repeat;

How to check if Thread finished execution

If you don't want to block the current thread by waiting/checking for the other running thread completion, you can implement callback method like this.

Action onCompleted = () => 
{  
    //On complete action
};

var thread = new Thread(
  () =>
  {
    try
    {
      // Do your work
    }
    finally
    {
      onCompleted();
    }
  });
thread.Start();

If you are dealing with controls that doesn't support cross-thread operation, then you have to invoke the callback method

this.Invoke(onCompleted);

how to generate public key from windows command prompt

ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key

Valid values for android:fontFamily and what they map to?

As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.

ie:

public class Museo500TextView extends TextView {
    public Museo500TextView(Context context, AttributeSet attrs) {
        super(context, attrs);      
        this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
    }
}

and

<my.package.views.Museo900TextView
        android:id="@+id/dialog_error_text_header"
        android:layout_width="190dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="12sp" />

Angular 5 Service to read local .json file

I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".

Just call require:

const content = require('../../path_of_your.json');

The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl property by template and the value by a require call to the actual HTML resource.

If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json:

"compilerOptions": {
  "types": ["node"],
  ...
},
...

Open new Terminal Tab from command line (Mac OS X)

osascript -e 'tell app "Terminal"
   do script "echo hello"
end tell'

This opens a new terminal and executes the command "echo hello" inside it.

How do I set the maximum line length in PyCharm?

For PyCharm 4

File >> Settings >> Editor >> Code Style: Right margin (columns)

suggestion: Take a look at other options in that tab, they're very helpful

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

Resize Cross Domain Iframe Height

You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377

yourotherdomain.html

<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
  // Size the parent iFrame
  function iframeResize() {
    var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
    parent.postMessage("resize::"+height,"*");
  }

  $(document).ready(function() {
    // Resize iframe
    setInterval(iframeResize, 1000);
  });
</script>

your website with iframe

<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
  // Listen for messages sent from the iFrame
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  eventer(messageEvent,function(e) {
    // If the message is a resize frame request
    if (e.data.indexOf('resize::') != -1) {
      var height = e.data.replace('resize::', '');
      document.getElementById('edh-iframe').style.height = height+'px';
    }
  } ,false);
</script>

Using Eloquent ORM in Laravel to perform search of database using LIKE

FYI, the list of operators (containing like and all others) is in code:

/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

protected $operators = array(
    '=', '<', '>', '<=', '>=', '<>', '!=',
    'like', 'not like', 'between', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
);

disclaimer:

Joel Larson's answer is correct. Got my upvote.

I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Using varchar(MAX) vs TEXT on SQL Server

The VARCHAR(MAX) type is a replacement for TEXT. The basic difference is that a TEXT type will always store the data in a blob whereas the VARCHAR(MAX) type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.

Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX) gives you is that it is also can be used with = and GROUP BY as any other VARCHAR column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.

In regard to if you should use LIKE to search, or if you should use Full Text Indexing and CONTAINS. This question is the same regardless of VARCHAR(MAX) or TEXT.

If you are searching large amounts of text and performance is key then you should use a Full Text Index.

LIKE is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

Display names of all constraints for a table in Oracle SQL

You need to query the data dictionary, specifically the USER_CONS_COLUMNS view to see the table columns and corresponding constraints:

SELECT *
  FROM user_cons_columns
 WHERE table_name = '<your table name>';

FYI, unless you specifically created your table with a lower case name (using double quotes) then the table name will be defaulted to upper case so ensure it is so in your query.

If you then wish to see more information about the constraint itself query the USER_CONSTRAINTS view:

SELECT *
  FROM user_constraints
 WHERE table_name = '<your table name>'
   AND constraint_name = '<your constraint name>';

If the table is held in a schema that is not your default schema then you might need to replace the views with:

all_cons_columns

and

all_constraints

adding to the where clause:

   AND owner = '<schema owner of the table>'

Possible cases for Javascript error: "Expected identifier, string or number"

This is a definitive un-answer: eliminating a tempting-but-wrong answer to help others navigate toward correct answers.

It might seem like debugging would highlight the problem. However, the only browser the problem occurs in is IE, and in IE you can only debug code that was part of the original document. For dynamically added code, the debugger just shows the body element as the current instruction, and IE claims the error happened on a huge line number.

Here's a sample web page that will demonstrate this problem in IE:

<html>
<head>
<title>javascript debug test</title>
</head>
<body onload="attachScript();">
<script type="text/javascript">
function attachScript() {
   var s = document.createElement("script");
   s.setAttribute("type", "text/javascript");
   document.body.appendChild(s);
   s.text = "var a = document.getElementById('nonexistent'); alert(a.tagName);"
}
</script>
</body>

This yielded for me the following error:

Line: 54654408
Error: Object required

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

BAT file to map to network drive without running as admin

This .vbs code creates a .bat file with the current mapped network drives. Then, just put the created file into the machine which you want to re-create the mappings and double-click it. It will try to create all mappings using the same drive letters (errors can occur if any letter is in use). This method also can be used as a backup of the current mappings. Save the code bellow as a .vbs file (e.g. Mappings.vbs) and double-click it.

' ********** My Code **********
Set wshShell = CreateObject( "WScript.Shell" )

' ********** Get ComputerName
strComputer = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )

' ********** Get Domain 
sUserDomain = createobject("wscript.network").UserDomain

Set Connect = GetObject("winmgmts://"&strComputer)
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections

' ********** Current Path
sCurrentPath = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

' ********** Blank the report message
strMsg = ""

' ********** Set objects 
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objWbem = GetObject("winmgmts:")
Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")

' ********** Get UserName
sUser = CreateObject("WScript.Network").UserName

' ********** Print user and computer
'strMsg = strMsg & "    User: " & sUser & VbCrLf
'strMsg = strMsg & "Computer: " & strComputer & VbCrLf & VbCrLf

strMsg = strMsg & "###  COPIED FROM " & strComputer & " ###" & VbCrLf& VbCrLf
strMsg = strMsg & "@echo off" & vbCrLf

For i = 0 to oDrives.Count - 1 Step 2
    strMsg = strMsg & "net use " & oDrives.Item(i) & " " & oDrives.Item(i+1) & " /user:" & sUserDomain & "\" & sUser & " /persistent:yes" & VbCrLf
Next
strMsg = strMsg & ":exit" & VbCrLf
strMsg = strMsg & "@pause" & VbCrLf

' ********** write the file to disk.
strDirectory = sCurrentPath 
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
    ' Procede
Else
    Set objFolder = objFSO.CreateFolder(strDirectory)
End if

' ********** Calculate date serial for filename **********
intMonth = month(now)
if intMonth < 10 then
    strThisMonth = "0" & intMonth
else
    strThisMonth = intMOnth
end if
intDay = Day(now)
if intDay < 10 then
    strThisDay = "0" & intDay
else
    strThisDay = intDay
end if
strFilenameDateSerial = year(now) & strThisMonth & strThisDay
    sFileName = strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".bat"
    Set objFile = objFSO.CreateTextFile(sFileName,True) 
objFile.Write strMsg & vbCrLf

' ********** Ask to view file
strFinish = "End: A .bat was generated. " & VbCrLf & "Copy the generated file  (" & sFileName & ")  into the machine where you want to recreate the mappings and double-click it." & VbCrLf & VbCrLf 
MsgBox(strFinish)

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

Why do we have to normalize the input for an artificial neural network?

When you use unnormalized input features, the loss function is likely to have very elongated valleys. When optimizing with gradient descent, this becomes an issue because the gradient will be steep with respect some of the parameters. That leads to large oscillations in the search space, as you are bouncing between steep slopes. To compensate, you have to stabilize optimization with small learning rates.

Consider features x1 and x2, where range from 0 to 1 and 0 to 1 million, respectively. It turns out the ratios for the corresponding parameters (say, w1 and w2) will also be large.

Normalizing tends to make the loss function more symmetrical/spherical. These are easier to optimize because the gradients tend to point towards the global minimum and you can take larger steps.

MySQL: Set user variable from result of query

Just add parenthesis around the query:

set @user = 123456;
set @group = (select GROUP from USER where User = @user);
select * from USER where GROUP = @group;

error, string or binary data would be truncated when trying to insert

In one of the INSERT statements you are attempting to insert a too long string into a string (varchar or nvarchar) column.

If it's not obvious which INSERT is the offender by a mere look at the script, you could count the <1 row affected> lines that occur before the error message. The obtained number plus one gives you the statement number. In your case it seems to be the second INSERT that produces the error.

Named parameters in JDBC

Plain vanilla JDBC does not support named parameters.

If you are using DB2 then using DB2 classes directly:

  1. Using named parameter markers with PreparedStatement objects
  2. Using named parameter markers with CallableStatement objects

How do I mock a class without an interface?

The standard mocking frameworks are creating proxy classes. This is the reason why they are technically limited to interfaces and virtual methods.

If you want to mock 'normal' methods as well, you need a tool that works with instrumentation instead of proxy generation. E.g. MS Moles and Typemock can do that. But the former has a horrible 'API', and the latter is commercial.

jQuery Mobile Page refresh mechanism

I posted that in jQuery forums (I hope it can help):

Diving into the jQM code i've found this solution. I hope it can help other people:

To refresh a dynamically modified page:

function refreshPage(page){
    // Page refresh
    page.trigger('pagecreate');
    page.listview('refresh');
}

It works even if you create new headers, navbars or footers. I've tested it with jQM 1.0.1.

Interface naming in Java

As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:

class Number implements Comparable{...}  
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}

Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.

Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?

I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

I'm not sure what you're trying to do: If you added the file via

svn add myfile

you only told svn to put this file into your repository when you do your next commit. There's no change to the repository before you type an

svn commit

If you delete the file before the commit, svn has it in its records (because you added it) but cannot send it to the repository because the file no longer exist.

So either you want to save the file in the repository and then delete it from your working copy: In this case try to get your file back (from the trash?), do the commit and delete the file afterwards via

svn delete myfile
svn commit

If you want to undo the add and just throw the file away, you can to an

svn revert myfile

which tells svn (in this case) to undo the add-Operation.

EDIT

Sorry, I wasn't aware that you're using the "Versions" GUI client for Max OSX. So either try a revert on the containing directory using the GUI or jump into the cold water and fire up your hidden Mac command shell :-) (it's called "Terminal" in the german OSX, no idea how to bring it up in the english version...)

setOnItemClickListener on custom ListView

Sample Code:

ListView list = (ListView) findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      Object listItem = list.getItemAtPosition(position);
   } 
});

In the sample code above, the listItem should contain the selected data for the textView.

CORS: credentials mode is 'include'

If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.

Inside of ConfigureServices

services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>
    {
        options.WithOrigins("https://localhost:xxxx");
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
    });
});

services.AddMvc();

Then inside of Configure:

app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
    {
        // Routing code here
    });

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

Is floating point math broken?

My workaround:

function add(a, b, precision) {
    var x = Math.pow(10, precision || 2);
    return (Math.round(a * x) + Math.round(b * x)) / x;
}

precision refers to the number of digits you want to preserve after the decimal point during addition.

NameError: uninitialized constant (rails)

In my case, I named a column name type and tried to set its value as UNPREPARED. And I got an error message like this:

Caused by: api_1 | NameError: uninitialized constant UNPREPARED

In rails, column type is reserved:

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'UNPREPARED'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Pl ease rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Food.inheritance_column to use another column for that information

You don't have permission to access / on this server

Fist check that apache is running. service httpd restart for restarting

CentOS 6 comes with SELinux activated, so, either change the policy or disabled it by editing /etc/sysconfig/selinux setting SELINUX=disabled. Then restart

Then check locally (from centos) if apache is working.

Change the row color in DataGridView based on the quantity of a cell value

This might be helpful

  1. Use the "RowPostPaint" event
  2. The name of the column is NOT the "Header" of the column. You have to go to the properties for the DataGridView => then select the column => then look for the "Name" property

I converted this from C# ('From: http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=74)

    Private Sub dgv_EmployeeTraining_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) 
    Handles dgv_EmployeeTraining.RowPostPaint

    If e.RowIndex < Me.dgv_EmployeeTraining.RowCount - 1 Then
        Dim dgvRow As DataGridViewRow = Me.dgv_EmployeeTraining.Rows(e.RowIndex)

    '<== This is the header Name
        'If CInt(dgvRow.Cells("EmployeeStatus_Training_e26").Value) <> 2 Then  


    '<== But this is the name assigned to it in the properties of the control
        If CInt(dgvRow.Cells("DataGridViewTextBoxColumn15").Value.ToString) <> 2 Then   

            dgvRow.DefaultCellStyle.BackColor = Color.FromArgb(236, 236, 255)

        Else
            dgvRow.DefaultCellStyle.BackColor = Color.LightPink

        End If

    End If

End Sub

How to build an android library with Android Studio and gradle?

Here is my solution for mac users I think it work for window also:

First go to your Android Studio toolbar

Build > Make Project (while you guys are online let it to download the files) and then

Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then

Run your app that is done it will launch your emulator and configure it then run it!

That is it!!! Happy Coding guys!!!!!!!

Where is nodejs log file?

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

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

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

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

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

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

module.exports = logger;

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

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

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

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

How to display two digits after decimal point in SQL Server

You can also use below code which helps me:

select convert(numeric(10,2), column_name) as Total from TABLE_NAME

where Total is alias of the field you want.

PHP Get Highest Value from Array

Don't sort the array to get the largest value.

Get the max value:

$value = max($array);

Get the corresponding key:

$key = array_search($value, $array);

Determine whether an array contains a value

Array.prototype.includes()

In ES2016, there is Array.prototype.includes().

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

Example

["Sam", "Great", "Sample", "High"].includes("Sam"); // true

Support

According to kangax and MDN, the following platforms are supported:

  • Chrome 47
  • Edge 14
  • Firefox 43
  • Opera 34
  • Safari 9
  • Node 6

Support can be expanded using Babel (using babel-polyfill) or core-js. MDN also provides a polyfill:

if (![].includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
    'use strict';
    var O = Object(this);
    var len = parseInt(O.length) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1]) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) {k = 0;}
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  };
}

"Multiple definition", "first defined here" errors

You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123();

#endif

commands.c

#include "commands.h"

void f123()
{
    /* code */
}

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

MySQL: Large VARCHAR vs. TEXT?

The preceding answers don't insist enough on the main problem: even in very simple queries like

(SELECT t2.* FROM t1, t2 WHERE t2.id = t1.id ORDER BY t1.id) 

a temporary table can be required, and if a VARCHAR field is involved, it is converted to a CHAR field in the temporary table. So if you have in your table say 500 000 lines with a VARCHAR(65000) field, this column alone will use 6.5*5*10^9 byte. Such temp tables can't be handled in memory and are written to disk. The impact can be expected to be catastrophic.

Source (with metrics): https://nicj.net/mysql-text-vs-varchar-performance/ (This refers to the handling of TEXT vs VARCHAR in "standard"(?) MyISAM storage engine. It may be different in others, e.g., InnoDB.)

Use xml.etree.ElementTree to print nicely formatted xml files

You can use the function toprettyxml() from xml.dom.minidom in order to do that:

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
<html>
<head>
  <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
                alert($event);
          }
        });     
  </script>  
</head>
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
  </div>
</body>
</html>

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

I had similar issues with the threads being started in Spring bean. These threads were not closing properly after i called executor.shutdownNow() in @PreDestroy method. So the solution for me was to let the thread finsih with IO already started and start no more IO, once @PreDestroy was called. And here is the @PreDestroy method. For my application the wait for 1 second was acceptable.

@PreDestroy
    public void beandestroy() {
        this.stopThread = true;
        if(executorService != null){
            try {
                // wait 1 second for closing all threads
                executorService.awaitTermination(1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

Here I have explained all the issues faced while trying to close threads.http://programtalk.com/java/executorservice-not-shutting-down/

The first day of the current month in php using date_modify as DateTime object

All those special php expressions, in spirit of first day of ... are great, though they go out of my head time and again.

So I decided to build a couple of basic datetime abstractions and tons of specific implementation which are auto-completed by any IDE. The point is to find what-kind of things. Like, today, now, the first day of a previous month, etc. All of those things I've listed are datetimes. Hence, there is an interface or abstract class called ISO8601DateTime, and specific datetimes which implement it.

The code in your particular case looks like that:

(new TheFirstDayOfThisMonth(new Now()))->value();

For more about this approach, take a look at this entry.

Can RDP clients launch remote applications and not desktops

This is called RemoteApp. To use it you need to install Terminal Services, which is now called Remote Desktop Services.

https://social.technet.microsoft.com/wiki/contents/articles/10817.publishing-remoteapps-in-windows-server-2012.aspx

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

You are definitely missing a small thing and that is you are not setting a default value:

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

So the code would look like:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

Explanation: If you want to change the time zone, set the default time zone using TimeZone.setDefault()

Slack clean all messages (~8K) in a channel

For anyone else who doesn't need to do it programmatic, here's a quick way:

(probably for paid users only)

  1. Open the channel in web or the desktop app, and click the cog (top right).
  2. Choose "Additional options..." to bring up the archival menu. notes
  3. Select "Set the channel message retention policy".
  4. Set "Retain all messages for a specific number of days".
  5. All messages older than this time are deleted permanently!

I usually set this option to "1 day" to leave the channel with some context, then I go back into the above settings, and set it's retention policy back to "default" to go continue storing them from now-on.

Notes:
Luke points out: If the option is hidden: you have to go to global workspace Admin settings, Message Retention & Deletion, and check "Let workspace members override these settings"

XSLT - How to select XML Attribute by Attribute?

Just remove the slash after Data and prepend the root:

<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

What's the quickest way to multiply multiple cells by another number?

Put the number you want to multiply by in a cell that is not in your range. Select the cell and "Copy" it to the clipboard. Next, select the Range A1:D5, and from the menu choose Edit|Paste Special. A dialog box will appear. In the "Operation" area, select "Multiply" and click "OK".

No connection could be made because the target machine actively refused it 127.0.0.1

If you have this while Fiddler is running -> in Fiddler, go to 'Rules' and disable 'Automatically Authenticate' and it should work again.

How should a model be structured in MVC?

Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.

You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.

It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):

class Database {
   protected $_conn;

   public function __construct($connection) {
       $this->_conn = $connection;
   }

   public function ExecuteObject($sql, $data) {
       // stuff
   }
}

abstract class Model {
   protected $_db;

   public function __construct(Database $db) {
       $this->_db = $db;
   }
}

class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}

$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');

Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.

Java double comparison epsilon

You do NOT use double to represent money. Not ever. Use java.math.BigDecimal instead.

Then you can specify how exactly to do rounding (which is sometimes dictated by law in financial applications!) and don't have to do stupid hacks like this epsilon thing.

Seriously, using floating point types to represent money is extremely unprofessional.

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

Error: [ng:areq] from angular controller

I had this error too, I changed the code like this then it worked.

html

 <html ng-app="app">

   <div ng-controller="firstCtrl">
       ...
   </div>

 </html>

app.js

(function(){

    var app = angular.module('app',[]);

    app.controller('firstCtrl',function($scope){    
         ...
    })

})();

You have to make sure that the name in module is same as ng-app

then div will be in the scope of firstCtrl

WooCommerce: Finding the products in database

I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta table. You can find the corresponding products within wp_posts table.

How to increase font size in NeatBeans IDE?

In OS X, Netbeans 8.0

  1. Use Command + , to open the options
  2. Select Fonts & Colors tab
  3. Click the button in the Font section (button is next to the Font textbox)
  4. Change the Font, style and size as needed

enter image description here

How to set session attribute in java?

By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

HttpSession s=request.getSession()
s.setAttribute("name","value");

You can get session on an ActionSupport based Action POJO class as follows

 ActionContext ctx= ActionContext.getContext();
   Map m=ctx.getSession();
   m.put("name", value);

look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

How can I convert a string with dot and comma into a float in Python

Here's a simple way I wrote up for you. :)

>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908

if statement in ng-click

Write as

<input type="submit" ng-click="profileForm.$valid==true?updateMyProfile():''" name="submit" value="Save" class="submit" id="submit">

Free tool to Create/Edit PNG Images?

Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.

SQL Server SELECT into existing table

There are two different ways to implement inserting data from one table to another table.

For Existing Table - INSERT INTO SELECT

This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.

----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

For Non-Existing Table - SELECT INTO

This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.

----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

Ref 1 2

How do I delete NuGet packages that are not referenced by any project in my solution?

One NuGet package can reference another NuGet package. So, please be very careful about inter-package dependencies. I just uninstalled a Google map package and it subsequently uninstalled underlying packages like Newtonsoft, Entity Framework, etc.

So, manually deleting particular package from packages folder would be safer.

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

Batch file script to zip files

No external dependency on 7zip or ZIP - create a vbs script and execute:

    @ECHO Zipping
    mkdir %TEMPDIR%
    xcopy /y /s %FILETOZIP% %TEMPDIR%
    echo Set objArgs = WScript.Arguments > _zipIt.vbs
    echo InputFolder = objArgs(0) >> _zipIt.vbs
    echo ZipFile = objArgs(1) >> _zipIt.vbs
    echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
    echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
    echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
    echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
    @ECHO *******************************************
    @ECHO Zipping, please wait..
    echo wScript.Sleep 12000 >> _zipIt.vbs
    CScript  _zipIt.vbs  %TEMPDIR%  %OUTPUTZIP%
    del _zipIt.vbs
    rmdir /s /q  %TEMPDIR%

    @ECHO *******************************************
    @ECHO      ZIP Completed

Git add all subdirectories

Do,

git add .

while in the root of the repository. It will add everything. If you do git add *, it will only add the files * points to. The single dot refers to the directory.

If your directory or file wasn't added to git index/repo after the above command, remember to check if it's marked as ignored by git in .gitignore file.

Multiple files upload (Array) with CodeIgniter 2.0

function imageUpload(){
            if ($this->input->post('submitImg') && !empty($_FILES['files']['name'])) {
                $filesCount = count($_FILES['files']['name']);
                $userID = $this->session->userdata('userID');
                $this->load->library('upload');

                $config['upload_path'] = './userdp/';
                $config['allowed_types'] = 'jpg|png|jpeg';
                $config['max_size'] = '9184928';
                $config['max_width']  = '5000';
                $config['max_height']  = '5000';

                $files = $_FILES;
                $cpt = count($_FILES['files']['name']);

                for($i = 0 ; $i < $cpt ; $i++){
                    $_FILES['files']['name']= $files['files']['name'][$i];
                    $_FILES['files']['type']= $files['files']['type'][$i];
                    $_FILES['files']['tmp_name']= $files['files']['tmp_name'][$i];
                    $_FILES['files']['error']= $files['files']['error'][$i];
                    $_FILES['files']['size']= $files['files']['size'][$i];    

                    $imageName = 'image_'.$userID.'_'.rand().'.png';

                    $config['file_name'] = $imageName;

                    $this->upload->initialize($config);
                    if($this->upload->do_upload('files')){
                        $fileData = $this->upload->data(); //it return
                        $uploadData[$i]['picturePath'] = $fileData['file_name'];
                    }
                }

                if (!empty($uploadData)) {
                    $imgInsert = $this->insert_model->insertImg($uploadData);
                    $statusMsg = $imgInsert?'Files uploaded successfully.':'Some problem occurred, please try again.';
                    $this->session->set_flashdata('statusMsg',$statusMsg);
                    redirect('home/user_dash');
                }
            }
            else{
                redirect('home/user_dash');
            }
        }

How can I disable a button in a jQuery dialog from a function?

Here's the sample from the question modified to disable the button once clicked:

$(function() {
    $("#dialog").dialog({
        bgiframe: true,
        height: 'auto',
        width: 700,
        show: 'clip',
        hide: 'clip',
        modal: true,
        buttons: {
            'Add to request list': function(evt) {

                // get DOM element for button
                var buttonDomElement = evt.target;
                // Disable the button
                $(buttonDomElement).attr('disabled', true);

                $('form').submit();
            },
            'Cancel': function() {
                $(this).dialog('close');
            }
        }
    });
}

Also, the following question will also be helpful with this: How can I disable a button on a jQuery UI dialog?

How to convert UTC timestamp to device local time in android

The code in your example looks fine at first glance. BTW, if the server timestamp is in UTC (i.e. it's an epoch timestamp) then you should not have to apply the current timezone offset. In other words if the server timestamp is in UTC then you can simply get the difference between the server timestamp and the system time (System.currentTimeMillis()) as the system time is in UTC (epoch).

I would check that the timestamp coming from your server is what you expect. If the timestamp from the server does not convert into the date you expect (in the local timezone) then the difference between the timestamp and the current system time will not be what you expect.

Use Calendar to get the current timezone. Initialize a SimpleDateFormatter with the current timezone; then log the server timestamp and verify if it's the date you expect:

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

/* debug: is it local time? */
Log.d("Time zone: ", tz.getDisplayName());

/* date formatter in local timezone */
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(tz);

/* print your timestamp and double check it's the date you expect */
long timestamp = cursor.getLong(columnIndex);
String localTime = sdf.format(new Date(timestamp * 1000)); // I assume your timestamp is in seconds and you're converting to milliseconds?
Log.d("Time: ", localTime);

If the server time that is printed is not what you expect then your server time is not in UTC.

If the server time that is printed is the date that you expect then you should not have to apply the rawoffset to it. So your code would be simpler (minus all the debug logging):

long timestamp = cursor.getLong(columnIndex);
Log.d("Server time: ", timestamp);

/* log the device timezone */
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone: ", tz.getDisplayName());

/* log the system time */
Log.d("System time: ", System.currentTimeMillis());

CharSequence relTime = DateUtils.getRelativeTimeSpanString(
    timestamp * 1000,
    System.currentTimeMillis(),
    DateUtils.MINUTE_IN_MILLIS);

((TextView) view).setText(relTime);

Placeholder in IE9

I think this is what you are looking for: jquery-html5-placeholder-fix

This solution uses feature detection (via modernizr) to determine if placeholder is supported. If not, adds support (via jQuery).

Calculating Pearson correlation and significance in Python

This is a implementation of Pearson Correlation function using numpy:


def corr(data1, data2):
    "data1 & data2 should be numpy arrays."
    mean1 = data1.mean() 
    mean2 = data2.mean()
    std1 = data1.std()
    std2 = data2.std()

#     corr = ((data1-mean1)*(data2-mean2)).mean()/(std1*std2)
    corr = ((data1*data2).mean()-mean1*mean2)/(std1*std2)
    return corr

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

The idea of interfaces is generally to expose a sort of base line contract by which code that performs work on an object can be guaranteed of certain functionality provided by that object. In the case of IEnumerable<T>, that contract happens to be "you can access all of my elements one by one."

The kinds of methods that can be written based on this contract alone are many. See the Enumerable class for tons of examples.

But to zero in on just one concrete one: think about Sum. In order to sum up a bunch of items, what do you need? What contract would you require? The answer is quite simple: just a way to see every item, no more. Random access isn't necessary. Even a total count of all the items is not necessary.

To have added an indexer to the IEnumerable<T> interface would have been detrimental in two ways:

  1. Code that requires the contract described above (access to a sequence of elements), if it required the IEnumerable<T> interface, would be artificially restrictive as it could not deal with any type that did not implement an indexer, even though to deal with such a type should really be well within the capabilities of the code.
  2. Any type that wanted to expose a sequence of elements but was not appropriately equipped to provide random access by index (e.g., LinkedList<T>, Dictionary<TKey, TValue>) would now have to either provide some inefficient means of simulating indexing, or else abandon the IEnumerable<T> interface.

All this being said, considering that the purpose of an interface is to provide a guarantee of the minimum required functionality in a given scenario, I really think that the IList<T> interface is poorly designed. Or rather, the lack of an interface "between" IEnumerable<T> and IList<T> (random access, but no modification) is an unfortunate oversight in the BCL, in my opinion.

cc1plus: error: unrecognized command line option "-std=c++11" with g++

you should try this

g++-4.4 -std=c++0x or g++-4.7 -std=c++0x

Get program execution time in the shell

Use the built-in time keyword:

$ help time

time: time [-p] PIPELINE
    Execute PIPELINE and print a summary of the real time, user CPU time,
    and system CPU time spent executing PIPELINE when it terminates.
    The return status is the return status of PIPELINE.  The `-p' option
    prints the timing summary in a slightly different format.  This uses
    the value of the TIMEFORMAT variable as the output format.

Example:

$ time sleep 2
real    0m2.009s
user    0m0.000s
sys     0m0.004s

Generate war file from tomcat webapp folder

There is a way to create war file of your project from eclipse.

First a create an xml file with the following code,

Replace HistoryCheck with your project name.

<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
    <target name="default" depends="buildwar,deploy"></target>
    <target name="buildwar">
        <war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
            <exclude name="WEB-INF/**" />
            <webinf dir="war/WEB-INF/">
                <include name="**/*.jar" />
            </webinf>
        </war>
    </target>
    <target name="deploy">
        <copy file="HistoryCheck.war" todir="." />
    </target>
</project>

Now, In project explorer right click on that xml file and Run as-> ant build

You can see the war file of your project in your project folder.

Invalid argument supplied for foreach()

If you're using php7 and you want to handle only undefined errors this is the cleanest IMHO

$array = [1,2,3,4];
foreach ( $array ?? [] as $item ) {
  echo $item;
}

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

How to make a phone call using intent in Android?

You can use Intent.ACTION_DIAL instead of Intent.ACTION_CALL. This shows the dialer with the number already entered, but allows the user to decide whether to actually make the call or not. ACTION_DIAL does not require the CALL_PHONE permission.

Find all CSV files in a directory using Python

import os

path = 'C:/Users/Shashank/Desktop/'
os.chdir(path)

for p,n,f in os.walk(os.getcwd()):
    for a in f:
        a = str(a)
        if a.endswith('.csv'):
            print(a)
            print(p)

This will help to identify path also of these csv files

Reading int values from SqlDataReader

Call ToString() instead of casting the reader result.

reader[0].ToString();
reader[1].ToString();
// etc...

And if you want to fetch specific data type values (int in your case) try the following:

reader.GetInt32(index);

Skip over a value in the range function in python

for i in range(100):
    if i == 50:
        continue
    dosomething

Laravel: Auth::user()->id trying to get a property of a non-object

For Laravel 6.X you can do the following:

$user = Auth::guard(<GUARD_NAME>)->user();
$user_id = $user->id;
$full_name = $user->full_name;

Using multiple delimiters in awk

Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ().

The file content:

528(smbw)
529(smbt)
530(smbn)
10115(smbs)

The command:

awk -F"[()]" '{print $2}' filename

result:

smbw
smbt
smbn
smbs

Using awk to just print the text between []:

Use awk -F'[][]' but awk -F'[[]]' will not work.

http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html

Convert multidimensional array into single array

This simple code you can use

$array = array_column($array, 'value', 'key');

Replace image src location using CSS

Here is another dirty hack :)

.application-title > img {
display: none;
}

.application-title::before {
content: url(path/example.jpg);
}

How to combine GROUP BY, ORDER BY and HAVING

Steps for Using Group by,Having By and Order by...

Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Here's what worked for me:

ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock
service mysqld restart

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

JSON.net: how to deserialize without using the default constructor?

A bit late and not exactly suited here, but I'm gonna add my solution here, because my question had been closed as a duplicate of this one, and because this solution is completely different.

I needed a general way to instruct Json.NET to prefer the most specific constructor for a user defined struct type, so I can omit the JsonConstructor attributes which would add a dependency to the project where each such struct is defined.

I've reverse engineered a bit and implemented a custom contract resolver where I've overridden the CreateObjectContract method to add my custom creation logic.

public class CustomContractResolver : DefaultContractResolver {

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var c = base.CreateObjectContract(objectType);
        if (!IsCustomStruct(objectType)) return c;

        IList<ConstructorInfo> list = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).OrderBy(e => e.GetParameters().Length).ToList();
        var mostSpecific = list.LastOrDefault();
        if (mostSpecific != null)
        {
            c.OverrideCreator = CreateParameterizedConstructor(mostSpecific);
            c.CreatorParameters.AddRange(CreateConstructorParameters(mostSpecific, c.Properties));
        }

        return c;
    }

    protected virtual bool IsCustomStruct(Type objectType)
    {
        return objectType.IsValueType && !objectType.IsPrimitive && !objectType.IsEnum && !objectType.Namespace.IsNullOrEmpty() && !objectType.Namespace.StartsWith("System.");
    }

    private ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
    {
        method.ThrowIfNull("method");
        var c = method as ConstructorInfo;
        if (c != null)
            return a => c.Invoke(a);
        return a => method.Invoke(null, a);
    }
}

I'm using it like this.

public struct Test {
  public readonly int A;
  public readonly string B;

  public Test(int a, string b) {
    A = a;
    B = b;
  }
}

var json = JsonConvert.SerializeObject(new Test(1, "Test"), new JsonSerializerSettings {
  ContractResolver = new CustomContractResolver()
});
var t = JsonConvert.DeserializeObject<Test>(json);
t.A.ShouldEqual(1);
t.B.ShouldEqual("Test");

Proxies with Python 'Requests' module

here is my basic class in python for the requests module with some proxy configs and stopwatch !

import requests
import time
class BaseCheck():
    def __init__(self, url):
        self.http_proxy  = "http://user:pw@proxy:8080"
        self.https_proxy = "http://user:pw@proxy:8080"
        self.ftp_proxy   = "http://user:pw@proxy:8080"
        self.proxyDict = {
                      "http"  : self.http_proxy,
                      "https" : self.https_proxy,
                      "ftp"   : self.ftp_proxy
                    }
        self.url = url
        def makearr(tsteps):
            global stemps
            global steps
            stemps = {}
            for step in tsteps:
                stemps[step] = { 'start': 0, 'end': 0 }
            steps = tsteps
        makearr(['init','check'])
        def starttime(typ = ""):
            for stemp in stemps:
                if typ == "":
                    stemps[stemp]['start'] = time.time()
                else:
                    stemps[stemp][typ] = time.time()
        starttime()
    def __str__(self):
        return str(self.url)
    def getrequests(self):
        g=requests.get(self.url,proxies=self.proxyDict)
        print g.status_code
        print g.content
        print self.url
        stemps['init']['end'] = time.time()
        #print stemps['init']['end'] - stemps['init']['start']
        x= stemps['init']['end'] - stemps['init']['start']
        print x


test=BaseCheck(url='http://google.com')
test.getrequests()

Pandas: how to change all the values of a column?

You can do a column transformation by using apply

Define a clean function to remove the dollar and commas and convert your data to float.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)

Next, call it on your column like this.

data['Revenue'] = data['Revenue'].apply(clean)

HttpClient not supporting PostAsJsonAsync method C#

I know this reply is too late, I had the same issue and i was adding the System.Net.Http.Formatting.Extension Nuget, after checking here and there I found that the Nuget is added but the System.Net.Http.Formatting.dll was not added to the references, I just reinstalled the Nuget

Find oldest/youngest datetime object in a list

Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)

"for" vs "each" in Ruby

Never ever use for it may cause almost untraceable bugs.

Don't be fooled, this is not about idiomatic code or style issues. Ruby's implementation of for has a serious flaw and should not be used.

Here is an example where for introduces a bug,

class Library
  def initialize
    @ary = []
  end
  def method_with_block(&block)
    @ary << block
  end
  def method_that_uses_these_blocks
    @ary.map(&:call)
  end
end

lib = Library.new

for n in %w{foo bar quz}
  lib.method_with_block { n }
end

puts lib.method_that_uses_these_blocks

Prints

quz
quz
quz

Using %w{foo bar quz}.each { |n| ... } prints

foo
bar
quz

Why?

In a for loop the variable n is defined once and only and then that one definition is use for all iterations. Hence each blocks refer to the same n which has a value of quz by the time the loop ends. Bug!

In an each loop a fresh variable n is defined for each iteration, for example above the variable n is defined three separate times. Hence each block refer to a separate n with the correct values.

I want to truncate a text or line with ellipsis using JavaScript

HTML with JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

The result will be:

My long lo...

Cheers

G.

How can I merge two commits into one if I already started rebase?

Assuming you were in your own topic branch. If you want to merge the last 2 commits into one and look like a hero, branch off the commit just before you made the last two commits (specified with the relative commit name HEAD~2).

git checkout -b temp_branch HEAD~2

Then squash commit the other branch in this new branch:

git merge branch_with_two_commits --squash

That will bring in the changes but not commit them. So just commit them and you're done.

git commit -m "my message"

Now you can merge this new topic branch back into your main branch.

How to start/stop/restart a thread in Java?

You can't restart a thread so your best option is to save the current state of the object at the time the thread was stopped and when operations need to continue on that object you can recreate that object using the saved and then start the new thread.

These two articles Swing Worker and Concurrency may help you determine the best solution for your problem.

How to use apply a custom drawable to RadioButton?

if you want to change the only icon of radio button then you can only add android:button="@drawable/ic_launcher" to your radio button and for making sensitive on click then you have to use the selector

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/image_what_you_want_on_select_state" android:state_checked="true"/>
<item android:drawable="@drawable/image_what_you_want_on_un_select_state"    android:state_checked="false"/>


 </selector>

and set to your radio android:background="@drawable/name_of_selector"

Center text in div?

To center horizontally, use text-align:center.

To center vertically, one can only use vertical-align:middle if there is another element in the same row that it is being aligned to.
See it working here.

We use an empty span with a height of 100%, and then put the content in the next element with a vertical-align:middle.

There are other techniques such as using table-cell or putting the content in an absolutely positioned element with top, bottom, left, and right all set to zero, but they all suffer from cross browser compatibility issues.

Count the number of occurrences of each letter in string

You can use the following code.

main()
{
    int i = 0,j=0,count[26]={0};
    char ch = 97;
    char string[100]="Hello how are you buddy ?";
    for (i = 0; i < 100; i++)
    {
        for(j=0;j<26;j++)
            {
            if (tolower(string[i]) == (ch+j))
                {
                    count[j]++;
                }
        }
    }
    for(j=0;j<26;j++)
        {

            printf("\n%c -> %d",97+j,count[j]);

    }

}

Hope this helps.