Programs & Examples On #Method missing

The Ruby method that is invoked on an object when you send it a message (or call a method) that it doesn't understand.

Using Regular Expressions to Extract a Value in Java

Full example:

private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
    // create matcher for pattern p and given string
    Matcher m = p.matcher("Testing123Testing");

    // if an occurrence if a pattern was found in a given string...
    if (m.find()) {
        // ...then you can use group() methods.
        System.out.println(m.group(0)); // whole matched expression
        System.out.println(m.group(1)); // first expression from round brackets (Testing)
        System.out.println(m.group(2)); // second one (123)
        System.out.println(m.group(3)); // third one (Testing)
    }
}

Since you're looking for the first number, you can use such regexp:

^\D+(\d+).*

and m.group(1) will return you the first number. Note that signed numbers can contain a minus sign:

^\D+(-?\d+).*

bash: mkvirtualenv: command not found

On Windows 10, to create the virtual environment, I replace "pip mkvirtualenv myproject" by "mkvirtualenv myproject" and that works well.

Why should you use strncpy instead of strcpy?

This may be used in many other scenarios, where you need to copy only a portion of your original string to the destination. Using strncpy() you can copy a limited portion of the original string as opposed by strcpy(). I see the code you have put up comes from publib.boulder.ibm.com.

Send attachments with PHP Mail()?

This works for me. It also attaches multiple attachments too. easily

<?php

if ($_POST && isset($_FILES['file'])) {
    $recipient_email = "[email protected]"; //recepient
    $from_email = "info@your_domain.com"; //from email using site domain.
    $subject = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if (strlen($sender_name) < 4) {
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email');
    }
    if (strlen($sender_message) < 4) {
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("specialToken$4332"); // boundary token to be used

    if ($file_count > 0) { //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:" . $from_email . "\r\n";
        $headers .= "Reply-To: " . $sender_email . "" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($sender_message));

        //attachments
        for ($x = 0; $x < $file_count; $x++) {
            if (!empty($attachments['name'][$x])) {

                if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                        1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                        2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                        3 => "The uploaded file was only partially uploaded",
                        4 => "No file was uploaded",
                        6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .= "Content-Type: $file_type; name=" . $file_name . "\r\n";
                $body .= "Content-Disposition: attachment; filename=" . $file_name . "\r\n";
                $body .= "Content-Transfer-Encoding: base64\r\n";
                $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
                $body .= $encoded_content;
            }
        }
    } else { //send plain email otherwise
        $headers = "From:" . $from_email . "\r\n" .
                "Reply-To: " . $sender_email . "\n" .
                "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

    $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if ($sentMail) { //output success or failure messages
        die('Thank you for your email');
    } else {
        die('Could not send mail! Please check your PHP mail configuration.');
    }
}
?>

What is an ORM, how does it work, and how should I use one?

Like all acronyms it's ambiguous, but I assume they mean object-relational mapper -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as the Vietnam of CS;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)

Disabling the long-running-script message in Internet Explorer

In my case, while playing video, I needed to call a function everytime currentTime of video updates. So I used timeupdate event of video and I came to know that it was fired at least 4 times a second (depends on the browser you use, see this). So I changed it to call a function every second like this:

var currentIntTime = 0;

var someFunction = function() {
    currentIntTime++;
    // Do something here
} 
vidEl.on('timeupdate', function(){
    if(parseInt(vidEl.currentTime) > currentIntTime) {
        someFunction();
    }
});

This reduces calls to someFunc by at least 1/3 and it may help your browser to behave normally. It did for me !!!

Cannot delete or update a parent row: a foreign key constraint fails

How about this alternative I've been using: allow the foreign key to be NULL and then choose ON DELETE SET NULL.

Personally I prefer using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, but on your set up you may want a different approach. Also, NULL'ing foreign key values may latter lead complications as you won't know what exactly happened there. So this change should be in close relation to how your application code works.

Hope this helps.

DOM element to corresponding vue.js component

If you're starting with a DOM element, check for a __vue__ property on that element. Any Vue View Models (components, VMs created by v-repeat usage) will have this property.

You can use the "Inspect Element" feature in your browsers developer console (at least in Firefox and Chrome) to view the DOM properties.

Hope that helps!

How to update all MySQL table rows at the same time?

UPDATE dummy SET myfield=1 WHERE id>1;

How do I change the string representation of a Python class?

This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

'""'

and not

'"a"'

as would be expected.

EDIT: answering mchicago's comment:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

b = A('b') print b

produces

'a'

while

json.dumps({'b': b})

produces

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

jquery select element by xpath

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.

Center icon in a div - horizontally and vertically

Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:

CSS

#container {
    display: table;
    width: 300px; /* not required, just for example */
    height: 400px; /* not required, just for example */
}

#update {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

HTML

<div id="container">
    <a id="update" href="#">
        <i class="icon-refresh"></i>
    </a>
</div>

JSFiddle

Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell display property works.

Why do we have to override the equals() method in Java?

From the article Override equals and hashCode in Java:

Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.

Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:

many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same

Integer wrapper class overrides equals to perform numerical comparison etc.

How can I make a SQL temp table with primary key and auto-incrementing field?

you dont insert into identity fields. You need to specify the field names and use the Values clause

insert into #tmp (AssignedTo, field2, field3) values (value, value, value)

If you use do a insert into... select field field field it will insert the first field into that identity field and will bomb

SQL query question: SELECT ... NOT IN

SELECT Reservations.idCustomer FROM Reservations (nolock)
LEFT OUTER JOIN @reservations ExcludedReservations (nolock) ON Reservations.idCustomer=ExcludedReservations.idCustomer AND DATEPART(hour, ExcludedReservations.insertDate) < 2
WHERE ExcludedReservations.idCustomer IS NULL AND Reservations.idCustomer IS NOT NULL
GROUP BY Reservations.idCustomer

[Update: Added additional criteria to handle idCustomer being NULL, which was apparently the main issue the original poster had]

Catch KeyError in Python

I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(e.message)

Is there a way to specify how many characters of a string to print out using printf()?

In C++, I do it in this way:

char *buffer = "My house is nice";
string showMsgStr(buffer, buffer + 5);
std::cout << showMsgStr << std::endl;

Please note this is not safe because when passing the second argument I can go beyond the size of the string and generate a memory access violation. You have to implement your own check for avoiding this.

JavaScript blob filename without link

This is my solution. From my point of view, you can not bypass the <a>.

_x000D_
_x000D_
function export2json() {_x000D_
  const data = {_x000D_
    a: '111',_x000D_
    b: '222',_x000D_
    c: '333'_x000D_
  };_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(_x000D_
    new Blob([JSON.stringify(data, null, 2)], {_x000D_
      type: "application/json"_x000D_
    })_x000D_
  );_x000D_
  a.setAttribute("download", "data.json");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2json()">Export data to json file</button>
_x000D_
_x000D_
_x000D_

package javax.mail and javax.mail.internet do not exist

  1. Download the Java mail jars.

  2. Extract the downloaded file.

  3. Copy the ".jar" file and paste it into ProjectName\WebContent\WEB-INF\lib folder

  4. Right click on the Project and go to Properties

  5. Select Java Build Path and then select Libraries

  6. Add JARs...

  7. Select the .jar file from ProjectName\WebContent\WEB-INF\lib and click OK

    that's all

Including another class in SCSS

@extend .myclass;
@extend #{'.my-class'};

MVC Return Partial View as JSON

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

I had the same issue with a .tgz file .

It was just about the location of the file. Ensure the file is in the same directory of the Dockerfile.

Also ensure the .dockerignore file directory doesn't exclude the file regex pattern.

@import vs #import - iOS 7

History:

#include => #import => .pch => @import

[#include vs #import]
[.pch - Precompiled header]

Module - @import

Product Name == Product Module Name 

@import module declaration says to compiler to load a precompiled binary of framework which decrease a building time. Modular Framework contains .modulemap[About]

If module feature is enabled in Xcode project #include and #import directives are automatically converted to @import that brings all advantages

enter image description here

AngularJS: How to run additional code after AngularJS has rendered a template?

Finally i found the solution, i was using a REST service to update my collection. In order to convert datatable jquery is the follow code:

$scope.$watchCollection( 'conferences', function( old, nuew ) {
        if( old === nuew ) return;
        $( '#dataTablex' ).dataTable().fnDestroy();
        $timeout(function () {
                $( '#dataTablex' ).dataTable();
        });
    });

Best way to create unique token in Rails?

If you want something that will be unique you can use something like this:

string = (Digest::MD5.hexdigest "#{ActiveSupport::SecureRandom.hex(10)}-#{DateTime.now.to_s}")

however this will generate string of 32 characters.

There is however other way:

require 'base64'

def after_create
update_attributes!(:token => Base64::encode64(id.to_s))
end

for example for id like 10000, generated token would be like "MTAwMDA=" (and you can easily decode it for id, just make

Base64::decode64(string)

WPF global exception handler

You can handle the AppDomain.UnhandledException event

EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException

Pipe output and capture exit status in Bash

Dumb solution: Connecting them through a named pipe (mkfifo). Then the command can be run second.

 mkfifo pipe
 tee out.txt < pipe &
 command > pipe
 echo $?

How can I enable MySQL's slow query log without restarting MySQL?

This should work on mysql > 5.5

SHOW VARIABLES LIKE '%long%';

SET GLOBAL long_query_time = 1;

What is the proper way to re-throw an exception in C#?

I know this is an old question, but I'm going to answer it because I have to disagree with all the answers here.

Now, I'll agree that most of the time you either want to do a plain throw, to preserve as much information as possible about what went wrong, or you want to throw a new exception that may contain that as an inner-exception, or not, depending on how likely you are to want to know about the inner events that caused it.

There is an exception though. There are several cases where a method will call into another method and a condition that causes an exception in the inner call should be considered the same exception on the outer call.

One example is a specialised collection implemented by using another collection. Let's say it's a DistinctList<T> that wraps a List<T> but refuses duplicate items.

If someone called ICollection<T>.CopyTo on your collection class, it might just be a straight call to CopyTo on the inner collection (if say, all the custom logic only applied to adding to the collection, or setting it up). Now, the conditions in which that call would throw are exactly the same conditions in which your collection should throw to match the documentation of ICollection<T>.CopyTo.

Now, you could just not catch the execption at all, and let it pass through. Here though the user gets an exception from List<T> when they were calling something on a DistinctList<T>. Not the end of the world, but you may want to hide those implementation details.

Or you could do your own checking:

public CopyTo(T[] array, int arrayIndex)
{
  if(array == null)
    throw new ArgumentNullException("array");
  if(arrayIndex < 0)
    throw new ArgumentOutOfRangeException("arrayIndex", "Array Index must be zero or greater.");
  if(Count > array.Length + arrayIndex)
    throw new ArgumentException("Not enough room in array to copy elements starting at index given.");
  _innerList.CopyTo(array, arrayIndex);
}

That's not the worse code because it's boilerplate and we can probably just copy it from some other implementation of CopyTo where it wasn't a simple pass-through and we had to implement it ourselves. Still, it's needlessly repeating the exact same checks that are going to be done in _innerList.CopyTo(array, arrayIndex), so the only thing it has added to our code is 6 lines where there could be a bug.

We could check and wrap:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentNullException ane)
  {
    throw new ArgumentNullException("array", ane);
  }
  catch(ArgumentOutOfRangeException aore)
  {
    throw new ArgumentOutOfRangeException("Array Index must be zero or greater.", aore);
  }
  catch(ArgumentException ae)
  {
    throw new ArgumentException("Not enough room in array to copy elements starting at index given.", ae);
  }
}

In terms of new code added that could potentially be buggy, this is even worse. And we don't gain a thing from the inner exceptions. If we pass a null array to this method and receive an ArgumentNullException, we're not going to learn anything by examining the inner exception and learning that a call to _innerList.CopyTo was passed a null array and threw an ArgumentNullException.

Here, we can do everything we want with:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentException ae)
  {
    throw ae;
  }
}

Every one of the exceptions that we expect to have to throw if the user calls it with incorrect arguments, will correctly be thrown by that re-throw. If there's a bug in the logic used here, it's in one of two lines - either we were wrong in deciding this was a case where this approach works, or we were wrong in having ArgumentException as the exception type looked for. It's the only two bugs that the catch block can possibly have.

Now. I still agree that most of the time you either want a plain throw; or you want to construct your own exception to more directly match the problem from the perspective of the method in question. There are cases like the above where re-throwing like this makes more sense, and there are plenty of other cases. E.g. to take a very different example, if an ATOM file reader implemented with a FileStream and an XmlTextReader receives a file error or invalid XML, then it will perhaps want to throw exactly the same exception it received from those classes, but it should look to the caller that it is AtomFileReader that is throwing a FileNotFoundException or XmlException, so they might be candidates for similarly re-throwing.

Edit:

We can also combine the two:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentException ae)
  {
    throw ae;
  }
  catch(Exception ex)
  {
    //we weren't expecting this, there must be a bug in our code that put
    //us into an invalid state, and subsequently let this exception happen.
    LogException(ex);
    throw;
  }
}

is there any IE8 only css hack?

For IE8 native browser alone:

.classname{
    *color: green; /* This is for IE8 Native browser alone */
}

How do I check in JavaScript if a value exists at a certain array index?

OK, let's first see what would happens if an array value not exist in JavaScript, so if we have an array like below:

const arr = [1, 2, 3, 4, 5];

and now we check if 6 is there at index 5 or not:

arr[5];

and we get undefined...

So that's basically give us the answer, the best way to check if undefined, so something like this:

if("undefined" === typeof arrayName[index]) {
  //array value is not there...
}

It's better NOT doing this in this case:

if(!arrayName[index]) {
  //Don't check like this..
}

Because imagine we have this array:

const arr = [0, 1, 2];

and we do:

if(!arr[0]) {
  //This get passed, because in JavaScript 0 is falsy
}

So as you see, even 0 is there, it doesn't get recognised, there are few other things which can do the same and make you application buggy, so be careful, I list them all down:

  1. undefined: if the value is not defined and it's undefined
  2. null: if it's null, for example if a DOM element not exists...
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false

Multiple values in single-value context

Yes, there is.

Surprising, huh? You can get a specific value from a multiple return using a simple mute function:

package main

import "fmt"
import "strings"

func µ(a ...interface{}) []interface{} {
    return a
}

type A struct {
    B string
    C func()(string)
}

func main() {
    a := A {
        B:strings.TrimSpace(µ(E())[1].(string)),
        C:µ(G())[0].(func()(string)),
    }

    fmt.Printf ("%s says %s\n", a.B, a.C())
}

func E() (bool, string) {
    return false, "F"
}

func G() (func()(string), bool) {
    return func() string { return "Hello" }, true
}

https://play.golang.org/p/IwqmoKwVm-

Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.

You can read more about the science behind that from this article. Credits to the author.

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

How to check if a URL exists or returns 404 with Java?

this worked for me:

URL u = new URL ( "http://www.example.com/");
HttpURLConnection huc =  ( HttpURLConnection )  u.openConnection (); 
huc.setRequestMethod ("GET");  //OR  huc.setRequestMethod ("HEAD"); 
huc.connect () ; 
int code = huc.getResponseCode() ;
System.out.println(code);

thanks for the suggestions above.

MongoDB or CouchDB - fit for production?

This question has already accepted answer but now a days one more NoSQL DB is in trend for many of its great features. It is Couchbase; which runs as CouchbaseLite on mobile platform and Couchbase Server on your server side.

Here is some of main features of Couchbase Lite.

Couchbase Lite is a lightweight, document-oriented (NoSQL), syncable database engine suitable for embedding into mobile apps.

Lightweight means:

Embedded—the database engine is a library linked into the app, not a separate server process. Small code size—important for mobile apps, which are often downloaded over cell networks. Quick startup time—important because mobile devices have relatively slow CPUs. Low memory usage—typical mobile data sets are relatively small, but some documents might have large multimedia attachments. Good performance—exact figures depend on your data and application, of course.

Document-oriented means:

Stores records in flexible JSON format instead of requiring predefined schemas or normalization. Documents can have arbitrary-sized binary attachments, such as multimedia content. Application data format can evolve over time without any need for explicit migrations. MapReduce indexing provides fast lookups without needing to use special query languages.

Syncable means:

Any two copies of a database can be brought into sync via an efficient, reliable, proven replication algorithm. Sync can be on-demand or continuous (with a latency of a few seconds). Devices can sync with a subset of a large database on a remote server. The sync engine supports intermittent and unreliable network connections. Conflicts can be detected and resolved, with app logic in full control of merging. Revision trees allow for complex replication topologies, including server-to-server (for multiple data centers) and peer-to-peer, without data loss or false conflicts. Couchbase Lite provides native APIs for seamless iOS (Objective-C) and Android (Java) development. In addition, it includes the Couchbase Lite Plug-in for PhoneGap, which enables you to build iOS and Android apps that you develop by using familiar web-application programming techniques and the PhoneGap mobile development framework.

You can explore more on Couchbase Lite

and Couchbase Server

This is going to the next big thing.

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

CSS selector for first element with class

you could use first-of-type or nth-of-type(1)

_x000D_
_x000D_
.red {_x000D_
  color: green;  _x000D_
}_x000D_
_x000D_
/* .red:nth-of-type(1) */_x000D_
.red:first-of-type {_x000D_
  color: red;  _x000D_
}
_x000D_
<div class="home">_x000D_
  <span>blah</span>_x000D_
  <p class="red">first</p>_x000D_
  <p class="red">second</p>_x000D_
  <p class="red">third</p>_x000D_
  <p class="red">fourth</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Global Git ignore

If you're using VSCODE, you can get this extension to handle the task for you. It watches your workspace each time you save your work and helps you to automatically ignore the files and folders you specified in your vscode settings.json ignoreit (vscode extension)

Bash script and /bin/bash^M: bad interpreter: No such file or directory

This is caused by editing file in windows and importing and executing in unix.

dos2unix -k -o filename should do the trick.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

In my case this had to do with lazy loading the iframe. Removing the iframe HTML attribute loading="lazy" solved the problem for me.

How do I check if a directory exists? "is_dir", "file_exists" or both?

$dirname = $_POST["search"];
$filename = "/folder/" . $dirname . "/";

if (!file_exists($filename)) {
    mkdir("folder/" . $dirname, 0777);
    echo "The directory $dirname was successfully created.";
    exit;
} else {
    echo "The directory $dirname exists.";
}

How to uninstall a package installed with pip install --user

As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding --user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the --user option.

In my case:

antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip  pip2  pip2.7  pip3  pip3.5

And then just uninstall with the specific pip version.

How to convert Observable<any> to array[]

This should work:

GetCountries():Observable<CountryData[]>  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json());
}

For this to work you will need to import the following:

import 'rxjs/add/operator/map'

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

Is there a way to add a gif to a Markdown file?

Upload from local:

  1. Add your .gif file to the root of Github repository and push the change.
  2. Go to README.md
  3. Add this ![Alt text](name-of-gif-file.gif) / ![](name-of-gif-file.gif)
  4. Commit and gif should be seen.

Show the gif using url:

  1. Go to README.md
  2. Add in this format ![Alt text](https://sample/url/name-of-gif-file.gif)
  3. Commit and gif should be seen.

Hope this helps.

How to create a project from existing source in Eclipse and then find it?

While creating a project from a full folder may or may not work within the workspace, there's a condition outside of the workspace that prevents starting a new project with a full folder.

This is relevant if you use numerous folder locations for sources, for example an htdocs or www folder for web projects, and a different location for desktop Java applications.

The condition mentioned occurs when Eclipse is told to create a new project, and given a full folder outside the workspace. Eclipse will say the folder isn't empty, and prevent creating a new project within the given folder. I haven't found a way around this, and any solution requires extra steps.

My favorite solution is as follows

  1. Rename the full folder with an appended "Original" or "Backup.
  2. Create the Eclipse project with the name of the full folder before the folder was renamed.
  3. Copy all the relabeled full folders contents into the new project folder.

Eclipse should make a new project, and update that project with the new folder contents as it scans for changes. The existing sources are now part of the new project.

Although you had to perform three extra steps, you now have a backup with the original sources available, and are also able to use a copy of them in an existing project. If storage space is a concern, simply move/cut the source rather than fully copy the original folder contents.

How to get the previous page URL using JavaScript?

<script type="text/javascript">
    document.write(document.referrer);
</script>

document.referrer serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.

It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.

Gradle: Execution failed for task ':processDebugManifest'

2 things you need to add to AndroidManifest.xml:

1st: add xmlns:tools="http://schemas.android.com/tools" to manifest tag

<manifest xmlns:android=".........
   package="...........
   xmlns:tools="http://schemas.android.com/tools">

2nd: Add tools:replace="icon" to application tag

<application
       android:icon=.........
       android:label=.......
       tools:replace="icon">

C# How do I click a button by hitting Enter whilst textbox has focus?

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Enter)
     {
         button.PerformClick();
         // these last two lines will stop the beep sound
         e.SuppressKeyPress = true;
         e.Handled = true;
     }
}

Bind this KeyDown event to the textbox, then when ever you press a key, this event will be fired. Inside the event we check whether user has pressed "Enter key", if so, you can perform you action

Is SMTP based on TCP or UDP?

Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

Check the eclipse.ini file and make sure there is no -vm option there that is pointing to a non existing java install now. You can delete the option to let Eclipse figure out what java install to use or change it so it's pointing to the new install.

What is the difference between #include <filename> and #include "filename"?

Form 1 - #include < xxx >

First, looks for the presence of header file in the current directory from where directive is invoked. If not found, then it searches in the preconfigured list of standard system directories.

Form 2 - #include "xxx"

This looks for the presence of header file in the current directory from where directive is invoked.


The exact search directory list depends on the target system, how GCC is configured, and where it is installed. You can find the search directory list of your GCC compiler by running it with -v option.

You can add additional directories to the search path by using - Idir, which causes dir to be searched after the current directory (for the quote form of the directive) and ahead of the standard system directories.


Basically, the form "xxx" is nothing but search in current directory; if not found falling back the form

Deserializing JSON Object Array with Json.net

For those who don't want to create any models, use the following code:

var result = JsonConvert.DeserializeObject<
  List<Dictionary<string, 
    Dictionary<string, string>>>>(content);

Note: This doesn't work for your JSON string. This is not a general solution for any JSON structure.

Xcode - ld: library not found for -lPods

It seems project has been using cocoapods. and that files are missing from your project.

You cant just download it from git. You need to install it from cocoapods.

for more help, you may follow Introduction to CocoaPods Tutorial

If the project uses CocoaPods be aware to always open the .xcworkspace file instead of the .xcodeproj file

How do I check if a number is a palindrome?

 public class Numbers
 {
   public static void main(int givenNum)
   { 
       int n= givenNum
       int rev=0;

       while(n>0)
       {
          //To extract the last digit
          int digit=n%10;

          //To store it in reverse
          rev=(rev*10)+digit;

          //To throw the last digit
          n=n/10;
      }

      //To check if a number is palindrome or not
      if(rev==givenNum)
      { 
         System.out.println(givenNum+"is a palindrome ");
      }
      else
      {
         System.out.pritnln(givenNum+"is not a palindrome");
      }
  }
}

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

Why does git revert complain about a missing -m option?

I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:

*   commit I want to cherry-pick (x)
|\  
| * branch I want to cherry-pick to (y)
* | 
|/  
* common parent (x)

I understand now that I want to do

git cherry-pick -m 2 mycommitsha

This is because -m 1 would merge based on the common parent where as -m 2 merges based on branch y, that is the one I want to cherry-pick to.

How do I get a TextBox to only accept numeric input in WPF?

If you do not want to write a lot of code to do a basic function (I don't know why people make long methods) you can just do this:

  1. Add namespace:

    using System.Text.RegularExpressions;
    
  2. In XAML, set a TextChanged property:

    <TextBox x:Name="txt1" TextChanged="txt1_TextChanged"/>
    
  3. In WPF under txt1_TextChanged method, add Regex.Replace:

    private void txt1_TextChanged(object sender, TextChangedEventArgs e)
    {
        txt1.Text = Regex.Replace(txt1.Text, "[^0-9]+", "");
    }
    

How do I disable log messages from the Requests library?

In case you came here looking for a way to modify logging of any (possibly deeply nested) module, use logging.Logger.manager.loggerDict to get a dictionary of all of the logger objects. The returned names can then be used as the argument to logging.getLogger:

import requests
import logging
for key in logging.Logger.manager.loggerDict:
    print(key)
# requests.packages.urllib3.connectionpool
# requests.packages.urllib3.util
# requests.packages
# requests.packages.urllib3
# requests.packages.urllib3.util.retry
# PYREADLINE
# requests
# requests.packages.urllib3.poolmanager

logging.getLogger('requests').setLevel(logging.CRITICAL)
# Could also use the dictionary directly:
# logging.Logger.manager.loggerDict['requests'].setLevel(logging.CRITICAL)

Per user136036 in a comment, be aware that this method only shows you the loggers that exist at the time you run the above snippet. If, for example, a module creates a new logger when you instantiate a class, then you must put this snippet after creating the class in order to print its name.

Unable to find a @SpringBootConfiguration when doing a JpaTest

It is worth to check if you have refactored package name of your main class annotated with @SpringBootApplication. In that case the testcase should be in an appropriate package otherwise it will be looking for it in the older package . this was the case for me.

How to solve java.lang.NoClassDefFoundError?

If your project is in a package like com.blahcode and your class is called Main, the compiled files may be output in a directory structure like ./out/com/blahcode/Main.class. This is especially true for IntelliJ IDEA.

When trying to run from a shell or cmd, you need to cd to that which contains com as a sub-directory.

cd out
java -classpath . com.blahcode.Main

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

img tag displays wrong orientation

Until CSS: image-orientation:from-image; is more universally supported we are doing a server side solution with python. Here's the gist of it. You check the exif data for orientation, then rotate the image accordingly and resave.

We prefer this solution over client side solutions as it does not require loading extra libraries client side, and this operation only has to happen one time on file upload.

if fileType == "image":
    exifToolCommand = "exiftool -j '%s'" % filePath
    exif = json.loads(subprocess.check_output(shlex.split(exifToolCommand), stderr=subprocess.PIPE))
    if 'Orientation' in exif[0]:
        findDegrees, = re.compile("([0-9]+)").search(exif[0]['Orientation']).groups()
        if findDegrees:
            rotateDegrees = int(findDegrees)
            if 'CW' in exif[0]['Orientation'] and 'CCW' not in exif[0]['Orientation']:
                rotateDegrees = rotateDegrees * -1
            # rotate image
            img = Image.open(filePath)
            img2 = img.rotate(rotateDegrees)
            img2.save(filePath)

How can I get a list of users from active directory?

Include the System.DirectoryServices.dll, then use the code below:

DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";

foreach (DirectoryEntry child in directoryEntry.Children)
{
    if (child.SchemaClassName == "User")
    {
        userNames += child.Name + Environment.NewLine   ;         
    }

}
MessageBox.Show(userNames);

How does the Java 'for each' loop work?

It adds beauty to your code by removing all the basic looping clutter. It gives a clean look to your code, justified below.

Normal for loop:

void cancelAll(Collection<TimerTask> list) {
    for (Iterator<TimerTask> i = list.iterator(); i.hasNext();)
         i.next().cancel();
}

Using for-each:

void cancelAll(Collection<TimerTask> list) {
    for (TimerTask t : list)
        t.cancel();
}

for-each is a construct over a collection that implements Iterator. Remember that, your collection should implement Iterator; otherwise you can't use it with for-each.

The following line is read as "for each TimerTask t in list."

for (TimerTask t : list)

There is less chance for errors in case of for-each. You don't have to worry about initializing the iterator or initializing the loop counter and terminating it (where there is scope for errors).

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

TypeScript static classes

You can create a class in Typescript as follows:

export class coordinate {
        static x: number;
        static y: number;
        static gradient() {
            return y/x;
        }
    }

and reference it's properties and methods "without" instantiation so:

coordinate.x = 10;
coordinate.y = 10;
console.log(`x of ${coordinate.x} and y of ${coordinate.y} has gradient of ${coordinate.gradient()}`);

Fyi using backticks `` in conjunction with interpolation syntax ${} allows ease in mixing code with text :-)

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

Convert javascript array to string

this's my function, convert object or array to json

function obj2json(_data){
    str = '{ ';
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += "'" + i + "':" + obj2arr(v) ;
        else if ($.type(v)== 'array')
            str += "'" + i + "':" + obj2arr(v) ;
        else{
            str +=  "'" + i + "':'" + v + "'";
        }
    });
    return str+= '}';
}

i just edit to v0.2 ^.^

 function obj2json(_data){
    str = (($.type(_data)== 'array')?'[ ': '{ ');
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += '"' + i + '":' + obj2json(v) ;
        else if ($.type(v)== 'array')
            str += '"' + i + '":' + obj2json(v) ;
        else{
            if($.type(_data)== 'array')
                str += '"' + v + '"';
            else
                str +=  '"' + i + '":"' + v + '"';
        }
    });
    return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}

Setting a spinner onClickListener() in Android

Personally, I use that:

    final Spinner spinner = (Spinner) (view.findViewById(R.id.userList));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                

            userSelectedIndex = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });  

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

How do I convert an NSString value to NSData?

NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];

Scroll to element on click in Angular 4

In Angular 7 works perfect

HTML

<button (click)="scroll(target)">Click to scroll</button>
<div #target>Your target</div>

In component

scroll(el: HTMLElement) {
    el.scrollIntoView({behavior: 'smooth'});
}

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

Entity Framework code first unique column

Note that in Entity Framework 6.1 (currently in beta) will support the IndexAttribute to annotate the index properties which will automatically result in a (unique) index in your Code First Migrations.

Returning http status code from Web Api controller

Try this :

return new ContentResult() { 
    StatusCode = 404, 
    Content = "Not found" 
};

How to create a Restful web service with input parameters?

You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello in your browser...

package newpackage;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;

@Path("generic")
public class GenericResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GenericResource
     */
    public GenericResource() {
    }

    /**
     * Retrieves representation of an instance of newpackage.GenericResource

     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    @Consumes("text/plain")
    @Path("getText/")
    public String getText(@QueryParam("arg1")
            @DefaultValue("") String arg1) {

       return  arg1 ;  }

    @PUT
    @Consumes("text/plain")
    public void putText(String content) {





    }
}

How to select option in drop down protractorjs e2e tests

Another way to set an option element:

var setOption = function(optionToSelect) {

    var select = element(by.id('locregion'));
    select.click();
    select.all(by.tagName('option')).filter(function(elem, index) {
        return elem.getText().then(function(text) {
            return text === optionToSelect;
        });
    }).then(function(filteredElements){
        filteredElements[0].click();
    });
};

// using the function
setOption('BeaverBox Testing');

How to get list of all installed packages along with version in composer?

List installed dependencies:

  • Flat: composer show -i
  • Tree: composer show -i -t

-i short for --installed.

-t short for --tree.

ref: https://getcomposer.org/doc/03-cli.md#show

Change border-bottom color using jquery?

$("selector").css("border-bottom-color", "#fff");
  1. construct your jQuery object which provides callable methods first. In this case, say you got an #mydiv, then $("#mydiv")
  2. call the .css() method provided by jQuery to modify specified object's css property values.

Handling 'Sequence has no elements' Exception

The value is null, you have to check why... (in addition to the implementation of the solutions proposed here)

Check the hardware Connections.

I do not want to inherit the child opacity from the parent in CSS

There is no one size fits-all approach, but one thing that I found particularly helpful is setting opacity for a div's direct children, except for the one that you want to keep fully visible. In code:

<div class="parent">
    <div class="child1"></div>
    <div class="child2"></div>
    <div class="child3"></div>
    <div class="child4"></div>
</div>

and css:

div.parent > div:not(.child1){
    opacity: 0.5;
}

In case you have background colors/images on the parent you fix color opacity with rgba and background-image by applying alpha filters

Angular IE Caching issue for $http

Duplicating my answer in another thread.

For Angular 2 and newer, the easiest way to add no-cache headers by overriding RequestOptions:

import { Injectable } from '@angular/core';
import { BaseRequestOptions, Headers } from '@angular/http';

@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
    headers = new Headers({
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
    });
}

And reference it in your module:

@NgModule({
    ...
    providers: [
        ...
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ]
})

build-impl.xml:1031: The module has not been deployed

  • Check if there any other instance of the server is running already
  • Check if the port that will be used by the server is free.

How do I check if a column is empty or null in MySQL?

select * from table where length(RTRIM(LTRIM(column_name))) > 0

How to fix Git error: object file is empty?

The git object files have gone corrupt (as pointed out in other answers as well). This can happen during machine crashes, etc.

I had the same thing. After reading the other top answers here I found the quickest way to fix the broken git repository with the following commands (execute in the git working directory that contains the .git folder):

(Be sure to back up your git repository folder first!)

find .git/objects/ -type f -empty | xargs rm
git fetch -p
git fsck --full

This will first remove any empty object files that cause corruption of the repository as a whole, and then fetch down the missing objects (as well as latest changes) from the remote repository, and then do a full object store check. Which, at this point, should succeed without any errors (there may be still some warnings though!)

PS. This answer suggests you have a remote copy of your git repository somewhere (e.g. on GitHub) and the broken repository is the local repository that is tied to the remote repository which is still in tact. If that is not the case, then do not attempt to fix it the way I recommend.

How to switch Python versions in Terminal?

pyenv is a 3rd party version manager which is super commonly used (18k stars, 1.6k forks) and exactly what I looked for when I came to this question.

Install pyenv.

Usage

$ pyenv install --list
Available versions:
  2.1.3
  [...]
  3.8.1
  3.9-dev
  activepython-2.7.14
  activepython-3.5.4
  activepython-3.6.0
  anaconda-1.4.0
  [... a lot more; including anaconda, miniconda, activepython, ironpython, pypy, stackless, ....]

$ pyenv install 3.8.1
Downloading Python-3.8.1.tar.xz...
-> https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tar.xz
Installing Python-3.8.1...
Installed Python-3.8.1 to /home/moose/.pyenv/versions/3.8.1

$ pyenv versions
* system (set by /home/moose/.pyenv/version)
  2.7.16
  3.5.7
  3.6.9
  3.7.4
  3.8-dev

$ python --version
Python 2.7.17
$ pip --version
pip 19.3.1 from /home/moose/.local/lib/python3.6/site-packages/pip (python 3.6)

$ mkdir pyenv-experiment && echo "3.8.1" > "pyenv-experiment/.python-version"
$ cd pyenv-experiment

$ python --version
Python 3.8.1
$ pip --version
pip 19.2.3 from /home/moose/.pyenv/versions/3.8.1/lib/python3.8/site-packages/pip (python 3.8)

How do I see which version of Swift I'm using?

Project build settings have a block 'Swift Compiler - Languages', which stores information about Swift Language Version in key-value format. It will show you all available (supported) Swift Language Version for your Xcode and active version also by a tick mark.

Project ? (Select Your Project Target) ? Build Settings ? (Type 'swift_version' in the Search bar) Swift Compiler Language ? Swift Language Version ? Click on Language list to open it (and there will be a tick mark on any one of list-item, that will be current swift version).

Look at this snapshot, for easy understanding:

xcode with described areas highlighted


With help of following code, programmatically you can find Swift version supported by your project.

#if swift(>=5.3)
print("Hello, Swift 5.3")

#elseif swift(>=5.2)
print("Hello, Swift 5.2")

#elseif swift(>=5.1)
print("Hello, Swift 5.1")

#elseif swift(>=5.0)
print("Hello, Swift 5.0")

#elseif swift(>=4.2)
print("Hello, Swift 4.2")

#elseif swift(>=4.1)
print("Hello, Swift 4.1")

#elseif swift(>=4.0)
print("Hello, Swift 4.0")

#elseif swift(>=3.2)
print("Hello, Swift 3.2")

#elseif swift(>=3.0)
print("Hello, Swift 3.0")

#elseif swift(>=2.2)
print("Hello, Swift 2.2")

#elseif swift(>=2.1)
print("Hello, Swift 2.1")

#elseif swift(>=2.0)
print("Hello, Swift 2.0")

#elseif swift(>=1.2)
print("Hello, Swift 1.2")

#elseif swift(>=1.1)
print("Hello, Swift 1.1")

#elseif swift(>=1.0)
print("Hello, Swift 1.0")

#endif

Here is result using Playground (with Xcode 11.x)

enter image description here

Converting URL to String and back again

2020 | SWIFT 5.1:

From STRING to URL:

let url = URL(fileURLWithPath: "//Users/Me/Desktop/Doc.txt")

From URL to STRING:

let a = String(describing: url)       // "file:////Users/Me/Desktop/Doc.txt"
let b = "\(url)"                      // "file:////Users/Me/Desktop/Doc.txt"
let c = url.absoluteString            // "file:////Users/Me/Desktop/Doc.txt"
let d = url.path                      // "/Users/Me/Desktop/Doc.txt" 

BUT value of d will be invisible due to debug process, so...

THE BEST SOLUTION:

let e = "\(url.path)"                 // "/Users/Me/Desktop/Doc.txt"

Remove background drawable programmatically in Android

I have a case scenario and I tried all the answers from above, but always new image was created on top of the old one. The solution that worked for me is:

imageView.setImageResource(R.drawable.image);

How do I properly clean up Excel interop objects?

UPDATE: Added C# code, and link to Windows Jobs

I spent sometime trying to figure out this problem, and at the time XtremeVBTalk was the most active and responsive. Here is a link to my original post, Closing an Excel Interop process cleanly, even if your application crashes. Below is a summary of the post, and the code copied to this post.

  • Closing the Interop process with Application.Quit() and Process.Kill() works for the most part, but fails if the applications crashes catastrophically. I.e. if the app crashes, the Excel process will still be running loose.
  • The solution is to let the OS handle the cleanup of your processes through Windows Job Objects using Win32 calls. When your main application dies, the associated processes (i.e. Excel) will get terminated as well.

I found this to be a clean solution because the OS is doing real work of cleaning up. All you have to do is register the Excel process.

Windows Job Code

Wraps the Win32 API Calls to register Interop processes.

public enum JobObjectInfoType
{
    AssociateCompletionPortInformation = 7,
    BasicLimitInformation = 2,
    BasicUIRestrictions = 4,
    EndOfJobTimeInformation = 6,
    ExtendedLimitInformation = 9,
    SecurityLimitInformation = 5,
    GroupInformation = 11
}

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
    public int nLength;
    public IntPtr lpSecurityDescriptor;
    public int bInheritHandle;
}

[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
    public Int64 PerProcessUserTimeLimit;
    public Int64 PerJobUserTimeLimit;
    public Int16 LimitFlags;
    public UInt32 MinimumWorkingSetSize;
    public UInt32 MaximumWorkingSetSize;
    public Int16 ActiveProcessLimit;
    public Int64 Affinity;
    public Int16 PriorityClass;
    public Int16 SchedulingClass;
}

[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
    public UInt64 ReadOperationCount;
    public UInt64 WriteOperationCount;
    public UInt64 OtherOperationCount;
    public UInt64 ReadTransferCount;
    public UInt64 WriteTransferCount;
    public UInt64 OtherTransferCount;
}

[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
    public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
    public IO_COUNTERS IoInfo;
    public UInt32 ProcessMemoryLimit;
    public UInt32 JobMemoryLimit;
    public UInt32 PeakProcessMemoryUsed;
    public UInt32 PeakJobMemoryUsed;
}

public class Job : IDisposable
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    static extern IntPtr CreateJobObject(object a, string lpName);

    [DllImport("kernel32.dll")]
    static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);

    private IntPtr m_handle;
    private bool m_disposed = false;

    public Job()
    {
        m_handle = CreateJobObject(null, null);

        JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
        info.LimitFlags = 0x2000;

        JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
        extendedInfo.BasicLimitInformation = info;

        int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
        IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
        Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

        if (!SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))
            throw new Exception(string.Format("Unable to set information.  Error: {0}", Marshal.GetLastWin32Error()));
    }

    #region IDisposable Members

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    #endregion

    private void Dispose(bool disposing)
    {
        if (m_disposed)
            return;

        if (disposing) {}

        Close();
        m_disposed = true;
    }

    public void Close()
    {
        Win32.CloseHandle(m_handle);
        m_handle = IntPtr.Zero;
    }

    public bool AddProcess(IntPtr handle)
    {
        return AssignProcessToJobObject(m_handle, handle);
    }

}

Note about Constructor code

  • In the constructor, the info.LimitFlags = 0x2000; is called. 0x2000 is the JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE enum value, and this value is defined by MSDN as:

Causes all processes associated with the job to terminate when the last handle to the job is closed.

Extra Win32 API Call to get the Process ID (PID)

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

Using the code

    Excel.Application app = new Excel.ApplicationClass();
    Job job = new Job();
    uint pid = 0;
    Win32.GetWindowThreadProcessId(new IntPtr(app.Hwnd), out pid);
    job.AddProcess(Process.GetProcessById((int)pid).Handle);

How do I get LaTeX to hyphenate a word that contains a dash?

multi\hskip0pt-\hskip0pt disciplinary

You can e.g. define like

\def\:{\hskip0pt}

and then write

multi\:-\:disciplinary

Note that the babel Russian language package has its own set of dashes that do not prohibit hyphenation, "~ (double quotation+tilde) for example.

pandas: find percentile stats of a given column

You can use the pandas.DataFrame.quantile() function, as shown below.

import pandas as pd
import random

A = [ random.randint(0,100) for i in range(10) ]
B = [ random.randint(0,100) for i in range(10) ]

df = pd.DataFrame({ 'field_A': A, 'field_B': B })
df
#    field_A  field_B
# 0       90       72
# 1       63       84
# 2       11       74
# 3       61       66
# 4       78       80
# 5       67       75
# 6       89       47
# 7       12       22
# 8       43        5
# 9       30       64

df.field_A.mean()   # Same as df['field_A'].mean()
# 54.399999999999999

df.field_A.median() 
# 62.0

# You can call `quantile(i)` to get the i'th quantile,
# where `i` should be a fractional number.

df.field_A.quantile(0.1) # 10th percentile
# 11.9

df.field_A.quantile(0.5) # same as median
# 62.0

df.field_A.quantile(0.9) # 90th percentile
# 89.10000000000001

ALTER TABLE DROP COLUMN failed because one or more objects access this column

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name> drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

How can I open multiple files using "with open" in Python?

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

Android: How to create a Dialog without a title?

In your code if you use requestWindowFeature(Window.FEATURE_NO_TITLE); be sure that it goes before dialog.setContentView(); otherwise it causes the application to crash.

How to switch to other branch in Source Tree to commit the code?

  1. Go to the log view (to be able to go here go to View -> log view).
  2. Double click on the line with the branch label stating that branch. Automatically, it will switch branch. (A prompt will dropdown and say switching branch.)
  3. If you have two or more branches on the same line, it will ask you via prompt which branch you want to switch. Choose the specific branch from the dropdown and click ok.

To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.

PowerShell To Set Folder Permissions

In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:

$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose

Verbosity is optional in the last line

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

I had the same issue and fixed by using project level crashlytics gradle version 2.1.1

classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1'

How to Find App Pool Recycles in Event Log

As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}

From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.

This along with @BlackHawkDesign comment should help you find what you need.

I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00

TypeScript enum to object array

Enums are real objects that exist at runtime. So you are able to reverse the mapping doing something like this:

let value = GoalProgressMeasurements.Not_Measured;
console.log(GoalProgressMeasurements[value]);
// => Not_Measured

Based on that you can use the following code:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

let map: {id: number; name: string}[] = [];

for(var n in GoalProgressMeasurements) {
    if (typeof GoalProgressMeasurements[n] === 'number') {
        map.push({id: <any>GoalProgressMeasurements[n], name: n});
    }
}

console.log(map);

Reference: https://www.typescriptlang.org/docs/handbook/enums.html

Closing pyplot windows

plt.close() will close current instance.

plt.close(2) will close figure 2

plt.close(plot1) will close figure with instance plot1

plt.close('all') will close all fiures

Found here.

Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.

You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

EXAMPLE

After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.

Below I create a plot:

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')

In this case, ax above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax).

par_plot is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.

I can also create a slider widget by doing the following:

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

The first line creates a new axes for the slider (called axsliderA), the second line creates a slider instance sA which is placed in the axes, and the third line specifies a function to call when the slider value changes (update).

My update function could look something like this:

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

The par_plot.set_ydata(y_data) changes the ydata property of the Line2D object with the handle par_plot.

The draw() function updates the current set of axes.

Putting it all together:

from pylab import *
import matplotlib.pyplot as plt
import numpy

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()


x_data = numpy.arange(-100,100,0.1);

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)

ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)

axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)

axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;

par_plot, = plot(x_data,y_data, lw=2, color='red')

show()

A note about the above: When I run the application, the code runs sequentially right through (it stores the update function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).

This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.

Angular 2 Unit Tests: Cannot find name 'describe'

if the error is in the .specs file app/app.component.spec.ts(7,3): error TS2304: Cannot find name 'beforeEach'.

add this to the top of your file and npm install rxjs

import { range } from 'rxjs'; import { map, filter } from 'rxjs/operators';

Clone private git repo with dockerfile

Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.

As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY the required files into your final image.

Additionally if we LABEL our intermediate layers, we can even delete them from the machine when finished.

# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate

# Take an SSH key as a build argument.
ARG SSH_KEY

# Install dependencies required to git clone.
RUN apk update && \
    apk add --update git && \
    apk add --update openssh

# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
    echo "$SSH_KEY" > /root/.ssh/id_rsa && \
    chmod -R 600 /root/.ssh/ && \
    ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git

# Choose the base image for our final image
FROM alpine

# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md

We can then build:

MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .

Prove our SSH keys are gone:

docker run -ti --rm clone-example cat /root/.ssh/id_rsa

Clean intermediate images from the build machine:

docker rmi -f $(docker images -q --filter label=stage=intermediate)

How do I make the first letter of a string uppercase in JavaScript?

Here is my attempt to make a universal function that can capitalize only the first letter, or the first letter of each word, including words separated by a dash (like some first names in French).

By default, the function capitalizes only the first letter and leave the rest untouched.

Parameters:

  • lc: true to lowercase the rest of the word(s)
  • all: true to capitalize each word

 

if (typeof String.prototype.capitalize !== 'function') {
    String.prototype.capitalize = function(lc, all) {
        if (all) {
            return this.split( " " ).map( function(currentValue, index, array ) {
                return currentValue.capitalize( lc );
            }, this).join(" ").split("-").map(function(currentValue, index, array) {
                return currentValue.capitalize(false);
            }, this).join("-");
        }
        else {
            return lc ? this.charAt(0).toUpperCase() + this.slice(1 ).toLowerCase() : this.charAt(0).toUpperCase() + this.slice(1);
        }
    }
}

Adding hours to JavaScript Date object?

The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.

this.setUTCHours(this.getUTCHours()+h);

will add h hours to this independent of time system peculiarities. Jason Harwig's method works as well.

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

How do I find out what type each object is in a ArrayList<Object>?

import java.util.ArrayList;

/**
 * @author potter
 *
 */
public class storeAny {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Object> anyTy=new ArrayList<Object>();
        anyTy.add(new Integer(1));
        anyTy.add(new String("Jesus"));
        anyTy.add(new Double(12.88));
        anyTy.add(new Double(12.89));
        anyTy.add(new Double(12.84));
        anyTy.add(new Double(12.82));

        for (Object o : anyTy) {
            if(o instanceof String){
                System.out.println(o.toString());
            } else if(o instanceof Integer) {
                System.out.println(o.toString());   
            } else if(o instanceof Double) {
                System.out.println(o.toString());
            }
        }
    }
}

Not equal string

Try this:

if(myString != "-1")

The opperand is != and not =!

You can also use Equals

if(!myString.Equals("-1"))

Note the ! before myString

SQL Server: use CASE with LIKE

This is the syntax you need:

CASE WHEN countries LIKE '%'+@selCountry+'%' THEN 'national' ELSE 'regional' END

Although, as per your original problem, I'd solve it differently, splitting the content of @selcountry int a table form and joining to it.

Powershell: How can I stop errors from being displayed in a script?

You have a couple of options. The easiest involve using the ErrorAction settings.

-Erroraction is a universal parameter for all cmdlets. If there are special commands you want to ignore you can use -erroraction 'silentlycontinue' which will basically ignore all error messages generated by that command. You can also use the Ignore value (in PowerShell 3+):

Unlike SilentlyContinue, Ignore does not add the error message to the $Error automatic variable.

If you want to ignore all errors in a script, you can use the system variable $ErrorActionPreference and do the same thing: $ErrorActionPreference= 'silentlycontinue'

See about_CommonParameters for more info about -ErrorAction. See about_preference_variables for more info about $ErrorActionPreference.

Cannot authenticate into mongo, "auth fails"

You can also try this :-

mongo localhost:27017/admin -u admin -p SECRETPASSWORD

Found it in this post

Here obviously the localhost can be some other host and the /admin can be some other database on which authentication has been applied

When to use "ON UPDATE CASCADE"

It's true that if your primary key is just a identity value auto incremented, you would have no real use for ON UPDATE CASCADE.

However, let's say that your primary key is a 10 digit UPC bar code and because of expansion, you need to change it to a 13-digit UPC bar code. In that case, ON UPDATE CASCADE would allow you to change the primary key value and any tables that have foreign key references to the value will be changed accordingly.

In reference to #4, if you change the child ID to something that doesn't exist in the parent table (and you have referential integrity), you should get a foreign key error.

NSOperation vs Grand Central Dispatch

Both NSQueueOperations and GCD allow executing heavy computation task in the background on separate threads by freeing the UI Application Main Tread.

Well, based previous post we see NSOperations has addDependency so that you can queue your operation one after another sequentially.

But I also read about GCD serial Queues you can create run your operations in the queue using dispatch_queue_create. This will allow running a set of operations one after another in a sequential manner.

NSQueueOperation Advantages over GCD:

  1. It allows to add dependency and allows you to remove dependency so for one transaction you can run sequential using dependency and for other transaction run concurrently while GCD doesn't allow to run this way.

  2. It is easy to cancel an operation if it is in the queue it can be stopped if it is running.

  3. You can define the maximum number of concurrent operations.

  4. You can suspend operation which they are in Queue

  5. You can find how many pending operations are there in queue.

How do you find the row count for all your tables in Postgres

To get estimates, see Greg Smith's answer.

To get exact counts, the other answers so far are plagued with some issues, some of them serious (see below). Here's a version that's hopefully better:

CREATE FUNCTION rowcount_all(schema_name text default 'public')
  RETURNS table(table_name text, cnt bigint) as
$$
declare
 table_name text;
begin
  for table_name in SELECT c.relname FROM pg_class c
    JOIN pg_namespace s ON (c.relnamespace=s.oid)
    WHERE c.relkind = 'r' AND s.nspname=schema_name
  LOOP
    RETURN QUERY EXECUTE format('select cast(%L as text),count(*) from %I.%I',
       table_name, schema_name, table_name);
  END LOOP;
end
$$ language plpgsql;

It takes a schema name as parameter, or public if no parameter is given.

To work with a specific list of schemas or a list coming from a query without modifying the function, it can be called from within a query like this:

WITH rc(schema_name,tbl) AS (
  select s.n,rowcount_all(s.n) from (values ('schema1'),('schema2')) as s(n)
)
SELECT schema_name,(tbl).* FROM rc;

This produces a 3-columns output with the schema, the table and the rows count.

Now here are some issues in the other answers that this function avoids:

  • Table and schema names shouldn't be injected into executable SQL without being quoted, either with quote_ident or with the more modern format() function with its %I format string. Otherwise some malicious person may name their table tablename;DROP TABLE other_table which is perfectly valid as a table name.

  • Even without the SQL injection and funny characters problems, table name may exist in variants differing by case. If a table is named ABCD and another one abcd, the SELECT count(*) FROM... must use a quoted name otherwise it will skip ABCD and count abcd twice. The %I of format does this automatically.

  • information_schema.tables lists custom composite types in addition to tables, even when table_type is 'BASE TABLE' (!). As a consequence, we can't iterate oninformation_schema.tables, otherwise we risk having select count(*) from name_of_composite_type and that would fail. OTOH pg_class where relkind='r' should always work fine.

  • The type of COUNT() is bigint, not int. Tables with more than 2.15 billion rows may exist (running a count(*) on them is a bad idea, though).

  • A permanent type need not to be created for a function to return a resultset with several columns. RETURNS TABLE(definition...) is a better alternative.

SwiftUI - How do I change the background color of a View?

Use Below Code for Navigation Bar Color Customization

struct ContentView: View {

@State var msg = "Hello SwiftUI"
init() {
    UINavigationBar.appearance().backgroundColor = .systemPink

     UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.white,
               .font : UIFont(name:"Helvetica Neue", size: 40)!]

    // 3.
    UINavigationBar.appearance().titleTextAttributes = [
        .font : UIFont(name: "HelveticaNeue-Thin", size: 20)!]

}
var body: some View {
    NavigationView {
    Text(msg)
        .navigationBarTitle(Text("NAVIGATION BAR"))       
    }
    }
}

enter image description here

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

After a long struggle, I found the solution.

Solution: Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.

The method ReadAsAsync is an extension method declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

Reflector came to rescue!

How do we update URL or query strings using javascript/jQuery without reloading the page?

Yes

document.location is the normal way.

However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.

Check out this thread on SO for more info:

What's the difference between window.location and document.location in JavaScript?

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

How to debug in Android Studio using adb over WiFi

if adb command not found.

-----------------------------

Install homebrew

 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Install adb

brew install android-platform-tools

---------------------------

Connect the device now.

  • Enable USB debugging in the Android device
  • Enable Allow ADB debugging in charge only mode
  • Connect the device to the computer via a USB port.

Start using adb

adb devices

List of devices attached
DUM0219A21000314 device

the first item is device id.

adb -s <device id> tcpip 5555

adb -s DUM0219A21000314 tcpip 5555

restarting in TCP mode port: 5555

Find the local IP address of your Android device. You can find this information in the quick settings drop-down menu by pressing / long pressing the WiFi icon and then clicking on the WiFi network you are connected to.

adb connect <IP address>:5555
adb connect 192.168.2.2:5555

connected to 192.168.2.2:5555

Don't forget! Allow ADB debugging in charge only mode enabled before connecting the device

Write Base64-encoded image to file

With Java 8's Base64 API

byte[] decodedImg = Base64.getDecoder()
                    .decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);

If your encoded image starts with something like data:image/png;base64,iVBORw0..., you'll have to remove the part. See this answer for an easy way to do that.

Insert data into table with result from another select query

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`;

MySQL - DATE_ADD month interval

Do I understand right that you assume that DATE_ADD("2011-01-01", INTERVAL 6 MONTH) should give you '2011-06-30' instead of '2011-07-01'? Of course, 2011-01-01 + 6 months is 2011-07-01. You want something like DATE_SUB(DATE_ADD("2011-01-01", INTERVAL 6 MONTH), INTERVAL 1 DAY).

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

<servlet-mapping>
  <servlet-name>server</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

PHP Converting Integer to Date, reverse of strtotime

Yes you can convert it back. You can try:

date("Y-m-d H:i:s", 1388516401);

The logic behind this conversion from date to an integer is explained in strtotime in PHP:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

For example, strtotime("1970-01-01 00:00:00") gives you 0 and strtotime("1970-01-01 00:00:01") gives you 1.

This means that if you are printing strtotime("2014-01-01 00:00:01") which will give you output 1388516401, so the date 2014-01-01 00:00:01 is 1,388,516,401 seconds after January 1 1970 00:00:00 UTC.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

How can I change NULL to 0 when getting a single value from a SQL function?

The easiest way to do this is just to add zero to your result.

i.e.

$A=($row['SUM'Price']+0);
echo $A;

hope this helps!!

MSSQL Error 'The underlying provider failed on Open'

NONE of the answers worked for me

I think that some of us all make silly mistakes, there are 100 ways to fail ...

My issue was new project, I setup all the configuration in another project, but the caller was a Web Api project in which I had to copy the same connection string in the Web api project.

I think this is crazy considering I was not even newing up dbcontext or anything from the web api.

Otherwise the class library was trying to look for a Database named

TokenApi.Core.CalContext   

of which my project is named TokenApi.Core and the CalContext is the name of the connection string and the file name

Set UIButton title UILabel font size programmatically

I hope it will be help to you

[_button.titleLabel setFont:[UIFont systemFontOfSize:15]];  

good luck

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

This error is caused by corrupted proj file.

Visual Studio always has backup project file at specific folder.

Please browse to:

C:\Users\<Your user>\Documents\Visual Studio <Vs version>\Backup Files\<your project>

You should see 2 files like this:

Original-May-18-2018-1209PM.<your project>.csproj
Recovered-May-18-2018-1209PM.<your project>.csproj

You only need copy file:

Original-May-18-2018-1209PM.<your project>.csproj

And re-name as

<your project>.csproj 

and override at root project folder.

Problem is solved!

Passing parameters to a JDBC PreparedStatement

You can use '?' to set custom parameters in string using PreparedStatments.

statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();

If you directly pass userID in query as you are doing then it may get attacked by SQL INJECTION Attack.

How to get the current time as datetime

Here is the SWIFT extension to get your current device location time (GMT).

func getGMTTimeDate() -> Date {
   var comp: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
   comp.calendar = Calendar.current
   comp.timeZone = TimeZone(abbreviation: "GMT")!
   return Calendar.current.date(from: comp)!
}

Get now time:-

Date().getGMTTimeDate()

How to implement linear interpolation?

Instead of extrapolating off the ends, you could return the extents of the y_list. Most of the time your application is well behaved, and the Interpolate[x] will be in the x_list. The (presumably) linear affects of extrapolating off the ends may mislead you to believe that your data is well behaved.

  • Returning a non-linear result (bounded by the contents of x_list and y_list) your program's behavior may alert you to an issue for values greatly outside x_list. (Linear behavior goes bananas when given non-linear inputs!)

  • Returning the extents of the y_list for Interpolate[x] outside of x_list also means you know the range of your output value. If you extrapolate based on x much, much less than x_list[0] or x much, much greater than x_list[-1], your return result could be outside of the range of values you expected.

    def __getitem__(self, x):
        if x <= self.x_list[0]:
            return self.y_list[0]
        elif x >= self.x_list[-1]:
            return self.y_list[-1]
        else:
            i = bisect_left(self.x_list, x) - 1
            return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
    

close fxml window by code, javafx

I'm not sure if this is the best way (or if it works), but you could try:

private void on_btnClose_clicked(ActionEvent actionEvent) {

        Window window = getScene().getWindow();   

        if (window instanceof Stage){
            ((Stage) window).close();
        }
}

(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)

What does the keyword Set actually do in VBA?

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.

Disabling Controls in Bootstrap

Remember for jQuery 1.6+ you should use the .prop() function.

$("input").prop('disabled', true);

$("input").prop('disabled', false);

How to use View.OnTouchListener instead of onClick

OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:

myView.setOnTouchListener(new View.OnTouchListener()
{
    // Implementation;
});

Convert integer to hexadecimal and back again

string HexFromID(int ID)
{
    return ID.ToString("X");
}

int IDFromHex(string HexID)
{
    return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}

I really question the value of this, though. You're stated goal is to make the value shorter, which it will, but that isn't a goal in itself. You really mean either make it easier to remember or easier to type.

If you mean easier to remember, then you're taking a step backwards. We know it's still the same size, just encoded differently. But your users won't know that the letters are restricted to 'A-F', and so the ID will occupy the same conceptual space for them as if the letter 'A-Z' were allowed. So instead of being like memorizing a telephone number, it's more like memorizing a GUID (of equivalent length).

If you mean typing, instead of being able to use the keypad the user now must use the main part of the keyboard. It's likely to be more difficult to type, because it won't be a word their fingers recognize.

A much better option is to actually let them pick a real username.

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

Using Tkinter in python to edit the title bar

For anybody who runs into the issue of having two windows open, and runs across this question. Here is how I stumbled upon a solution.

The reason the code in this question is producing two windows is because

Frame.__init__(self, parent)

is being run before

self.root = Tk()

The simple fix is to run Tk() before running Frame.__init_()

self.root = Tk()
Frame.__init__(self, parent)

Why that is the case, I'm not entirely sure.

Convert month int to month name

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

Why would one use nested classes in C++?

I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.

For example, consider a generic Field class that has an ID number, a type code and a field name. If I want to search a vector of these Fields by either ID number or name, I might construct a functor to do so:

class Field
{
public:
  unsigned id_;
  string name_;
  unsigned type_;

  class match : public std::unary_function<bool, Field>
  {
  public:
    match(const string& name) : name_(name), has_name_(true) {};
    match(unsigned id) : id_(id), has_id_(true) {};
    bool operator()(const Field& rhs) const
    {
      bool ret = true;
      if( ret && has_id_ ) ret = id_ == rhs.id_;
      if( ret && has_name_ ) ret = name_ == rhs.name_;
      return ret;
    };
    private:
      unsigned id_;
      bool has_id_;
      string name_;
      bool has_name_;
  };
};

Then code that needs to search for these Fields can use the match scoped within the Field class itself:

vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));

MySQL update CASE WHEN/THEN/ELSE

That's because you missed ELSE.

"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)

referenced before assignment error in python

def inside():
   global var
   var = 'info'
inside()
print(var)

>>>'info'

problem ended

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

php hide ALL errors

To hide errors only from users but displaying logs errors in apache log

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

1 - Displaying error only in log
2 - hide from users

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx) http://www.ofx.net/

This is what apps like quicken, ms money etc use.

MySQL: @variable vs. variable. What's the difference?

@variable is very useful if calling stored procedures from an application written in Java , Python etc. There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.

Side-note on PL/SQL (Oracle)

The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:

  • Function variable for which the scope ends when function exits.
  • Package body variables defined at the top of package and outside all functions whose scope is the session and visibility is package.
  • Package variable whose variable is session and visibility is global.

My Experience in PL/SQL

I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.

I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.

Opinion towards @ in MySQL

I am happy to see that at least this @ facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.

Get the data received in a Flask request

To get request.form as a normal dictionary , use request.form.to_dict(flat=False).

To return JSON data for an API, pass it to jsonify.

This example returns form data as JSON data.

@app.route('/form_to_json', methods=['POST'])
def form_to_json():
    data = request.form.to_dict(flat=False)
    return jsonify(data)

Here's an example of POST form data with curl, returning as JSON:

$ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer"
{
  "name": "ivanleoncz", 
  "role": "Software Developer"
}

Is it possible to read from a InputStream with a timeout?

As jt said, NIO is the best (and correct) solution. If you really are stuck with an InputStream though, you could either

  1. Spawn a thread who's exclusive job is to read from the InputStream and put the result into a buffer which can be read from your original thread without blocking. This should work well if you only ever have one instance of the stream. Otherwise you may be able to kill the thread using the deprecated methods in the Thread class, though this may cause resource leaks.

  2. Rely on isAvailable to indicate data that can be read without blocking. However in some cases (such as with Sockets) it can take a potentially blocking read for isAvailable to report something other than 0.

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE allitems
CHANGE itemid itemid INT(10) AUTO_INCREMENT;

Spring MVC: how to create a default controller for index page?

It can be solved in more simple way: in web.xml

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>

After that use any controllers that your want to process index.htm with @RequestMapping("index.htm"). Or just use index controller

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="index.htm">indexController</prop>
        </props>
    </property>
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="index" />
</bean>

python pip on Windows - command 'cl.exe' failed

I had come across this problem many times. There is cl.exe but for some strange reason pip couldn't find it, even if we run the command from the bin folder where cl.exe is present. Try using conda installer, it worked fine for me.

As you can see in the following image, pip is not able to find the cl.exe. Then I tried installing using conda

image 1

And to my surprise it gets installed without an error once you have the right version of vs cpp build tools installed, i.e. v14.0 in the right directory.

image 2

Get dates from a week number in T-SQL

I've taken elindeblom's solution and modified it - the use of strings (even if cast to dates) makes me nervous for the different formats of dates used around the world. This avoids that issue.

While not requested, I've also included time so the week ends 1 second before midnight:

    DECLARE @WeekNum INT = 12,
        @YearNum INT = 2014 ;

    SELECT  DATEADD(wk,
                    DATEDIFF(wk, 6,
                             CAST(RTRIM(@YearNum * 10000 + 1 * 100 + 1) AS DATETIME))
                    + ( @WeekNum - 1 ), 6) AS [start_of_week],
            DATEADD(second, -1,
                    DATEADD(day,
                            DATEDIFF(day, 0,
                                     DATEADD(wk,
                                             DATEDIFF(wk, 5,
                                                      CAST(RTRIM(@YearNum * 10000
                                                                 + 1 * 100 + 1) AS DATETIME))
                                             + ( @WeekNum + -1 ), 5)) + 1, 0)) AS [end_of_week] ;

Yes, I know I'm still casting but from a number. It "feels" safer to me.

This results in:

    start_of_week           end_of_week
    ----------------------- -----------------------
    2014-03-16 00:00:00.000 2014-03-22 23:59:59.000

Finding the 'type' of an input element

Check the type property. Would that suffice?

Smooth scroll without the use of jQuery

Try this smooth scrolling demo, or an algorithm like:

  1. Get the current top location using self.pageYOffset
  2. Get the position of element till where you want to scroll to: element.offsetTop
  3. Do a for loop to reach there, which will be quite fast or use a timer to do smooth scroll till that position using window.scrollTo

See also the other popular answer to this question.


Andrew Johnson's original code:

function currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}


function elmYPosition(eID) {
    var elm = document.getElementById(eID);
    var y = elm.offsetTop;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
    } return y;
}


function smoothScroll(eID) {
    var startY = currentYPosition();
    var stopY = elmYPosition(eID);
    var distance = stopY > startY ? stopY - startY : startY - stopY;
    if (distance < 100) {
        scrollTo(0, stopY); return;
    }
    var speed = Math.round(distance / 100);
    if (speed >= 20) speed = 20;
    var step = Math.round(distance / 25);
    var leapY = stopY > startY ? startY + step : startY - step;
    var timer = 0;
    if (stopY > startY) {
        for ( var i=startY; i<stopY; i+=step ) {
            setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
            leapY += step; if (leapY > stopY) leapY = stopY; timer++;
        } return;
    }
    for ( var i=startY; i>stopY; i-=step ) {
        setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
        leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
    }
}

Related links:

How to call servlet through a JSP page

there isn't method to call Servlet. You should make mapping in web.xml and then trigger this mapping.

Example: web.xml:

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>test.HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

This mapping means that every call to http://yoursite/yourwebapp/hello trigger this servlet For example this jsp:

<jsp:forward page="/hello"/> 

Segmentation fault on large array sizes

Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:

ulimit -s unlimited

But be careful, memory is a limited resource and with great power come great responsibilities :)

How many bytes does one Unicode character take?

You won't see a simple answer because there isn't one.

First, Unicode doesn't contain "every character from every language", although it sure does try.

Unicode itself is a mapping, it defines codepoints and a codepoint is a number, associated with usually a character. I say usually because there are concepts like combining characters. You may be familiar with things like accents, or umlauts. Those can be used with another character, such as an a or a u to create a new logical character. A character therefore can consist of 1 or more codepoints.

To be useful in computing systems we need to choose a representation for this information. Those are the various unicode encodings, such as utf-8, utf-16le, utf-32 etc. They are distinguished largely by the size of of their codeunits. UTF-32 is the simplest encoding, it has a codeunit that is 32bits, which means an individual codepoint fits comfortably into a codeunit. The other encodings will have situations where a codepoint will need multiple codeunits, or that particular codepoint can't be represented in the encoding at all (this is a problem for instance with UCS-2).

Because of the flexibility of combining characters, even within a given encoding the number of bytes per character can vary depending on the character and the normalization form. This is a protocol for dealing with characters which have more than one representation (you can say "an 'a' with an accent" which is 2 codepoints, one of which is a combining char or "accented 'a'" which is one codepoint).

How to add a column in TSQL after a specific column?

solution:

This will work for tables where there are no dependencies on the changing table which would trigger cascading events. First make sure you can drop the table you want to restructure without any disastrous repercussions. Take a note of all the dependencies and column constraints associated with your table (i.e. triggers, indexes, etc.). You may need to put them back in when you are done.

STEP 1: create the temp table to hold all the records from the table you want to restructure. Do not forget to include the new column.

CREATE TABLE #tmp_myTable
(   [new_column] [int] NOT NULL, <-- new column has been inserted here!
    [idx] [bigint] NOT NULL,
    [name] [nvarchar](30) NOT NULL,
    [active] [bit] NOT NULL
)

STEP 2: Make sure all records have been copied over and that the column structure looks the way you want.

SELECT TOP 10 * FROM #tmp_myTable ORDER BY 1 DESC -- you can do COUNT(*) or anything to make sure you copied all the records

STEP 3: DROP the original table:

DROP TABLE myTable

If you are paranoid about bad things could happen, just rename the original table (instead of dropping it). This way it can be always returned back.

EXEC sp_rename myTable, myTable_Copy

STEP 4: Recreate the table myTable the way you want (should match match the #tmp_myTable table structure)

CREATE TABLE myTable
(   [new_column] [int] NOT NULL,
    [idx] [bigint] NOT NULL,
    [name] [nvarchar](30) NOT NULL,
    [active] [bit] NOT NULL
)

-- do not forget any constraints you may need

STEP 5: Copy the all the records from the temp #tmp_myTable table into the new (improved) table myTable.

INSERT INTO myTable ([new_column],[idx],[name],[active])
SELECT [new_column],[idx],[name],[active]
FROM #tmp_myTable

STEP 6: Check if all the data is back in your new, improved table myTable. If yes, clean up after yourself and DROP the temp table #tmp_myTable and the myTable_Copy table if you chose to rename it instead of dropping it.

How to get the list of all database users

EXEC sp_helpuser

or

SELECT * FROM sysusers

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

How to decrypt a password from SQL server?

The SQL Server password hashing algorithm:

hashBytes = 0x0100 | fourByteSalt | SHA1(utf16EncodedPassword+fourByteSalt)

For example, to hash the password "correct horse battery staple". First we generate some random salt:

fourByteSalt = 0x9A664D79;

And then hash the password (encoded in UTF-16) along with the salt:

 SHA1("correct horse battery staple" + 0x9A66D79);
=SHA1(0x63006F007200720065006300740020006200610074007400650072007900200068006F00720073006500200073007400610070006C006500 0x9A66D79)
=0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

The value stored in the syslogins table is the concatenation of:

[header] + [salt] + [hash]
0x0100 9A664D79 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

Which you can see in SQL Server:

SELECT 
   name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins
WHERE name = 'sa'

name  PasswordHash
====  ======================================================
sa    0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
  • Version header: 0100
  • Salt (four bytes): 9A664D79
  • Hash: 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3 (SHA-1 is 20 bytes; 160 bits)

Validation

You validate a password by performing the same hash:

  • grab the salt from the saved PasswordHash: 0x9A664D79

and perform the hash again:

SHA1("correct horse battery staple" + 0x9A66D79);

which will come out to the same hash, and you know the password is correct.

What once was good, but now is weak

The hashing algorithm introduced with SQL Server 7, in 1999, was good for 1999.

  • It is good that the password hash salted.
  • It is good to append the salt to the password, rather than prepend it.

But today it is out-dated. It only runs the hash once, where it should run it a few thousand times, in order to thwart brute-force attacks.

In fact, Microsoft's Baseline Security Analyzer will, as part of it's checks, attempt to bruteforce passwords. If it guesses any, it reports the passwords as weak. And it does get some.

Brute Forcing

To help you test some passwords:

DECLARE @hash varbinary(max)
SET @hash = 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
--Header: 0x0100
--Salt:   0x9A664D79
--Hash:   0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

DECLARE @password nvarchar(max)
SET @password = 'password'

SELECT
    @password AS CandidatePassword,
    @hash AS PasswordHash,

    --Header
    0x0100
    +
    --Salt
    CONVERT(VARBINARY(4), SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))
    +
    --SHA1 of Password + Salt
    HASHBYTES('SHA1', @password + SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))

SQL Server 2012 and SHA-512

Starting with SQL Server 2012, Microsoft switched to using SHA-2 512-bit:

hashBytes = 0x0200 | fourByteSalt | SHA512(utf16EncodedPassword+fourByteSalt)

Changing the version prefix to 0x0200:

SELECT 
   name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins

name  PasswordHash
----  --------------------------------
xkcd  0x02006A80BA229556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
  • Version: 0200 (SHA-2 256-bit)
  • Salt: 6A80BA22
  • Hash (64 bytes): 9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38

This means we hash the UTF-16 encoded password, with the salt suffix:

  • SHA512("correct horse battery staple"+6A80BA22)
  • SHA512(63006f0072007200650063007400200068006f0072007300650020006200610074007400650072007900200073007400610070006c006500 + 6A80BA22)
  • 9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38

Combine several images horizontally with Python

Here is a function generalizing previous approaches, creating a grid of images in PIL:

from PIL import Image
import numpy as np

def pil_grid(images, max_horiz=np.iinfo(int).max):
    n_images = len(images)
    n_horiz = min(n_images, max_horiz)
    h_sizes, v_sizes = [0] * n_horiz, [0] * (n_images // n_horiz)
    for i, im in enumerate(images):
        h, v = i % n_horiz, i // n_horiz
        h_sizes[h] = max(h_sizes[h], im.size[0])
        v_sizes[v] = max(v_sizes[v], im.size[1])
    h_sizes, v_sizes = np.cumsum([0] + h_sizes), np.cumsum([0] + v_sizes)
    im_grid = Image.new('RGB', (h_sizes[-1], v_sizes[-1]), color='white')
    for i, im in enumerate(images):
        im_grid.paste(im, (h_sizes[i % n_horiz], v_sizes[i // n_horiz]))
    return im_grid

It will shrink each row and columns of the grid to the minimum. You can have only a row by using pil_grid(images), or only a column by using pil_grid(images, 1).

One benefit of using PIL over numpy-array based solutions is that you can deal with images structured differently (like grayscale or palette-based images).

Example outputs

def dummy(w, h):
    "Produces a dummy PIL image of given dimensions"
    from PIL import ImageDraw
    im = Image.new('RGB', (w, h), color=tuple((np.random.rand(3) * 255).astype(np.uint8)))
    draw = ImageDraw.Draw(im)
    points = [(i, j) for i in (0, im.size[0]) for j in (0, im.size[1])]
    for i in range(len(points) - 1):
        for j in range(i+1, len(points)):
            draw.line(points[i] + points[j], fill='black', width=2)
    return im

dummy_images = [dummy(20 + np.random.randint(30), 20 + np.random.randint(30)) for _ in range(10)]

pil_grid(dummy_images):

line.png

pil_grid(dummy_images, 3):

enter image description here

pil_grid(dummy_images, 1):

enter image description here

How to export specific request to file using postman?

You can export collection by clicking on arrow button

enter image description here

and then click on download collection button

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Bring a window to the front in WPF

If you are trying to hide the window, for example you minimize the window, I have found that using

    this.Hide();

will hide it correctly, then simply using

    this.Show();

will then show the window as the top most item once again.

Java Garbage Collection Log messages

I just wanted to mention that one can get the detailed GC log with the

-XX:+PrintGCDetails 

parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

Example usage:

java -Xloggc:./memory.log -XX:+PrintGCDetails Memory

To visualize the data better you can try gcviewer (a more recent version can be found on github).

Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

How to make scipy.interpolate give an extrapolated result beyond the input range?

As of SciPy version 0.17.0, there is a new option for scipy.interpolate.interp1d that allows extrapolation. Simply set fill_value='extrapolate' in the call. Modifying your code in this way gives:

import numpy as np
from scipy import interpolate

x = np.arange(0,10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y, fill_value='extrapolate')

print f(9)
print f(11)

and the output is:

0.0497870683679
0.010394302658

Check if input is integer type in C

This method works for everything (integers and even doubles) except zero (it calls it invalid):

The while loop is just for the repetitive user input. Basically it checks if the integer x/x = 1. If it does (as it would with a number), its an integer/double. If it doesn't, it obviously it isn't. Zero fails the test though.

#include <stdio.h> 
#include <math.h>

void main () {
    double x;
    int notDouble;
    int true = 1;
    while(true) {
        printf("Input an integer: \n");
        scanf("%lf", &x);
        if (x/x != 1) {
            notDouble = 1;
            fflush(stdin);
        }
        if (notDouble != 1) {
            printf("Input is valid\n");
        }
        else {
            printf("Input is invalid\n");
        }
        notDouble = 0;
    }
}

How do I perform the SQL Join equivalent in MongoDB?

You can do it using the aggregation pipeline, but it's a pain to write it yourself.

You can use mongo-join-query to create the aggregation pipeline automatically from your query.

This is how your query would look like:

const mongoose = require("mongoose");
const joinQuery = require("mongo-join-query");

joinQuery(
    mongoose.models.Comment,
    {
        find: { pid:444 },
        populate: ["uid"]
    },
    (err, res) => (err ? console.log("Error:", err) : console.log("Success:", res.results))
);

Your result would have the user object in the uid field and you can link as many levels deep as you want. You can populate the reference to the user, which makes reference to a Team, which makes reference to something else, etc..

Disclaimer: I wrote mongo-join-query to tackle this exact problem.

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

Where to put a textfile I want to use in eclipse?

You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.

How can I keep Bootstrap popovers alive while being hovered?

I think an easy way would be this:

$('.popover').each(function () {
                    var $this = $(this);
                    $this.popover({
                        trigger: 'hover',
                        content: 'Content Here',
                        container: $this
                    })
                });

This way the popover is created inside the target element itself. so when you move your mouse over the popover, it's still over the element. Bootstrap 3.3.2 works well with this. Older version may have some problems with animation, so you may want to disable "animation:false"

Using C++ base class constructors?

Prefer initialization:

class C : public A
{
public:
    C(const string &val) : A(anInt) {}
};

In C++11, you can use inheriting constructors (which has the syntax seen in your example D).

Update: Inheriting Constructors have been available in GCC since version 4.8.


If you don't find initialization appealing (e.g. due to the number of possibilities in your actual case), then you might favor this approach for some TMP constructs:

class A
{
public: 
    A() {}
    virtual ~A() {}
    void init(int) { std::cout << "A\n"; }
};

class B : public A
{
public:
    B() : A() {}
    void init(int) { std::cout << "B\n"; }
};

class C : public A
{
public:
    C() : A() {}
    void init(int) { std::cout << "C\n"; }
};

class D : public A
{
public:
    D() : A() {}
    using A::init;
    void init(const std::string& s) { std::cout << "D -> " << s << "\n"; }
};

int main()
{
    B b; b.init(10);
    C c; c.init(10);
    D d; d.init(10); d.init("a");

    return 0;
}

removing table border

From your case, you need to set the border to none on <table> and <td> tags.

    <table width=1000 style="border:none; border-collapse:collapse; cellspacing:0; cellpadding:0" >
        <tr>
            <td style="border:none" rowspan=2>
                <img src="/Content/Images/elk_banner.jpg" />
            </td>
            <td style="border:none">
                <div id="logindisplay">
                    @Html.Partial("_LogOnPartial")
                </div>
            </td>
        </tr>
    </table>

Change one value based on another value in pandas

This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.

In this way it's possible to avoid key errors.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
...     def __missing__(self, key):
...         return ''
...     
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

The same thing can be done more simply in the following way. The use of the 'default' argument for the get method of a dict object makes it unnecessary to subclass a dict.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

Find index of last occurrence of a substring in a string

Use .rfind():

>>> s = 'hello'
>>> s.rfind('l')
3

Also don't use str as variable name or you'll shadow the built-in str().

Determining Referer in PHP

There is no reliable way to check this. It's really under client's hand to tell you where it came from. You could imagine to use cookie or sessions informations put only on some pages of your website, but doing so your would break user experience with bookmarks.

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

Helper function to copy rows shamelessly adapted from here

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class RowCopy {

    public static void main(String[] args) throws Exception{
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("c:/input.xls"));
        HSSFSheet sheet = workbook.getSheet("Sheet1");
        copyRow(workbook, sheet, 0, 1);
        FileOutputStream out = new FileOutputStream("c:/output.xls");
        workbook.write(out);
        out.close();
    }

    private static void copyRow(HSSFWorkbook workbook, HSSFSheet worksheet, int sourceRowNum, int destinationRowNum) {
        // Get the source / new row
        HSSFRow newRow = worksheet.getRow(destinationRowNum);
        HSSFRow sourceRow = worksheet.getRow(sourceRowNum);

        // If the row exist in destination, push down all rows by 1 else create a new row
        if (newRow != null) {
            worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
        } else {
            newRow = worksheet.createRow(destinationRowNum);
        }

        // Loop through source columns to add to new row
        for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
            // Grab a copy of the old/new cell
            HSSFCell oldCell = sourceRow.getCell(i);
            HSSFCell newCell = newRow.createCell(i);

            // If the old cell is null jump to next cell
            if (oldCell == null) {
                newCell = null;
                continue;
            }

            // Copy style from old cell and apply to new cell
            HSSFCellStyle newCellStyle = workbook.createCellStyle();
            newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
            ;
            newCell.setCellStyle(newCellStyle);

            // If there is a cell comment, copy
            if (oldCell.getCellComment() != null) {
                newCell.setCellComment(oldCell.getCellComment());
            }

            // If there is a cell hyperlink, copy
            if (oldCell.getHyperlink() != null) {
                newCell.setHyperlink(oldCell.getHyperlink());
            }

            // Set the cell data type
            newCell.setCellType(oldCell.getCellType());

            // Set the cell data value
            switch (oldCell.getCellType()) {
                case Cell.CELL_TYPE_BLANK:
                    newCell.setCellValue(oldCell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    newCell.setCellValue(oldCell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_ERROR:
                    newCell.setCellErrorValue(oldCell.getErrorCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    newCell.setCellFormula(oldCell.getCellFormula());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    newCell.setCellValue(oldCell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    newCell.setCellValue(oldCell.getRichStringCellValue());
                    break;
            }
        }

        // If there are are any merged regions in the source row, copy to new row
        for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
            CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
            if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
                CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
                        (newRow.getRowNum() +
                                (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow()
                                        )),
                        cellRangeAddress.getFirstColumn(),
                        cellRangeAddress.getLastColumn());
                worksheet.addMergedRegion(newCellRangeAddress);
            }
        }
    }
}

Cookie blocked/not saved in IFRAME in Internet Explorer

This is buried in the comments of other answers, but I almost missed it, so it seems like it deserves its own answer.

To review: in order for IE to accept 3rd party cookies, you need serve your files with an http header called p3p in the format:

CP="my compact p3p policy"

BUT, p3p is pretty much dead as a standard at this point and you can easily get IE to work without investing the time and legal resources in creating a real p3p policy. This is because if your compact p3p policy header is invalid, IE actually treats it as a good policy and accepts 3rd party cookies. So you can use a p3p header such as this

CP="This site does not have a p3p policy."

You can optionally include a link to a page that explains why you don't have a p3p policy, as Google and Facebook do (they point here: https://support.google.com/accounts/answer/151657 and here: https://www.facebook.com/help/327993273962160/).

Finally, it's important to note that all files served from the 3rd party site need to have the p3p header, not just the one that sets the cookie, so you may not be able to just do this in your PHP, asp.net, etc code. You are probably better off setting in up on the web server level (i.e. in IIS or Apache).

How do I disable fail_on_empty_beans in Jackson?

You can also probably annotate the class with @JsonIgnoreProperties(ignoreUnknown=true) to ignore the fields undefined in the class

Add leading zeroes/0's to existing Excel values to certain length

If you use custom formatting and need to concatenate those values elsewhere, you can copy them and Paste Special --> Values elsewhere in the sheet (or on a different sheet), then concatenate those values.

Reading Datetime value From Excel sheet

Or you can simply use OleDbDataAdapter to get data from Excel

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

CREATE TABLE LIKE A1 as A2

For MySQL, you can do it like this:

CREATE TABLE New_Users   SELECT * FROM Old_Users group by ID;

Text Editor For Linux (Besides Vi)?

When I searched for TextMate alternative for Linux, I ended up using Geany. It's not as powerfull, but still nice to work with. Great replacement for Kate.

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

javascript: pause setTimeout();

If anyone wants the TypeScript version shared by the Honorable @SeanVieira here, you can use this:

    public timer(fn: (...args: any[]) => void, countdown: number): { onCancel: () => void, onPause: () => void, onResume: () => void } {
        let ident: NodeJS.Timeout | number;
        let complete = false;
        let totalTimeRun: number;
        const onTimeDiff = (date1: number, date2: number) => {
            return date2 ? date2 - date1 : new Date().getTime() - date1;
        };

        const handlers = {
            onCancel: () => {
                clearTimeout(ident as NodeJS.Timeout);
            },
            onPause: () => {
                clearTimeout(ident as NodeJS.Timeout);
                totalTimeRun = onTimeDiff(startTime, null);
                complete = totalTimeRun >= countdown;
            },
            onResume: () => {
                ident = complete ? -1 : setTimeout(fn, countdown - totalTimeRun);
            }
        };

        const startTime = new Date().getTime();
        ident = setTimeout(fn, countdown);

        return handlers;
    }

using lodash .groupBy. how to add your own keys for grouped output?

In 2017 do so

_.chain(data)
  .groupBy("color")
  .toPairs()
  .map(item => _.zipObject(["color", "users"], item))
  .value();

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

Why is nginx responding to any domain name?

The first server block in the nginx config is the default for all requests that hit the server for which there is no specific server block.

So in your config, assuming your real domain is REAL.COM, when a user types that in, it will resolve to your server, and since there is no server block for this setup, the server block for FAKE.COM, being the first server block (only server block in your case), will process that request.

This is why proper Nginx configs have a specific server block for defaults before following with others for specific domains.

# Default server
server {
    return 404;
}

server {
    server_name domain_1;
    [...]
}

server {
    server_name domain_2;
    [...]
}

etc

** EDIT **

It seems some users are a bit confused by this example and think it is limited to a single conf file etc.

Please note that the above is a simple example for the OP to develop as required.

I personally use separate vhost conf files with this as so (CentOS/RHEL):

http {
    [...]
    # Default server
    server {
        return 404;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

/etc/nginx/conf.d/ will contain domain_1.conf, domain_2.conf... domain_n.conf which will be included after the server block in the main nginx.conf file which will always be the first and will always be the default unless it is overridden it with the default_server directive elsewhere.

The alphabetical order of the file names of the conf files for the other servers becomes irrelevant in this case.

In addition, this arrangement gives a lot of flexibility in that it is possible to define multiple defaults.

In my specific case, I have Apache listening on Port 8080 on the internal interface only and I proxy PHP and Perl scripts to Apache.

However, I run two separate applications that both return links with ":8080" in the output html attached as they detect that Apache is not running on the standard Port 80 and try to "help" me out.

This causes an issue in that the links become invalid as Apache cannot be reached from the external interface and the links should point at Port 80.

I resolve this by creating a default server for Port 8080 to redirect such requests.

http {
    [...]
    # Default server block for undefined domains
    server {
        listen 80;
        return 404;
    }
    # Default server block to redirect Port 8080 for all domains
    server {
        listen my.external.ip.addr:8080;
        return 301 http://$host$request_uri;
    }
    # Other servers
    include /etc/nginx/conf.d/*.conf;
}

As nothing in the regular server blocks listens on Port 8080, the redirect default server block transparently handles such requests by virtue of its position in nginx.conf.

I actually have four of such server blocks and this is a simplified use case.

Staging Deleted files

If you want to simply add all the deleted files to stage then you can use git add .

This is the easiest way right now with git v2.27.0. Note that using * and . are different approaches. Using git add * would only add currently present files whereas git add . would also stage the files deleted with rm command.

It's obvious but worth mentioning that other files which have been modified would also be added to the staging area when you use git add ..

Permission denied (publickey,keyboard-interactive)

You may want to double check the authorized_keys file permissions:

$ chmod 600 ~/.ssh/authorized_keys

Newer SSH server versions are very picky on this respect.