Programs & Examples On #Language details

How to install Selenium WebDriver on Mac OS

Mac already has Python and a package manager called easy_install, so open Terminal and type

sudo easy_install selenium

Android View shadow

Use the elevation property for shadow affect:

<YourView
    ...
    android:elevation="3dp"/>

Difference between jQuery’s .hide() and setting CSS to display: none

.hide() stores the previous display property just before setting it to none, so if it wasn't the standard display property for the element you're a bit safer, .show() will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Android Marshmallow many methods are deprecated.

For example, to get color use

ContextCompat.getColor(context, R.color.color_name);

Also to get drawable use

ContextCompat.getDrawable(context, R.drawable.drawble_name);

How to set image for bar button with swift?

Only two Lines of code required for this

Swift 3.0

let closeButtonImage = UIImage(named: "ic_close_white")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(ResetPasswordViewController.barButtonDidTap(_:)))

func barButtonDidTap(_ sender: UIBarButtonItem) 
{

}

How to return JSON data from spring Controller using @ResponseBody

Add the below dependency to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>

What is a semaphore?

A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.

How to change the background color of a UIButton while it's highlighted?

UIButton extension with Swift 3+ syntax:

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.setBackgroundImage(colorImage, for: forState)
    }}

Use it like:

YourButton.setBackgroundColor(color: UIColor.white, forState: .highlighted)

Original Answer: https://stackoverflow.com/a/30604658/3659227

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

String, StringBuffer, and StringBuilder

----------------------------------------------------------------------------------
                  String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                 
Storage Area | Constant String Pool         Heap                   Heap 
Modifiable   |  No (immutable)              Yes( mutable )         Yes( mutable )
Thread Safe  |      Yes                     Yes                     No
 Performance |     Fast                 Very slow                  Fast
----------------------------------------------------------------------------------

How do I remove a file from the FileList

This is extemporary, but I had the same problem which I solved this way. In my case I was uploading the files via XMLHttp request, so I was able to post the FileList cloned data through formdata appending. Functionality is that you can drag and drop or select multiple files as many times as you want (selecting files again won't reset the cloned FileList), remove any file you want from the (cloned) file list, and submit via xmlhttprequest whatever was left there. This is what I did. It is my first post here so code is a little messy. Sorry. Ah, and I had to use jQuery instead of $ as it was in Joomla script.

// some global variables
var clon = {};  // will be my FileList clone
var removedkeys = 0; // removed keys counter for later processing the request
var NextId = 0; // counter to add entries to the clone and not replace existing ones

jQuery(document).ready(function(){
    jQuery("#form input").change(function () {

    // making the clone
    var curFiles = this.files;
    // temporary object clone before copying info to the clone
    var temparr = jQuery.extend(true, {}, curFiles);
    // delete unnecessary FileList keys that were cloned
    delete temparr["length"];
    delete temparr["item"];

    if (Object.keys(clon).length === 0){
       jQuery.extend(true, clon, temparr);
    }else{
       var keysArr = Object.keys(clon);
       NextId = Math.max.apply(null, keysArr)+1; // FileList keys are numbers
       if (NextId < curFiles.length){ // a bug I found and had to solve for not replacing my temparr keys...
          NextId = curFiles.length;
       }
       for (var key in temparr) { // I have to rename new entries for not overwriting existing keys in clon
          if (temparr.hasOwnProperty(key)) {
             temparr[NextId] = temparr[key];
             delete temparr[key];
                // meter aca los cambios de id en los html tags con el nuevo NextId
                NextId++;
          }
       } 
       jQuery.extend(true, clon, temparr); // copy new entries to clon
    }

// modifying the html file list display

if (NextId === 0){
    jQuery("#filelist").html("");
    for(var i=0; i<curFiles.length; i++) {
        var f = curFiles[i];
        jQuery("#filelist").append("<p id=\"file"+i+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+i+")\">x</a></p>"); // the function BorrarFile will handle file deletion from the clone by file id
    }
}else{
    for(var i=0; i<curFiles.length; i++) {
        var f = curFiles[i];
        jQuery("#filelist").append("<p id=\"file"+(i+NextId-curFiles.length)+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+(i+NextId-curFiles.length)+")\">x</a></p>"); // yeap, i+NextId-curFiles.length actually gets it right
    }        
}
// update the total files count wherever you want
jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
    });
});

function BorrarFile(id){ // handling file deletion from clone
    jQuery("#file"+id).remove(); // remove the html filelist element
    delete clon[id]; // delete the entry
    removedkeys++; // add to removed keys counter
    if (Object.keys(clon).length === 0){
        jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
        jQuery("#fileToUpload").val(""); // I had to reset the form file input for my form check function before submission. Else it would send even though my clone was empty
    }else{
        jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
    }
}
// now my form check function

function check(){
    if( document.getElementById("fileToUpload").files.length == 0 ){
        alert("No file selected");
        return false;
    }else{
        var _validFileExtensions = [".pdf", ".PDF"]; // I wanted pdf files
        // retrieve input files
        var arrInputs = clon;

       // validating files
       for (var i = 0; i < Object.keys(arrInputs).length+removedkeys; i++) {
         if (typeof arrInputs[i]!="undefined"){
           var oInput = arrInputs[i];
           if (oInput.type == "application/pdf") {
               var sFileName = oInput.name;
               if (sFileName.length > 0) {
                   var blnValid = false;
                   for (var j = 0; j < _validFileExtensions.length; j++) {
                     var sCurExtension = _validFileExtensions[j];
                     if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                       blnValid = true;
                       break;
                     }
                   }
                  if (!blnValid) {
                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                    return false;
                  }
              }
           }else{
           alert("Sorry, " + arrInputs[0].name + " is invalid, allowed extensions are: " + _validFileExtensions.join(" or "));
           return false;
           }
         }
       }

    // proceed with the data appending and submission
    // here some hidden input values i had previously set. Now retrieving them for submission. My form wasn't actually even a form...
    var fecha = jQuery("#fecha").val();
    var vendor = jQuery("#vendor").val();
    var sku = jQuery("#sku").val();
    // create the formdata object
    var formData = new FormData();
    formData.append("fecha", fecha);
    formData.append("vendor", encodeURI(vendor));
    formData.append("sku", sku);
    // now appending the clone file data (finally!)
    var fila = clon; // i just did this because I had already written the following using the "fila" object, so I copy my clone again
    // the interesting part. As entries in my clone object aren't consecutive numbers I cannot iterate normally, so I came up with the following idea
    for (i = 0; i < Object.keys(fila).length+removedkeys; i++) { 
        if(typeof fila[i]!="undefined"){
            formData.append("fileToUpload[]", fila[i]); // VERY IMPORTANT the formdata key for the files HAS to be an array. It will be later retrieved as $_FILES['fileToUpload']['temp_name'][i]
        }
    }
    jQuery("#submitbtn").fadeOut("slow"); // remove the upload btn so it can't be used again
    jQuery("#drag").html(""); // clearing the output message element
    // start the request
    var xhttp = new XMLHttpRequest();
    xhttp.addEventListener("progress", function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
        }, false);
        if ( xhttp.upload ) {
            xhttp.upload.onprogress = function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                var percent = done / total;
                jQuery("#drag").html(Math.round(percent * 100) + "%");
            };
        }
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         var respuesta = this.responseText;
         jQuery("#drag").html(respuesta);
        }
      };
      xhttp.open("POST", "your_upload_handler.php", true);  
      xhttp.send(formData);
    return true;
    }
};

Now the html and styles for this. I'm quite a newbie but all this actually worked for me and took me a while to figure it out.

<div id="form" class="formpos">
<!--    Select the pdf to upload:-->
  <input type="file" name="fileToUpload[]" id="fileToUpload" accept="application/pdf" multiple>
  <div><p id="drag">Drop your files here or click to select them</p>
  </div>
  <button id="submitbtn" onclick="return check()" >Upload</button>
// these inputs are passed with different names on the formdata. Be aware of that
// I was echoing this, so that's why I use the single quote for php variables
  <input type="hidden" id="fecha" name="fecha_copy" value="'.$fecha.'" />
  <input type="hidden" id="vendor" name="vendorname" value="'.$vendor.'" />
  <input type="hidden" id="sku" name="sku" value="'.$sku.'"" />
</div>
<h1 style="width: 500px!important;margin:20px auto 0px!important;font-size:24px!important;">File list:</h1>
<div id="filelist" style="width: 500px!important;margin:10px auto 0px!important;">Nothing selected yet</div>

The styles for that. I had to mark some of them !important to override Joomla behavior.

.formpos{
  width: 500px;
  height: 200px;
  border: 4px dashed #999;
  margin: 30px auto 100px;
 }
.formpos  p{
  text-align: center!important;
  padding: 80px 30px 0px;
  color: #000;
}
.formpos  div{
  width: 100%!important;
  height: 100%!important;
  text-align: center!important;
  margin-bottom: 30px!important;
}
.formpos input{
  position: absolute!important;
  margin: 0!important;
  padding: 0!important;
  width: 500px!important;
  height: 200px!important;
  outline: none!important;
  opacity: 0!important;
}
.formpos button{
  margin: 0;
  color: #fff;
  background: #16a085;
  border: none;
  width: 508px;
  height: 35px;
  margin-left: -4px;
  border-radius: 4px;
  transition: all .2s ease;
  outline: none;
}
.formpos button:hover{
  background: #149174;
  color: #0C5645;
}
.formpos button:active{
  border:0;
}

I hope this helps.

Hibernate: flush() and commit()

It is usually not recommended to call flush explicitly unless it is necessary. Hibernate usually auto calls Flush at the end of the transaction and we should let it do it's work. Now, there are some cases where you might need to explicitly call flush where a second task depends upon the result of the first Persistence task, both being inside the same transaction.

For example, you might need to persist a new Entity and then use the Id of that Entity to do some other task inside the same transaction, on that case it's required to explicitly flush the entity first.

@Transactional
void someServiceMethod(Entity entity){
    em.persist(entity); 
    em.flush() //need to explicitly flush in order to use id in next statement
    doSomeThingElse(entity.getId());    
}

Also Note that, explicitly flushing does not cause a database commit, a database commit is done only at the end of a transaction, so if any Runtime error occurs after calling flush the changes would still Rollback.

TypeError: 'int' object is not subscriptable

You can't do something like that: (int(sumall[0])+int(sumall[1]))

That's because sumall is an int and not a list or dict.

So, summ + sumd will be you're lucky number

Default instance name of SQL Server Express

in my case the right server name was the name of my computer. for example John-PC, or somth

Simple PHP form: Attachment to email (code golf)

In order to add the file to the email as an attachment, it will need to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.

As for emailing, Zend Mail has a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.

With Zend_Mail, sending an email with an attachment is as simple as:

$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();

If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.

Pushing empty commits to remote

Is there any disadvantages/consequences of pushing empty commits?

Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.

You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f back to remote.

Is there way to use two PHP versions in XAMPP?

run this in Command Prompt windows (cmd.exe).

set PATH=C:\xampp\php;%PATH%

change it depending where you put the php 7 installation.

Android: Create a toggle button with image and no text

create toggle_selector.xml in res/drawable

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
  <item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>

apply the selector to your toggle button

<ToggleButton
            android:id="@+id/chkState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOff=""
            android:textOn=""/>

Note: for removing the text i used following in above code

textOff=""
textOn=""

Order Bars in ggplot2 bar graph

Since we are only looking at the distribution of a single variable ("Position") as opposed to looking at the relationship between two variables, then perhaps a histogram would be the more appropriate graph. ggplot has geom_histogram() that makes it easy:

ggplot(theTable, aes(x = Position)) + geom_histogram(stat="count")

enter image description here

Using geom_histogram():

I think geom_histogram() is a little quirky as it treats continuous and discrete data differently.

For continuous data, you can just use geom_histogram() with no parameters. For example, if we add in a numeric vector "Score"...

    Name   Position   Score  
1   James  Goalkeeper 10
2   Frank  Goalkeeper 20
3   Jean   Defense    10
4   Steve  Defense    10
5   John   Defense    20
6   Tim    Striker    50

and use geom_histogram() on the "Score" variable...

ggplot(theTable, aes(x = Score)) + geom_histogram()

enter image description here

For discrete data like "Position" we have to specify a calculated statistic computed by the aesthetic to give the y value for the height of the bars using stat = "count":

 ggplot(theTable, aes(x = Position)) + geom_histogram(stat = "count")

Note: Curiously and confusingly you can also use stat = "count" for continuous data as well and I think it provides a more aesthetically pleasing graph.

ggplot(theTable, aes(x = Score)) + geom_histogram(stat = "count")

enter image description here

Edits: Extended answer in response to DebanjanB's helpful suggestions.

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.

Keyboard shortcut to clear cell output in Jupyter notebook

Add following at start of cell and run it:

from IPython.display import clear_output
clear_output(wait=True)

How to send email from SQL Server?

Step 1) Create Profile and Account

You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.

Step 2)

RUN:

sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO

Step 3)

USE msdb
GO
EXEC sp_send_dbmail @profile_name='yourprofilename',
@recipients='[email protected]',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'

To loop through the table

DECLARE @email_id NVARCHAR(450), @id BIGINT, @max_id BIGINT, @query NVARCHAR(1000)

SELECT @id=MIN(id), @max_id=MAX(id) FROM [email_adresses]

WHILE @id<=@max_id
BEGIN
    SELECT @email_id=email_id 
    FROM [email_adresses]

    set @query='sp_send_dbmail @profile_name=''yourprofilename'',
                        @recipients='''+@email_id+''',
                        @subject=''Test message'',
                        @body=''This is the body of the test message.
                        Congrates Database Mail Received By you Successfully.'''

    EXEC @query
    SELECT @id=MIN(id) FROM [email_adresses] where id>@id

END

Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html

Extracting specific columns from a data frame

Using the dplyr package, if your data.frame is called df1:

library(dplyr)

df1 %>%
  select(A, B, E)

This can also be written without the %>% pipe as:

select(df1, A, B, E)

How should I have explained the difference between an Interface and an Abstract class?

I believe what the interviewer was trying to get at was probably the difference between interface and implementation.

The interface - not a Java interface, but "interface" in more general terms - to a code module is, basically, the contract made with client code that uses the interface.

The implementation of a code module is the internal code that makes the module work. Often you can implement a particular interface in more than one different way, and even change the implementation without client code even being aware of the change.

A Java interface should only be used as an interface in the above generic sense, to define how the class behaves for the benefit of client code using the class, without specifying any implementation. Thus, an interface includes method signatures - the names, return types, and argument lists - for methods expected to be called by client code, and in principle should have plenty of Javadoc for each method describing what that method does. The most compelling reason for using an interface is if you plan to have multiple different implementations of the interface, perhaps selecting an implementation depending on deployment configuration.

A Java abstract class, in contrast, provides a partial implementation of the class, rather than having a primary purpose of specifying an interface. It should be used when multiple classes share code, but when the subclasses are also expected to provide part of the implementation. This permits the shared code to appear in only one place - the abstract class - while making it clear that parts of the implementation are not present in the abstract class and are expected to be provided by subclasses.

Jquery Setting Value of Input Field

This should work.

$(".formData").val("valuesgoeshere")

For empty

$(".formData").val("")

If this does not work, you should post a jsFiddle.

Demo:

_x000D_
_x000D_
$(function() {_x000D_
  $(".resetInput").on("click", function() {_x000D_
    $(".formData").val("");_x000D_
  });_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
_x000D_
_x000D_

How do I get my solution in Visual Studio back online in TFS?

I am using Visual Studio 2017 15.4.0 version. Especially when i started use lightweight solution option, this offline thing happened to me. I tried to above solutions which are:

  1. Tried to regedit option but can not see appropriate menu options. Didn't work.
  2. Right click on solution, there is go online option and when i choose it that gives this error message: "The solution is offline because its associated Team Foundation Server is offline. Unable to determine the workspace for this solution."

Then from File -> Source Control -> Advanced -> Change Source Control. I saw my files. I select them and then chose bind option. That worked for me.

How to auto-indent code in the Atom editor?

I found the option in the menu, under Edit > Lines > Auto Indent. It doesn't seem to have a default keymap bound.

You could try to add a key mapping (Atom > Open Your Keymap [on Windows: File > Settings > Keybindings > "your keymap file"]) like this one:

'atom-text-editor':
  'cmd-alt-l': 'editor:auto-indent'

It worked for me :)


For Windows:

'atom-text-editor':
  'ctrl-alt-l': 'editor:auto-indent'

Failed loading english.pickle with nltk.data.load

This is what worked for me just now:

# Do this in a separate python interpreter session, since you only have to do it once
import nltk
nltk.download('punkt')

# Do this in your ipython notebook or analysis script
from nltk.tokenize import word_tokenize

sentences = [
    "Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.",
    "Professor Plum has a green plant in his study.",
    "Miss Scarlett watered Professor Plum's green plant while he was away from his office last week."
]

sentences_tokenized = []
for s in sentences:
    sentences_tokenized.append(word_tokenize(s))

sentences_tokenized is a list of a list of tokens:

[['Mr.', 'Green', 'killed', 'Colonel', 'Mustard', 'in', 'the', 'study', 'with', 'the', 'candlestick', '.', 'Mr.', 'Green', 'is', 'not', 'a', 'very', 'nice', 'fellow', '.'],
['Professor', 'Plum', 'has', 'a', 'green', 'plant', 'in', 'his', 'study', '.'],
['Miss', 'Scarlett', 'watered', 'Professor', 'Plum', "'s", 'green', 'plant', 'while', 'he', 'was', 'away', 'from', 'his', 'office', 'last', 'week', '.']]

The sentences were taken from the example ipython notebook accompanying the book "Mining the Social Web, 2nd Edition"

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".

Next, use the apply function in pandas to apply the function - e.g.

df.apply (lambda row: label_race(row), axis=1)

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:

0           White
1        Hispanic
2           White
3           White
4           Other
5           White
6     Two Or More
7           White
8    Haw/Pac Isl.
9           White

If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.

df['race_label'] = df.apply (lambda row: label_race(row), axis=1)

The resultant dataframe looks like this (scroll to the right to see the new column):

      lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label
0      MOST    JEFF      E             0          0             0              0             0          1       White         White
1    CRUISE     TOM      E             0          0             0              1             0          0       White      Hispanic
2      DEPP  JOHNNY    NaN             0          0             0              0             0          1     Unknown         White
3     DICAP     LEO    NaN             0          0             0              0             0          1     Unknown         White
4    BRANDO  MARLON      E             0          0             0              0             0          0       White         Other
5     HANKS     TOM    NaN             0          0             0              0             0          1     Unknown         White
6    DENIRO  ROBERT      E             0          1             0              0             0          1       White   Two Or More
7    PACINO      AL      E             0          0             0              0             0          1       White         White
8  WILLIAMS   ROBIN      E             0          0             1              0             0          0       White  Haw/Pac Isl.
9  EASTWOOD   CLINT      E             0          0             0              0             0          1       White         White

How to read the post request parameters using JavaScript

Use sessionStorage!

_x000D_
_x000D_
$(function(){_x000D_
    $('form').submit{_x000D_
       document.sessionStorage["form-data"] =  $('this').serialize();_x000D_
       document.location.href = 'another-page.html';_x000D_
    }_x000D_
});
_x000D_
_x000D_
_x000D_

At another-page.html:

_x000D_
_x000D_
var formData = document.sessionStorage["form-data"];
_x000D_
_x000D_
_x000D_

Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Run exe file with parameters in a batch file

If you need to see the output of the execute, use CALL together with or instead of START.

Example:

CALL "C:\Program Files\Certain Directory\file.exe" -param PAUSE

This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE after the call or else the window may close instantly.

Get Path from another app (WhatsApp)

You can't get a path to file from WhatsApp. They don't expose it now. The only thing you can get is InputStream:

InputStream is = getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/16695"));

Using is you can show a picture from WhatsApp in your app.

Get SELECT's value and text in jQuery

$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value

Determine distance from the top of a div to top of window with javascript

I used this:

                              myElement = document.getElemenById("xyz");
Get_Offset_From_Start       ( myElement );  // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement );  // returns positions from current scrolled view's TOP and LEFT

code:

function Get_Offset_From_Start (object, offset) { 
    offset = offset || {x : 0, y : 0};
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    if(object.offsetParent) {
        offset = Get_Offset_From_Start (object.offsetParent, offset);
    }
    return offset;
}

function Get_Offset_From_CurrentView (myElement) {
    if (!myElement) return;
    var offset = Get_Offset_From_Start (myElement);
    var scrolled = GetScrolled (myElement.parentNode);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
    scrolled = scrolled || {x : 0, y : 0};
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
    return scrolled;
}

    /*
    // live monitoring
    window.addEventListener('scroll', function (evt) {
        var Positionsss =  Get_Offset_From_CurrentView(myElement);  
        console.log(Positionsss);
    });
    */

How do I pass multiple parameters in Objective-C?

You need to delimit each parameter name with a ":" at the very least. Technically the name is optional, but it is recommended for readability. So you could write:

- (NSMutableArray*)getBusStops:(NSString*)busStop :(NSSTimeInterval*)timeInterval;

or what you suggested:

- (NSMutableArray*)getBusStops:(NSString*)busStop forTime:(NSSTimeInterval*)timeInterval;

How can I change the color of AlertDialog title and the color of the line under it

In the class onCreateView, I put this:

Dialog d = getDialog();
    d.setTitle(Html.fromHtml("<font color='#EC407A'>About</font>"));
    int dividerId = d.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
    View divider = d.findViewById(dividerId);
    divider.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

colorPrimary links to our colors.xml file that stores all the colors. Also d.setTitle provides a hacky way to set the title colour.

VBA Count cells in column containing specified value

This isn't exactly what you are looking for but here is how I've approached this problem in the past;

You can enter a formula like;

=COUNTIF(A1:A10,"Green")

...into a cell. This will count the Number of cells between A1 and A10 that contain the text "Green". You can then select this cell value in a VBA Macro and assign it to a variable as normal.

What is "pom" packaging in maven?

To simply answer your question when you do a mvn:install, maven will create a packaged artifact based on (packaging attribute in pom.xml), After you run your maven install you can find the file with .package extension

  • In target directory of the project workspace
  • Also where your maven 2 local repository is search for (.m2/respository) on your box, Your artifact is listed in .m2 repository under (groupId/artifactId/artifactId-version.packaging) directory
  • If you look under the directory you will find packaged extension file and also pom extension (pom extension is basically the pom.xml used to generate this package)
  • If your maven project is multi-module each module will two files as described above except for the top level project that will only have a pom

Configure active profile in SpringBoot via Maven

You should use the Spring Boot Maven Plugin:

<project>  
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.1.RELEASE</version>
        <configuration>
          <profiles>
            <profile>foo</profile>
            <profile>bar</profile>
          </profiles>
        </configuration>
        ...
      </plugin>
      ...
    </plugins>
    ...
  </build>
  ...
</project>

SQL Server : How to test if a string has only digit characters

Use Not Like

where some_column NOT LIKE '%[^0-9]%'

Demo

declare @str varchar(50)='50'--'asdarew345'

select 1 where @str NOT LIKE '%[^0-9]%'

How to uninstall Golang?

sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go

This is perfect for Ubuntu 18.18

How can I add private key to the distribution certificate?

"Valid Signing identity not found" This is because you don't have the private key for distribution certificate.

If the distribution certificate was created originally on a different Mac you may need to import this private key from that Mac. This private key is not available to download from your provisioning portal.

When you import the correct private key to your mac , XCode's organizer will recognize your already downloaded distribution profile as a "Valid profile"

However if you do not have access to the original Mac which created those profiles, the only option you have is revoking profiles.

How to get back to most recent version in Git?

To return to the latest version:

git checkout <branch-name> 

For example, git checkout master or git checkout dev

System.Data.OracleClient requires Oracle client software version 8.1.7

Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.

How to set opacity in parent div and not affect in child div?

I had the same problem and I fixed by setting transparent png image as background for the parent tag.

This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !

How to Compare two strings using a if in a stored procedure in sql server 2008?

Two things:

  1. Only need one (1) equals sign to evaluate
  2. You need to specify a length on the VARCHAR - the default is a single character.

Use:

DECLARE @temp VARCHAR(10)
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -

DECLARE @temp VARCHAR
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "yes"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "no".

Better way to check variable for null or empty string?

empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:

if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

What is the reason behind "non-static method cannot be referenced from a static context"?

I think it is worth pointing out that by the rules of the Java language the Java compiler inserts the equivalent of "this." when it notices that you're accessing instance methods or instance fields without an explicit instance. Of course, the compiler knows that it can only do this from within an instance method, which has a "this" variable, as static methods don't.

Which means that when you're in an instance method the following are equivalent:

instanceMethod();
this.instanceMethod();

and these are also equivalent:

... = instanceField;
... = this.instanceField;

The compiler is effectively inserting the "this." when you don't supply a specific instance.

This (pun intended) bit of "magic help" by the compiler can confuse novices: it means that instance calls and static calls sometimes appear to have the same syntax while in reality are calls of different types and underlying mechanisms.

The instance method call is sometimes referred to as a method invocation or dispatch because of the behaviors of virtual methods supporting polymorphism; dispatching behavior happens regardless of whether you wrote an explicit object instance to use or the compiler inserted a "this.".

The static method call mechanism is simpler, like a function call in a non-OOP language.

Personally, I think the error message is misleading, it could read "non-static method cannot be referenced from a static context without specifying an explicit object instance".


What the compiler is complaining about is that it cannot simply insert the standard "this." as it does within instance methods, because this code is within a static method; however, maybe the author merely forgot to supply the instance of interest for this invocation — say, an instance possibly supplied to the static method as parameter, or created within this static method.

In short, you most certainly can call instance methods from within a static method, you just need to have and specify an explicit instance object for the invocation.

What does PermGen actually stand for?

Permanent Generation. See the java GC tuning guide for more details on the garbage collector.

Return from lambda forEach() in java

This what helped me:

List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);

Taken from Java 8 Finding Specific Element in List with Lambda

What is the size of column of int(11) in mysql in bytes?

As others have said, the minumum/maximum values the column can store and how much storage it takes in bytes is only defined by the type, not the length.

A lot of these answers are saying that the (11) part only affects the display width which isn't exactly true, but mostly.

A definition of int(2) with no zerofill specified will:

  • still accept a value of 100
  • still display a value of 100 when output (not 0 or 00)
  • the display width will be the width of the largest value being output from the select query.

The only thing the (2) will do is if zerofill is also specified:

  • a value of 1 will be shown 01.
  • When displaying values, the column will always have a width of the maximum possible value the column could take which is 10 digits for an integer, instead of the miniumum width required to display the largest value that column needs to show for in that specific select query, which could be much smaller.
  • The column can still take, and show a value exceeding the length, but these values will not be prefixed with 0s.

The best way to see all the nuances is to run:

CREATE TABLE `mytable` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `int1` int(10) NOT NULL,
    `int2` int(3) NOT NULL,
    `zf1` int(10) ZEROFILL NOT NULL,
    `zf2` int(3) ZEROFILL NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `mytable` 
(`int1`, `int2`, `zf1`, `zf2`) 
VALUES
(10000, 10000, 10000, 10000),
(100, 100, 100, 100);

select * from mytable;

which will output:

+----+-------+-------+------------+-------+
| id | int1  | int2  | zf1        | zf2   |
+----+-------+-------+------------+-------+
|  1 | 10000 | 10000 | 0000010000 | 10000 |
|  2 |   100 |   100 | 0000000100 |   100 |
+----+-------+-------+------------+-------+

This answer is tested against MySQL 5.7.12 for Linux and may or may not vary for other implementations.

How to reset all checkboxes using jQuery or pure JS?

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container check">
<button class="btn">click</button>
  <input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car<br>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car<br>
</div>
<script>
$('.btn').click(function() {

$('input[type=checkbox]').each(function() 
{ 
        this.checked = false; 
}); 
})
</script>
</body>
</html>

PHPMailer character encoding issues

I work myself this way

  $mail->FromName = utf8_decode($_POST['name']);

http://php.net/manual/en/function.utf8-decode.php

How do I calculate a trendline for a graph?

If you have access to Excel, look in the "Statistical Functions" section of the Function Reference within Help. For straight-line best-fit, you need SLOPE and INTERCEPT and the equations are right there.

Oh, hang on, they're also defined online here: http://office.microsoft.com/en-us/excel/HP052092641033.aspx for SLOPE, and there's a link to INTERCEPT. OF course, that assumes MS don't move the page, in which case try Googling for something like "SLOPE INTERCEPT EQUATION Excel site:microsoft.com" - the link given turned out third just now.

How to animate the change of image in an UIImageView?

With Swift 3

extension UIImageView{   
 var imageWithFade:UIImage?{
        get{
            return self.image
        }
        set{
            UIView.transition(with: self,
                              duration: 0.5, options: .transitionCrossDissolve, animations: {
                                self.image = newValue
            }, completion: nil)
        }
    }
}

Usage:

myImageView.imageWithFade = myImage

Java get last element of a collection

Well one solution could be:

list.get(list.size()-1)

Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

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

For me, running the ad-hoc network on Windows 8.1, it was two things:

  • I had to set a static IP on my Android (under Advanced Options under where you type the Wifi password)
  • I had to use a password 8 characters long

Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.

I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Yet another way to do this:

(Get-Date).AddDays(-1).Date.AddHours(22)

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

Create a symbolic link of directory in Ubuntu

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

If you get this error when you are running it, then probably its because you have not included mysql-connector JAR file to your webserver's lib folder.

Now it is important to add mysql-connector-java-5.1.25-bin.jar to your classpath and also to your webserver's lib directory. Tomcat lib path is given as an example Tomcat 6.0\lib

Convert Pixels to Points

Surely this whole question should be:

"How do I obtain the horizontal and vertical PPI (Pixels Per Inch) of the monitor?"

There are 72 points in an inch (by definition, a "point" is defined as 1/72nd of an inch, likewise a "pica" is defined as 1/72nd of a foot). With these two bits of information you can convert from px to pt and back very easily.

How to base64 encode image in linux bash / shell

Base 64 for html:

file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"

ORA-01861: literal does not match format string

Just before executing the query: alter session set NLS_DATE_FORMAT = "DD.MM.YYYY HH24:MI:SS"; or whichever format you are giving the information to the date function. This should fix the ORA error

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

Options for initializing a string array

You have several options:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

Node.js Mongoose.js string to ObjectId function

You can do it like this:

var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");

EDIT: New standard has fromHexString rather than fromString

Spring Boot - Loading Initial Data

You can create a data.sql file in your src/main/resources folder and it will be automatically executed on startup. In this file you can add some insert statements, eg.:

INSERT INTO users (username, firstname, lastname) VALUES
  ('lala', 'lala', 'lala'),
  ('lolo', 'lolo', 'lolo');

Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:

CREATE TABLE task (
  id          INTEGER PRIMARY KEY,
  description VARCHAR(64) NOT NULL,
  completed   BIT NOT NULL);

Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your application.properties:

spring.jpa.hibernate.ddl-auto=none

More information can be found at the documentation about Database initialization.


If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:

spring.datasource.initialization-mode=always

If you're using multiple database vendors, you can name your file data-h2.sql or data-mysql.sql depending on which database platform you want to use.

To make that work, you'll have to configure the spring.datasource.platform property though:

spring.datasource.platform=h2

How to check what user php is running as?

If available you can probe the current user account with posix_geteuid and then get the user name with posix_getpwuid.

$username = posix_getpwuid(posix_geteuid())['name'];

If you are running in safe mode however (which is often the case when exec is disabled), then it's unlikely that your PHP process is running under anything but the default www-data or apache account.

powershell - list local users and their groups

Use this to get an array with the local users and the groups they are member of:

Get-LocalUser | 
    ForEach-Object { 
        $user = $_
        return [PSCustomObject]@{ 
            "User"   = $user.Name
            "Groups" = Get-LocalGroup | Where-Object {  $user.SID -in ($_ | Get-LocalGroupMember | Select-Object -ExpandProperty "SID") } | Select-Object -ExpandProperty "Name"
        } 
    }

To get an array with the local groups and their members:

Get-LocalGroup | 
    ForEach-Object {
        $group = $_
        return [PSCustomObject]@{ 
            "Group"   = $group.Name
            "Members" = $group | Get-LocalGroupMember | Select-Object -ExpandProperty "Name"
        } 
    } 

Rotate and translate

Something that may get missed: in my chaining project, it turns out a space separated list also needs a space separated semicolon at the end.

In other words, this doesn't work:

transform: translate(50%, 50%) rotate(90deg);

but this does:

transform: translate(50%, 50%) rotate(90deg) ; //has a space before ";"

DataRow: Select cell value by a given column name

On top of what Jimmy said, you can also make the select generic by using Convert.ChangeType along with the necessary null checks:

public T GetColumnValue<T>(DataRow row, string columnName)
  {
        T value = default(T);
        if (row.Table.Columns.Contains(columnName) && row[columnName] != null && !String.IsNullOrWhiteSpace(row[columnName].ToString()))
        {
            value = (T)Convert.ChangeType(row[columnName].ToString(), typeof(T));
        }

        return value;
  }

Setting top and left CSS attributes

You can also use the setProperty method like below

document.getElementById('divName').style.setProperty("top", "100px");

Spring MVC - How to get all request params in a map in Spring controller?

Edit

It has been pointed out that there exists (at least as of 3.0) a pure Spring MVC mechanism by which one could get this data. I will not detail it here, as it is the answer of another user. See @AdamGent's answer for details, and don't forget to upvote it.

In the Spring 3.2 documentation this mechanism is mentioned on both the RequestMapping JavaDoc page and the RequestParam JavaDoc page, but prior, it is only mentioned in the RequestMapping page. In 2.5 documentation there is no mention of this mechanism.

This is likely the preferred approach for most developers as it removes (at least this) binding to the HttpServletRequest object defined by the servlet-api jar.

/Edit

You should have access to the requests query string via request.getQueryString().

In addition to getQueryString, the query parameters can also be retrieved from request.getParameterMap() as a Map.

Error on renaming database in SQL Server 2008 R2

Change database to single user mode as shown in the other answers

Sometimes, even after converting to single user mode, the only connection allowed to the database may be in use.

To close a connection even after converting to single user mode try:

select * from master.sys.sysprocesses
where spid>50 -- don't want system sessions
  and dbid = DB_ID('BOSEVIKRAM')

Look at the results and see the ID of the connection to the database in question.

Then use the command below to close this connection (there should only be one since the database is now in single user mode)

KILL connection_ID

Replace connection_id with the ID in the results of the 1st query

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

How do I set the selected item in a comboBox to match my string using C#?

Find mySecondObject (of type MyObject) in combobox (containing a list of MyObjects) and select the item:

foreach (MyObject item in comboBox.Items)
{
   if (item.NameOrID == mySecondObject.NameOrID)
    {
        comboBox.SelectedItem = item;
        break;
    }
}

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Serializing an object to JSON

Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):

function winHasJSON(){
  json_data = JSON.stringify(obj);
  // ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
  winHasJSON();
} else {
  $.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

You'll have to make a join:

SELECT A.SalesOrderID, B.Foo
FROM A
JOIN B bo ON bo.id = (
     SELECT TOP 1 id
     FROM B bi
     WHERE bi.SalesOrderID = a.SalesOrderID
     ORDER BY bi.whatever
     )
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'

, assuming that b.id is a PRIMARY KEY on B

In MS SQL 2005 and higher you may use this syntax:

SELECT SalesOrderID, Foo
FROM (
  SELECT A.SalesOrderId, B.Foo,
         ROW_NUMBER() OVER (PARTITION BY B.SalesOrderId ORDER BY B.whatever) AS rn
  FROM A
  JOIN B ON B.SalesOrderID = A.SalesOrderID
  WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
) i
WHERE rn

This will select exactly one record from B for each SalesOrderId.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

FormData Objects: Upload Files Using Ajax

XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.

function AjaxFileUpload() {
    var file = document.getElementById("files");
    //var file = fileInput;
    var fd = new FormData();
    fd.append("imageFileData", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/ws/fileUpload.do');
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
             alert('success');
        }
        else if (uploadResult == 'success')
             alert('error');
    };
    xhr.send(fd);
}

https://developer.mozilla.org/en-US/docs/Web/API/FormData

If (Array.Length == 0)

Your suggested test is fine, so long as the array is intialised...

Martin.

How do I alter the position of a column in a PostgreSQL database table?

"Alter column position" in the PostgreSQL Wiki says:

PostgreSQL currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.

That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.

One other idea occurs to me: you can define a VIEW that specifies the order of columns how you like it, without changing the physical position of the column in the base table.

What is a database transaction?

I would suggest that a definition of 'transaction processing' would be more useful, as it covers transactions as a concept in computer science.

From wikipedia:

In computer science, transaction processing is information processing that is divided into individual, indivisible operations, called transactions. Each transaction must succeed or fail as a complete unit; it cannot remain in an intermediate state.

http://en.wikipedia.org/wiki/Transaction_processing#Implementations

Set adb vendor keys

I had the same problem running Ubuntu 18.04. I tried multiple solutions but my device (OnePlus 5T) was always unauthorized.

Solution

  1. Configure udev rules on Ubuntu. To do this, just follow the official documentation: https://developer.android.com/studio/run/device

    The idVendor of my device (OnePlus) is not listed. To get it, just connect your device and use lsusb:

    Bus 003 Device 008: ID 2a70:4ee7

    In this example, 2a70 is the idVendor.

  2. Remove existing adb keys on Ubuntu:

    rm -v ~/.android/adbkey* ~/.android/adbkey ~/.android/adbkey.pub

  3. 'Revoke USB debugging authorizations' on your device configuration (developer options).

  4. Finally, restart the adb server to create a new key:

    sudo adb kill-server sudo adb devices

After that, I got the authorization prompt on my device and I authorized it.

Can I use if (pointer) instead of if (pointer != NULL)?

As others already answered well, they both are interchangeable.

Nonetheless, it's worth mentioning that there could be a case where you may want to use the explicit statement, i.e. pointer != NULL.

See also https://stackoverflow.com/a/60891279/2463963

Overflow:hidden dots at the end

Hide text on load and show on hover

_x000D_
_x000D_
.hide-text {
  width: 70px;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis;
}

span:hover {
   white-space: unset;
   text-overflow: unset;
}
_x000D_
<span class="hide-text"> How to hide text by dots and show text on hover</span>
_x000D_
_x000D_
_x000D_

What does status=canceled for a resource mean in Chrome Developer Tools?

The requests might have been blocked by a tracking protection plugin.

Java 8 Distinct by property

Maybe will be useful for somebody. I had a little bit another requirement. Having list of objects A from 3rd party remove all which have same A.b field for same A.id (multiple A object with same A.id in list). Stream partition answer by Tagir Valeev inspired me to use custom Collector which returns Map<A.id, List<A>>. Simple flatMap will do the rest.

 public static <T, K, K2> Collector<T, ?, Map<K, List<T>>> groupingDistinctBy(Function<T, K> keyFunction, Function<T, K2> distinctFunction) {
    return groupingBy(keyFunction, Collector.of((Supplier<Map<K2, T>>) HashMap::new,
            (map, error) -> map.putIfAbsent(distinctFunction.apply(error), error),
            (left, right) -> {
                left.putAll(right);
                return left;
            }, map -> new ArrayList<>(map.values()),
            Collector.Characteristics.UNORDERED)); }

How to handle login pop up window using Selenium WebDriver?

In C# Selenium Web Driver I have managed to get it working with the following code:

var alert = TestDriver.SwitchTo().Alert();
alert.SendKeys(CurrentTestingConfiguration.Configuration.BasicAuthUser + Keys.Tab + CurrentTestingConfiguration.Configuration.BasicAuthPassword);
alert.Accept();

Although it seems similar, the following did not work with Firefox (Keys.Tab resets all the form and the password will be written within the user field):

alert.SendKeys(CurrentTestingConfiguration.Configuration.BasicAuthUser);
alert.SendKeys(Keys.Tab);
alert.SendKeys(CurrentTestingConfiguration.Configuration.BasicAuthPassword);

Also, I have tried the following solution which resulted in exception:

var alert = TestDriver.SwitchTo().Alert();
alert.SetAuthenticationCredentials(
   CurrentTestingConfiguration.Configuration.BasicAuthUser,
   CurrentTestingConfiguration.Configuration.BasicAuthPassword);

System.NotImplementedException: 'POST /session/38146c7c-cd1a-42d8-9aa7-1ac6837e64f6/alert/credentials did not match a known command'

Service vs IntentService in the Android platform

The Major Difference between a Service and an IntentService is described as follows:

Service :

1.A Service by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.

2.Allows Multiple requests at a time.(Multi Threading)

IntentService :

1.Now, coming to IntentService, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent() method ,which receives the intent for each start request, where you can do the background work.

2.But it allows only one request at a time.

Set environment variables from file of key/value pairs

This might be helpful:

export $(cat .env | xargs) && rails c

Reason why I use this is if I want to test .env stuff in my rails console.

gabrielf came up with a good way to keep the variables local. This solves the potential problem when going from project to project.

env $(cat .env | xargs) rails

I've tested this with bash 3.2.51(1)-release


Update:

To ignore lines that start with #, use this (thanks to Pete's comment):

export $(grep -v '^#' .env | xargs)

And if you want to unset all of the variables defined in the file, use this:

unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/\1/' | xargs)

Update:

To also handle values with spaces, use:

export $(grep -v '^#' .env | xargs -d '\n')

on GNU systems -- or:

export $(grep -v '^#' .env | xargs -0)

on BSD systems.


From this answer you can auto-detect the OS with this:

export-env.sh

#!/bin/sh

## Usage:
##   . ./export-env.sh ; $COMMAND
##   . ./export-env.sh ; echo ${MINIENTREGA_FECHALIMITE}

unamestr=$(uname)
if [ "$unamestr" = 'Linux' ]; then

  export $(grep -v '^#' .env | xargs -d '\n')

elif [ "$unamestr" = 'FreeBSD' ]; then

  export $(grep -v '^#' .env | xargs -0)

fi

To draw an Underline below the TextView in Android

underline a textview in android

5 Amazing Ways To Underline A TextView In Android - Kotlin/Java & XML

  1. String html = "<u>Underline using Html.fromHtml()</u>"; textview.setText(Html.fromHtml(html));

But Html.fromHtml(String resource) was deprecated in API 24.

So you can use the latest android support library androidx.core.text.HtmlCompat. Before that, you need to include the dependency in your project.

`implementation 'androidx.core:core:1.0.1'`
  1. String html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>"; //underline textview using HtmlCompat.fromHtml() method textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));

Using strings.xml,

  1. <string name="underline_text">1.3 &lt;u>Underline using HtmlCompat.fromHtml() and string resource&lt;/u></string>

textview13.setText(HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY));

using PaintFlags

  1. textview2.setPaintFlags(textview2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); textview2.setText("2. Underline using setPaintFlags()");

using SpannableString

`String content1 = "3.1 Underline using SpannableString";
        SpannableString spannableString1 = new SpannableString(content1);
        spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
        textview31.setText(spannableString1);`

Convert number to month name in PHP

this is trivially easy, why are so many people making such bad suggestions? @Bora was the closest, but this is the most robust

/***
 * returns the month in words for a given month number
 */
date("F", strtotime(date("Y")."-".$month."-01"));

this is the way to do it

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Along with the embed, I also had to install the Google Cast extension in my browser.

<iframe width="1280" height="720" src="https://www.youtube.com/embed/4u856utdR94" frameborder="0" allowfullscreen></iframe>

How do I get the current timezone name in Postgres 9.3?

You can access the timezone by the following script:

SELECT * FROM pg_timezone_names WHERE name = current_setting('TIMEZONE');
  • current_setting('TIMEZONE') will give you Continent / Capital information of settings
  • pg_timezone_names The view pg_timezone_names provides a list of time zone names that are recognized by SET TIMEZONE, along with their associated abbreviations, UTC offsets, and daylight-savings status.
  • name column in a view (pg_timezone_names) is time zone name.

output will be :

name- Europe/Berlin, 
abbrev - CET, 
utc_offset- 01:00:00, 
is_dst- false

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

I had same issue in Android Studio 3. (the project was open) so I closed the current project and the IDE automatically prompted to download the latest components. once its done everything was working correctly.

How can I get the content of CKEditor using JQuery?

First of all you should include ckeditor and jquery connector script in your page,

then create a textarea

<textarea name="content" class="editor" id="ms_editor"></textarea>

attach ckeditor to the text area, in my project I use something like this:

$('textarea.editor').ckeditor(function() {
        }, { toolbar : [
            ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
            ['Undo','Redo'],
            ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
            ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
            ['Link','Unlink','Anchor', 'Image', 'Smiley'],
            ['Table','HorizontalRule','SpecialChar'],
            ['Styles','BGColor']
        ], toolbarCanCollapse:false, height: '300px', scayt_sLang: 'pt_PT', uiColor : '#EBEBEB' } );

on submit get the content using:

var content = $( 'textarea.editor' ).val();

That's it! :)

How to read connection string in .NET Core?

There is another approach. In my example you see some business logic in repository class that I use with dependency injection in ASP .NET MVC Core 3.1.

And here I want to get connectiongString for that business logic because probably another repository will have access to another database at all.

This pattern allows you in the same business logic repository have access to different databases.

C#

public interface IStatsRepository
{
            IEnumerable<FederalDistrict> FederalDistricts();
}

class StatsRepository : IStatsRepository
{
   private readonly DbContextOptionsBuilder<EFCoreTestContext>
                optionsBuilder = new DbContextOptionsBuilder<EFCoreTestContext>();
   private readonly IConfigurationRoot configurationRoot;

   public StatsRepository()
   {
       IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
           .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
       configurationRoot = configurationBuilder.Build();
   }

   public IEnumerable<FederalDistrict> FederalDistricts()
   {
        var conn = configurationRoot.GetConnectionString("EFCoreTestContext");
        optionsBuilder.UseSqlServer(conn);

        using (var ctx = new EFCoreTestContext(optionsBuilder.Options))
        { 
            return ctx.FederalDistricts.Include(x => x.FederalSubjects).ToList();
        }
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "EFCoreTestContext": "Data Source=DESKTOP-GNJKL2V\\MSSQLSERVER2014;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Getting Git to work with a proxy server - fails with "Request timed out"

For the git protocol (git://...), install socat and write a script such as:

#!/bin/sh

exec socat - socks4:your.company.com:$1:$2

make it executable, put it in your path, and in your ~/.gitconfig set core.gitproxy to the name of that script.

How to replace multiple patterns at once with sed?

I believe this should solve your problem. I may be missing a few edge cases, please comment if you notice one.

You need a way to exclude previous substitutions from future patterns, which really means making outputs distinguishable, as well as excluding these outputs from your searches, and finally making outputs indistinguishable again. This is very similar to the quoting/escaping process, so I'll draw from it.

  • s/\\/\\\\/g escapes all existing backslashes
  • s/ab/\\b\\c/g substitutes raw ab for escaped bc
  • s/bc/\\a\\b/g substitutes raw bc for escaped ab
  • s/\\\(.\)/\1/g substitutes all escaped X for raw X

I have not accounted for backslashes in ab or bc, but intuitively, I would escape the search and replace terms the same way - \ now matches \\, and substituted \\ will appear as \.

Until now I have been using backslashes as the escape character, but it's not necessarily the best choice. Almost any character should work, but be careful with the characters that need escaping in your environment, sed, etc. depending on how you intend to use the results.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Implementing IDisposable correctly

IDisposable exists to provide a means for you to clean up unmanaged resources that won't be cleaned up automatically by the Garbage Collector.

All of the resources that you are "cleaning up" are managed resources, and as such your Dispose method is accomplishing nothing. Your class shouldn't implement IDisposable at all. The Garbage Collector will take care of all of those fields just fine on its own.

How to make an executable JAR file?

Here it is in one line:

jar cvfe myjar.jar package.MainClass *.class

where MainClass is the class with your main method, and package is MainClass's package.

Note you have to compile your .java files to .class files before doing this.

c  create new archive
v  generate verbose output on standard output
f  specify archive file name
e  specify application entry point for stand-alone application bundled into an executable jar file

This answer inspired by Powerslave's comment on another answer.

How to get the current time as datetime

Xcode 8.2.1 • Swift 3.0.2

extension Date {
    var hour: Int { return Calendar.autoupdatingCurrent.component(.hour, from: self) }
}

let date = Date()      // "Mar 16, 2017, 3:43 PM"
let hour = date.hour   // 15

Check if MySQL table exists or not

$result = mysql_query("SHOW TABLES FROM $dbname");

while($row = mysql_fetch_row($result)) 
{
    $arr[] = $row[0];
}

if(in_array($table,$arr))
{
  echo 'Table exists';
}

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:

public getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`api/products/v1/`);
  }

How to restrict the selectable date ranges in Bootstrap Datepicker?

Another possibility is to use the options with data attributes, like this(minimum date 1 week before):

<input class='datepicker' data-date-start-date="-1w">

More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

Combining Two Images with OpenCV

You can also use OpenCV's inbuilt functions cv2.hconcat and cv2.vconcat which like their names suggest are used to join images horizontally and vertically respectively.

import cv2

img1 = cv2.imread('opencv/lena.jpg')
img2 = cv2.imread('opencv/baboon.jpg')

v_img = cv2.vconcat([img1, img2])
h_img = cv2.hconcat([img1, img2])

cv2.imshow('Horizontal', h_img)
cv2.imshow('Vertical', v_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Horizontal Concatenation

Horizontal

Vertical Concatenation

Vertical

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Just add this one-line class in your CSS, and use the bootstrap label component.

.label-as-badge {
    border-radius: 1em;
}

Compare this label and badge side by side:

<span class="label label-default label-as-badge">hello</span>
<span class="badge">world</span>

enter image description here

They appear the same. But in the CSS, label uses em so it scales nicely, and it still has all the "-color" classes. So the label will scale to bigger font sizes better, and can be colored with label-success, label-warning, etc. Here are two examples:

<span class="label label-success label-as-badge">Yay! Rah!</span>

enter image description here

Or where things are bigger:

<div style="font-size: 36px"><!-- pretend an enclosing class has big font size -->
    <span class="label label-success label-as-badge">Yay! Rah!</span>
</div>

enter image description here


11/16/2015: Looking at how we'll do this in Bootstrap 4

Looks like .badge classes are completely gone. But there's a built-in .label-pill class (here) that looks like what we want.

.label-pill {
  padding-right: .6em;
  padding-left: .6em;
  border-radius: 10rem;
}

In use it looks like this:

<span class="label label-pill label-default">Default</span>
<span class="label label-pill label-primary">Primary</span>
<span class="label label-pill label-success">Success</span>
<span class="label label-pill label-info">Info</span>
<span class="label label-pill label-warning">Warning</span>
<span class="label label-pill label-danger">Danger</span>

enter image description here


11/04/2014: Here's an update on why cross-pollinating alert classes with .badge is not so great. I think this picture sums it up:

enter image description here

Those alert classes were not designed to go with badges. It renders them with a "hint" of the intended colors, but in the end consistency is thrown out the window and readability is questionable. Those alert-hacked badges are not visually cohesive.

The .label-as-badge solution is only extending the bootstrap design. We are keeping intact all the decision making made by the bootstrap designers, namely the consideration they gave for readability and cohesion across all the possible colors, as well as the color choices themselves. The .label-as-badge class only adds rounded corners, and nothing else. There are no color definitions introduced. Thus, a single line of CSS.

Yep, it is easier to just hack away and drop in those .alert-xxxxx classes -- you don't have to add any lines of CSS. Or you could care more about the little things and add one line.

How to get the day name from a selected date?

If you want to know the day of the week for your code to do something with it, DateTime.Now.DayOfWeek will do the job.

If you want to display the day of week to the user, DateTime.Now.ToString("dddd") will give you the localized day name, according to the current culture (MSDN info on the "dddd" format string).

How to merge multiple lists into one list in python?

import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)

Just another method....

Where is the Global.asax.cs file?

That's because you created a Web Site instead of a Web Application. The cs/vb files can only be seen in a Web Application, but in a website you can't have a separate cs/vb file.

Edit: In the website you can add a cs file behavior like..

<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>

~/Global.asax.cs:

namespace ApplicationName
{
    public partial class MyApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
        }
    }
}

How to pass html string to webview on android

i have successfully done by below line

 //data == html data which you want to load
 String data = "Your data which you want to load";

 WebView webview = (WebView)this.findViewById(R.id.webview);
 webview.getSettings().setJavaScriptEnabled(true);
 webview.loadData(data, "text/html; charset=utf-8", "UTF-8");

Or You can try

 webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

HTML Image not displaying, while the src url works

Your file needs to be located inside your www directory. For example, if you're using wamp server on Windows, j3evn.jpg should be located,

C:/wamp/www/img/j3evn.jpg

and you can access it in html via

<img class="sealImage" alt="Image of Seal" src="../img/j3evn.jpg">

Look for the www, public_html, or html folder belonging to your web server. Place all your files and resources inside that folder.

Hope this helps!

How to find the unclosed div tag

Use notepad ++ . you can find them easily

http://notepad-plus-plus.org/download/

Or you can View source from FIREfox - Unclosed divs will be shown in RED

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

jus do this import { shallow, mount } from "enzyme";

const store = mockStore({
  startup: { complete: false }
});

describe("==== Testing App ======", () => {
  const setUpFn = props => {
    return mount(
      <Provider store={store}>
        <App />
      </Provider>
    );
  };

  let wrapper;
  beforeEach(() => {
    wrapper = setUpFn();
  });

xampp MySQL does not start

If there are two instances of MySql it's normal that it gives such an error if they both run at the same time. If you really need 2 servers, you must change the listening port of one of them, or if you don't it's probably better to simply uninstall one of them. This is so regarless of MySql itself, because two programs cannot listen on the same port at the same time.

R: Plotting a 3D surface from x, y, z

Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?

x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)

HTTP authentication logout via PHP

AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.

This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details. From then on, until the browser is closed, it will always send the credentials without further prompting.

Is there a "previous sibling" selector?

Removing the styles of next siblings on hover, so that it looks like only previous siblings have styles added on hover.

_x000D_
_x000D_
ul li {
  color: red;
  cursor: pointer;
}

ul:hover li {
  color: blue;
}

ul:hover li:hover ~ li{
  color: red;
}
_x000D_
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>
_x000D_
_x000D_
_x000D_

How to make the first option of <select> selected with jQuery

Although the each function probably isn't necessary ...

$('select').each(function(){
    $(this).find('option:first').prop('selected', 'selected');
});

works for me.

Git keeps asking me for my ssh key passphrase

on mac, if your ssh key need passphrase everytime and you want to skip it, then you can try below, it works fine for me

  1. eval "$(ssh-agent -s)"
  2. ssh-add -K .ssh/id_rsa
  3. add this default ssh configuration works for me

Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa

Android - Package Name convention

Android follows normal java package conventions plus here is an important snippet of text to read (this is important regarding the wide use of xml files while developing on android).

The reason for having it in reverse order is to do with the layout on the storage media. If you consider each period ('.') in the application name as a path separator, all applications from a publisher would sit together in the path hierarchy. So, for instance, packages from Adobe would be of the form:

com.adobe.reader (Adobe Reader)

com.adobe.photoshop (Adobe Photoshop)

com.adobe.ideas (Adobe Ideas)

[Note that this is just an illustration and these may not be the exact package names.]

These could internally be mapped (respectively) to:

com/adobe/reader

com/adobe/photoshop

com/adobe/ideas

The concept comes from Package Naming Conventions in Java, more about which can be read here:*

http://en.wikipedia.org/wiki/Java_package#Package_naming_conventions

Source: http://www.quora.com/Why-do-a-majority-of-Android-package-names-begin-with-com

Base table or view not found: 1146 Table Laravel 5

When you are passing the custom request in the controller method, and your request file doesn't follow the proper syntax or table name is changed, then laravel through this type of exception. I'll show you in Example.

My Request code.
     public function rules()
        {
            return [
                'name' => 'required|unique:posts|max:50',
                'description' => 'required',
            ];
        }

But my table name is todos not posts so that's why it through "Base table or view not found: 1146 Table Laravel 7


    I forgot to change the table name in first index.
     public function rules()
        {
            return [
                'name' => 'required|unique:todos|max:50',
                'description' => 'required',
            ];
        }

How do I flush the PRINT buffer in TSQL?

Yes... The first parameter of the RAISERROR function needs an NVARCHAR variable. So try the following;

-- Replace PRINT function
DECLARE @strMsg NVARCHAR(100)
SELECT @strMsg = 'Here''s your message...'
RAISERROR (@strMsg, 0, 1) WITH NOWAIT

OR

RAISERROR (n'Here''s your message...', 0, 1) WITH NOWAIT

How can I check for NaN values?

With python < 2.6 I ended up with

def isNaN(x):
    return str(float(x)).lower() == 'nan'

This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

Function to calculate distance between two coordinates

Derek's solution worked fine for me, and I've just simply converted it to PHP, hope it helps somebody out there !

function calcCrow($lat1, $lon1, $lat2, $lon2){
        $R = 6371; // km
        $dLat = toRad($lat2-$lat1);
        $dLon = toRad($lon2-$lon1);
        $lat1 = toRad($lat1);
        $lat2 = toRad($lat2);

        $a = sin($dLat/2) * sin($dLat/2) +sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2); 
        $c = 2 * atan2(sqrt($a), sqrt(1-$a)); 
        $d = $R * $c;
        return $d;
}

// Converts numeric degrees to radians
function toRad($Value) 
{
    return $Value * pi() / 180;
}

CSS image overlay with color and transparency

If you want to make the reverse of what you showed consider doing this:

.tint:hover:before {
    background: rgba(0,0,250, 0.5);

  }

  .t2:before {
    background: none;
  }

and look at the effect on the 2nd picture.

Is it supposed to look like this?

What is HEAD in Git?

I'd just like to detail a few things in Greg Hewgil's accepted answer. According to the Git Pocket Guide

Branch:

the branch itself is defined as all points reachable in the commit graph from the named commit (the “tip” of the branch).

HEAD: A special type of Ref

The special ref HEAD determines what branch you are on...

Refs

Git defines two kinds of references, or named pointers, which it calls “refs”:

  • A simple ref, which points directly to an object ID (usually a commit or tag)
  • A symbolic ref (or symref), which points to another ref (either simple or symbolic)

As Greg mentioned, HEAD can be in a "detached state". So HEAD can be either a simple ref (for a detached HEAD) or a symref.

if HEAD is a symbolic ref for an existing branch, then you are “on” that branch. If, on the other hand, HEAD is a simple ref directly naming a commit by its SHA-1 ID, then you are not “on” any branch, but rather in “detached HEAD” mode, which happens when you check out some earlier commit to examine.

Highlight a word with jQuery

I have created a repository on similar concept that changes the colors of the texts whose colors are recognised by html5 (we don't have to use actual #rrggbb values and could just use the names as html5 standardised about 140 of them)

colors.js colors.js

_x000D_
_x000D_
$( document ).ready(function() {_x000D_
 _x000D_
 function hiliter(word, element) {_x000D_
  var rgxp = new RegExp("\\b" + word + "\\b" , 'gi'); // g modifier for global and i for case insensitive _x000D_
  var repl = '<span class="myClass">' + word + '</span>';_x000D_
  element.innerHTML = element.innerHTML.replace(rgxp, repl);_x000D_
   _x000D_
   };_x000D_
_x000D_
 hiliter('dolor', document.getElementById('dolor'));_x000D_
});
_x000D_
.myClass{_x000D_
_x000D_
background-color:red;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
 <head>_x000D_
  <title>highlight</title>_x000D_
  _x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
 _x000D_
   <link href="main.css" type="text/css"  rel="stylesheet"/>_x000D_
   _x000D_
 </head>_x000D_
 <body id='dolor'>_x000D_
<p >_x000D_
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit._x000D_
</p>_x000D_
<p>_x000D_
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero._x000D_
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris._x000D_
</p>_x000D_
 <script type="text/javascript" src="main.js" charset="utf-8"></script>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do you convert a byte array to a hexadecimal string in C?

For simple usage I made a function that encodes the input string (binary data):

/* Encodes string to hexadecimal string reprsentation
    Allocates a new memory for supplied lpszOut that needs to be deleted after use
    Fills the supplied lpszOut with hexadecimal representation of the input
    */
void StringToHex(unsigned char *szInput, size_t size_szInput, char **lpszOut)
{
    unsigned char *pin = szInput;
    const char *hex = "0123456789ABCDEF";
    size_t outSize = size_szInput * 2 + 2;
    *lpszOut = new char[outSize];
    char *pout = *lpszOut;
    for (; pin < szInput + size_szInput; pout += 2, pin++)
    {
        pout[0] = hex[(*pin >> 4) & 0xF];
        pout[1] = hex[*pin & 0xF];
    }
    pout[0] = 0;
}

Usage:

unsigned char input[] = "This is a very long string that I want to encode";
char *szHexEncoded = NULL;
StringToHex(input, strlen((const char *)input), &szHexEncoded);

printf(szHexEncoded);

// The allocated memory needs to be deleted after usage
delete[] szHexEncoded;

Truncating long strings with CSS: feasible yet?

2014 March: Truncating long strings with CSS: a new answer with focus on browser support

Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).

<style type="text/css">
    span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;     /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
        -o-text-overflow: ellipsis;  /** Opera 9 & 10 **/
        width: 370px; /* note that this width will have to be smaller to see the effect */
    }
</style>

<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>

The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.

Successfully tested (on Browserstack.com) on Windows OS, for web browsers:

  • IE6 to IE11
  • Opera 10.6, Opera 11.1, Opera 15.0, Opera 20.0
  • Chrome 14, Chrome 20, Chrome 25
  • Safari 4.0, Safari 5.0, Safari 5.1
  • Firefox 7.0, Firefox 15

Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).

I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).

Some further testing on a Mac OS web browsers would be needed.

Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated

Resources:

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Removing Spaces from a String in C?

#include<stdio.h>
#include<string.h>
main()
{
  int i=0,n;
  int j=0;
  char str[]="        Nar ayan singh              ";
  char *ptr,*ptr1;
  printf("sizeof str:%ld\n",strlen(str));
  while(str[i]==' ')
   {
     memcpy (str,str+1,strlen(str)+1);
   }
  printf("sizeof str:%ld\n",strlen(str));
  n=strlen(str);
  while(str[n]==' ' || str[n]=='\0')
    n--;
  str[n+1]='\0';
  printf("str:%s ",str);
  printf("sizeof str:%ld\n",strlen(str));
}

Merge DLL into EXE?

Use Costura.Fody.

You just have to install the nuget and then do a build. The final executable will be standalone.

Making an array of integers in iOS

I created a simple Objective C wrapper around the good old C array to be used more conveniently: https://gist.github.com/4705733

How to force C# .net app to run only one instance in Windows?

This is what I use in my application:

static void Main()
{
  bool mutexCreated = false;
  System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );

  if( !mutexCreated )
  {
    if( MessageBox.Show(
      "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
      "slimKEYS already running",
      MessageBoxButtons.YesNo,
      MessageBoxIcon.Question ) != DialogResult.Yes )
    {
      mutex.Close();
      return;
    }
  }

  // The usual stuff with Application.Run()

  mutex.Close();
}

z-index not working with position absolute

z-index only applies to elements that have been given an explicit position. Add position:relative to #popupContent and you should be good to go.

What is the convention for word separator in Java package names?

The official naming conventions aren't that strict, they don't even 'forbid' camel case notation except for prefix (com in your example).

But I personally would avoid upper case letters and hyphenations, even numbers. I'd choose com.stackoverflow.mypackage like Bragboy suggested too.

(hyphenations '-' are not legal in package names)

EDIT

Interesting - the language specification has something to say about naming conventions too.

In Chapter 7.7 Unique Package Names we see examples with package names that consist of upper case letters (so CamelCase notation would be OK) and they suggest to replace hyphonation by an underscore ("mary-lou" -> "mary_lou") and prefix java keywords with an underscore ("com.example.enum" -> "com.example._enum")

Some more examples for upper case letters in package names can be found in chapter 6.8.1 Package Names.

Run bash command on jenkins pipeline

I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)

Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps

pipeline {
    agent none

    stages {

        stage ('Hello') {
            agent any

            steps {
                echo 'Hello, '

                sh '''#!/bin/bash

                    echo "Hello from bash"
                    echo "Who I'm $SHELL"
                '''
            }
        }
    }
}

The result of the above execution is

enter image description here

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Yes even I got the same error. So I did the following changes

-> Check the error in the Problems tab located near the Console tab

-> See where the error persists, Its possible that some jar file may be corrupted or is outdated so, pom isn't activated in the Project.

-> I found one of my jar was outdated version so I updated it by getting the dependencies from maven repository from this link https://mvnrepository.com

So to conclude, do check where the error persist and which jar file is outdated and make changes accordingly

SSL: CERTIFICATE_VERIFY_FAILED with Python3

On Debian 9 I had to:

$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs

I'm not sure why, but this enviroment variable was never set.

Change working directory in my current shell context when running Node script

The correct way to change directories is actually with process.chdir(directory). Here's an example from the documentation:

console.log('Starting directory: ' + process.cwd());
try {
  process.chdir('/tmp');
  console.log('New directory: ' + process.cwd());
}
catch (err) {
  console.log('chdir: ' + err);
}

This is also testable in the Node.js REPL:

[monitor@s2 ~]$ node
> process.cwd()
'/home/monitor'
> process.chdir('../');
undefined
> process.cwd();
'/home'

Create a file if one doesn't exist - C

You typically have to do this in a single syscall, or else you will get a race condition.

This will open for reading and writing, creating the file if necessary.

FILE *fp = fopen("scores.dat", "ab+");

If you want to read it and then write a new version from scratch, then do it as two steps.

FILE *fp = fopen("scores.dat", "rb");
if (fp) {
    read_scores(fp);
}

// Later...

// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
    error();
write_scores(fp);

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Error after upgrading pip: cannot import name 'main'

Check if pip has been cached on another path, to do so, call $ which pip and check that the path is different from the one prompted in the error, if that's the case run:

$ hash -r

When the cache is clear, pip will be working again. reference: http://cheng.logdown.com/posts/2015/06/14/-usr-bin-pip-no-such-file-or-directory

How to remove all leading zeroes in a string

Regex was proposed already, but not correctly:

<?php
    $number = '00000004523423400023402340240';
    $withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
    echo $withoutLeadingZeroes;
?>

output is then:

4523423400023402340240

Background on Regex: the ^ signals beginning of string and the + sign signals more or none of the preceding sign. Therefore, the regex ^0+ matches all zeroes at the beginning of a string.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

In bootstrap 3, this works well for me:

.btn-link.btn-anchor {
    outline: none !important;
    padding: 0;
    border: 0;
    vertical-align: baseline;
}

Used like:

<button type="button" class="btn-link btn-anchor">My Button</button>

Demo

mat-form-field must contain a MatFormFieldControl

In my case, one of my closing parenthesis for "onChanges()" were missed on the input element and thus the input element was apparently not being rendered at all:

<input mat-menu-item 
      matInput type="text" 
      [formControl]="myFormControl"
      (ngModelChange)="onChanged()>

How to mark a method as obsolete or deprecated?

To mark as obsolete with a warning:

[Obsolete]
private static void SomeMethod()

You get a warning when you use it:

Obsolete warning is shown

And with IntelliSense:

Obsolete warning with IntelliSense

If you want a message:

[Obsolete("My message")]
private static void SomeMethod()

Here's the IntelliSense tool tip:

IntelliSense shows the obsolete message

Finally if you want the usage to be flagged as an error:

[Obsolete("My message", true)]
private static void SomeMethod()

When used this is what you get:

Method usage is displayed as an error

Note: Use the message to tell people what they should use instead, not why it is obsolete.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Actually, you need to update your repo first, then an upgrade of your Glibc can fix this issue.

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

What's the difference between identifying and non-identifying relationships?

user287724's answer gives the following example of the book and author relationship:

A book however is written by an author, and the author could have written multiple books. But the book needs to be written by an author it cannot exist without an author. Therefore the relationship between the book and the author is an identifying relationship.

This is a very confusing example and is definitely not a valid example for an identifying relationship.

Yes, a book can not be written without at least one author, but the author(it's foreign key) of the book is NOT IDENTIFYING the book in the books table!

You can remove the author (FK) from the book row and still can identify the book row by some other field (ISBN, ID, ...etc) , BUT NOT the author of the book!!

I think a valid example of an identifying relationship would be the relationship between (products table) and a (specific product details table) 1:1

products table
+------+---------------+-------+--------+
|id(PK)|Name           |type   |amount  |
+------+---------------+-------+--------+
|0     |hp-laser-510   |printer|1000    |
+------+---------------+-------+--------+
|1     |viewsonic-10   |screen |900     |
+------+---------------+-------+--------+
|2     |canon-laser-100|printer|200     |
+------+---------------+-------+--------+

printers_details table
+--------------+------------+---------+---------+------+
|Product_ID(FK)|manufacturer|cartridge|color    |papers|
+--------------+------------+---------+---------+------+
|0             |hp          |CE210    |BLACK    |300   |
+--------------+------------+---------+---------+------+
|2             |canon       |MKJ5     |COLOR    |900   |
+--------------+------------+---------+---------+------+
* please note this is not real data

In this example the Product_ID in the printers_details table is considered a FK references the products.id table and ALSO a PK in the printers_details table , this is an identifying relationship because the Product_ID(FK) in the printers table IS IDENTIFYING the row inside the child table, we can't remove the product_id from the child table because we can't identify the row any more because we lost it's primary key

If you want to put it in 2 lines:

an identifying relationship is the relationship when the FK in the child table is considered a PK(or identifier) in the child table while still references the parent table

Another example may be when you have 3 tables (imports - products - countries) in an imports and exports for some country database

The import table is the child that has these fields(the product_id(FK), the country_id(FK) , the amount of the imports , the price , the units imported , the way of transport(air, sea) ) we may use the (product_id, thecountry_id`) to identify each row of the imports "if they all in the same year" here the both columns can compose together a primary key in the child table(imports) and also referencing there parent tables.

Please I'm happy I finally understand the concept of the identifying relationship and non identifying relationship, so please don't tell me I'm wrong with all of these vote ups for a completely invalid example

Yes logically a book can't be written without an author but a book can be identified without the author,In fact it can't be identified with the author!

You can 100% remove the author from the book row and still can identify the book!.

Array to Hash Ruby

You could try like this, for single array

irb(main):019:0> a = ["item 1", "item 2", "item 3", "item 4"]
  => ["item 1", "item 2", "item 3", "item 4"]
irb(main):020:0> Hash[*a]
  => {"item 1"=>"item 2", "item 3"=>"item 4"}

for array of array

irb(main):022:0> a = [[1, 2], [3, 4]]
  => [[1, 2], [3, 4]]
irb(main):023:0> Hash[*a.flatten]
  => {1=>2, 3=>4}

Git: can't undo local changes (error: path ... is unmerged)

git checkout origin/[branch] .
git status

// Note dot (.) at the end. And all will be good

How to use if statements in underscore.js templates?

This should do the trick:

<% if (typeof(date) !== "undefined") { %>
    <span class="date"><%= date %></span>
<% } %>

Remember that in underscore.js templates if and for are just standard javascript syntax wrapped in <% %> tags.

compare differences between two tables in mysql

INTERSECT needs to be emulated in MySQL:

SELECT  'robot' AS `set`, r.*
FROM    robot r
WHERE   ROW(r.col1, r.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    tbd_robot
        )
UNION ALL
SELECT  'tbd_robot' AS `set`, t.*
FROM    tbd_robot t
WHERE   ROW(t.col1, t.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    robot
        )

How to split (chunk) a Ruby array into parts of X elements?

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

angular-cli server - how to specify default port

For @angular/cli v6.2.1

The project configuration file angular.json is able to handle multiple projects (workspaces) which can be individually served.

ng config projects.my-test-project.targets.serve.options.port 4201

Where the my-test-project part is the project name what you set with the ng new command just like here:

$ ng new my-test-project
$ cd my-test-project
$ ng config projects.my-test-project.targets.serve.options.port 4201
$ ng serve
** Angular Live Development Server is listening on localhost:4201, open your browser on http://localhost:4201/ **

Legacy:

I usually use the ng set command to change the Angular CLI settings for project level.

ng set defaults.serve.port=4201

It changes change your .angular.cli.json and adds the port settings as it mentioned earlier.

After this change you can use simply ng serve and it going to use the prefered port without the need of specifying it every time.

How to view AndroidManifest.xml from APK file?

Aapt2, included in the Android SDK build tools can do this - no third party tools needed.

$(ANDROID_SDK)/build-tools/28.0.3/aapt2 d --file AndroidManifest.xml app-foo-release.apk

Starting with build-tools v29 you have to add the command xmltree:

$(ANDROID_SDK)/build-tools/29.0.3/aapt2 d xmltree --file AndroidManifest.xml app-foo-release.apk

Why is JsonRequestBehavior needed?

MVC defaults to DenyGet to protect you against a very specific attack involving JSON requests to improve the liklihood that the implications of allowing HTTP GET exposure are considered in advance of allowing them to occur.

This is opposed to afterwards when it might be too late.

Note: If your action method does not return sensitive data, then it should be safe to allow the get.

Further reading from my Wrox ASP.NET MVC3 book

By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request. For more details, see Phil's post at http://haacked.com/archive/2009/06/24/json-hijacking.aspx/ or this SO post.

Haack, Phil (2011). Professional ASP.NET MVC 3 (Wrox Programmer to Programmer) (Kindle Locations 6014-6020). Wrox. Kindle Edition.

Related StackOverflow question

With most recents browsers (starting with Firefox 21, Chrome 27, or IE 10), this is no more a vulnerability.

get current date with 'yyyy-MM-dd' format in Angular 4

If you only want to display then you can use date pipe in HTML like this :

Just Date:

your date | date: 'dd MMM yyyy'

Date With Time:

your date | date: 'dd MMM yyyy hh:mm a'

And if you want to take input only date from new Date() then :

You can use angular formatDate() in ts file like this -

currentDate = new Date();

const cValue = formatDate(currentDate, 'yyyy-MM-dd', 'en-US');

Configure WAMP server to send email

You need a SMTP server to send your mail. If you have one available which does not require SMTP authentification (maybe your ISP's?) just edit the 'SMTP' ([mail function]) setting in your php.ini file.

If this is no option because your SMTP server requires authentification you won't be able to use the internal mail() function and have to use some 3rd party class which supports smtp auth. e.g. http://pear.php.net/package/Mail/

Javascript form validation with password confirming

 if ($("#Password").val() != $("#ConfirmPassword").val()) {
          alert("Passwords do not match.");
      }

A JQuery approach that will eliminate needless code.

What is the use of adding a null key or value to a HashMap in Java?

Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"

How to check if my string is equal to null?

I always use like this:

if (mystr != null && !mystr.isEmpty()){
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}else {
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}

or you can copy this to your project:

private boolean isEmptyOrNull(String mystr){
    if (mystr != null && !mystr.isEmpty()){ return true; }
    else { return false; }
}

and just call it like :

boolean b = isEmptyOrNull(yourString);

it will return true if is empty or null.
b=true if is empty or null

or you can use try catch and catch when it is null.

How to get hex color value rather than RGB value?

Same answer like @Jim F answer but ES6 syntax , so, less instructions :

const rgb2hex = (rgb) => {
  if (rgb.search("rgb") === -1) return rgb;
  rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
  const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2);
  return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
};

cd into directory without having permission

Enter super user mode, and cd into the directory that you are not permissioned to go into. Sudo requires administrator password.

sudo su
cd directory

Can I convert a C# string value to an escaped string literal

Here is a little improvement for Smilediver's answer, it will not escape all no-ASCII chars but only these are really needed.

using System;
using System.Globalization;
using System.Text;

public static class CodeHelper
{
    public static string ToLiteral(this string input)
    {
        var literal = new StringBuilder(input.Length + 2);
        literal.Append("\"");
        foreach (var c in input)
        {
            switch (c)
            {
                case '\'': literal.Append(@"\'"); break;
                case '\"': literal.Append("\\\""); break;
                case '\\': literal.Append(@"\\"); break;
                case '\0': literal.Append(@"\0"); break;
                case '\a': literal.Append(@"\a"); break;
                case '\b': literal.Append(@"\b"); break;
                case '\f': literal.Append(@"\f"); break;
                case '\n': literal.Append(@"\n"); break;
                case '\r': literal.Append(@"\r"); break;
                case '\t': literal.Append(@"\t"); break;
                case '\v': literal.Append(@"\v"); break;
                default:
                    if (Char.GetUnicodeCategory(c) != UnicodeCategory.Control)
                    {
                        literal.Append(c);
                    }
                    else
                    {
                        literal.Append(@"\u");
                        literal.Append(((ushort)c).ToString("x4"));
                    }
                    break;
            }
        }
        literal.Append("\"");
        return literal.ToString();
    }
}

How to execute a Ruby script in Terminal?

Just invoke ruby XXXXX.rb in terminal, if the interpreter is in your $PATH variable.

( this can hardly be a rails thing, until you have it running. )

Show row number in row header of a DataGridView

You can also draw the string dynamically inside the RowPostPaint event:

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Since the question was "display" :

@Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}")

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

For each row in an R dataframe

I use this simple utility function:

rows = function(tab) lapply(
  seq_len(nrow(tab)),
  function(i) unclass(tab[i,,drop=F])
)

Or a faster, less clear form:

rows = function(x) lapply(seq_len(nrow(x)), function(i) lapply(x,"[",i))

This function just splits a data.frame to a list of rows. Then you can make a normal "for" over this list:

tab = data.frame(x = 1:3, y=2:4, z=3:5)
for (A in rows(tab)) {
    print(A$x + A$y * A$z)
}        

Your code from the question will work with a minimal modification:

for (well in rows(dataFrame)) {
  wellName <- well$name    # string like "H1"
  plateName <- well$plate  # string like "plate67"
  wellID <- getWellID(wellName, plateName)
  cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}

Maven : error in opening zip file when running maven

I downloaded the jar file manually and replace the one in my local directory and it worked

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

Skip download if files exist in wget?

The answer I was looking for is at https://unix.stackexchange.com/a/9557/114862.

Using the -c flag when the local file is of greater or equal size to the server version will avoid re-downloading.

link_to method and click event in Rails

just use

=link_to "link", "javascript:function()"

Copying sets Java

The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from). When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:

findbugs says

The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.

As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.

Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:

Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
    copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));

Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.

What is inf and nan?

nan means "not a number", a float value that you get if you perform a calculation whose result can't be expressed as a number. Any calculations you perform with NaN will also result in NaN.

inf means infinity.

For example:

>>> 2*float("inf")
inf
>>> -2*float("inf")
-inf
>>> float("inf")-float("inf")
nan

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

What you need (for tic-tac-toe or a far more difficult game like Chess) is the minimax algorithm, or its slightly more complicated variant, alpha-beta pruning. Ordinary naive minimax will do fine for a game with as small a search space as tic-tac-toe, though.

In a nutshell, what you want to do is not to search for the move that has the best possible outcome for you, but rather for the move where the worst possible outcome is as good as possible. If you assume your opponent is playing optimally, you have to assume they will take the move that is worst for you, and therefore you have to take the move that MINimises their MAXimum gain.

How to check if another instance of my shell script is running

Use the PS command in a little different way to ignore child process as well:

ps -eaf | grep -v grep | grep $PROCESS | grep -v $$

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

Previous answers are correct: adding the line...

Response.AddHeader("Content-Disposition", "inline; filename=[filename]");

...will causing multiple Content-Disposition headers to be sent down to the browser. This happens b/c FileContentResult internally applies the header if you supply it with a file name. An alternative, and pretty simple, solution is to simply create a subclass of FileContentResult and override its ExecuteResult() method. Here's an example that instantiates an instance of the System.Net.Mime.ContentDisposition class (the same object used in the internal FileContentResult implementation) and passes it into the new class:

public class FileContentResultWithContentDisposition : FileContentResult
{
    private const string ContentDispositionHeaderName = "Content-Disposition";

    public FileContentResultWithContentDisposition(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
        : base(fileContents, contentType)
    {
        // check for null or invalid ctor arguments
        ContentDisposition = contentDisposition;
    }

    public ContentDisposition ContentDisposition { get; private set; }

    public override void ExecuteResult(ControllerContext context)
    {
        // check for null or invalid method argument
        ContentDisposition.FileName = ContentDisposition.FileName ?? FileDownloadName;
        var response = context.HttpContext.Response;
        response.ContentType = ContentType;
        response.AddHeader(ContentDispositionHeaderName, ContentDisposition.ToString());
        WriteFile(response);
    }
}

In your Controller, or in a base Controller, you can write a simple helper to instantiate a FileContentResultWithContentDisposition and then call it from your action method, like so:

protected virtual FileContentResult File(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
{
    var result = new FileContentResultWithContentDisposition(fileContents, contentType, contentDisposition);
    return result;
}

public ActionResult Report()
{
    // get a reference to your document or file
    // in this example the report exposes properties for
    // the byte[] data and content-type of the document
    var report = ...
    return File(report.Data, report.ContentType, new ContentDisposition {
        Inline = true,
        FileName = report.FileName
    });
}

Now the file will be sent to the browser with the file name you choose and with a content-disposition header of "inline; filename=[filename]".

I hope that helps!

Split / Explode a column of dictionaries into separate columns with pandas

Merlin's answer is better and super easy, but we don't need a lambda function. The evaluation of dictionary can be safely ignored by either of the following two ways as illustrated below:

Way 1: Two steps

# step 1: convert the `Pollutants` column to Pandas dataframe series
df_pol_ps = data_df['Pollutants'].apply(pd.Series)

df_pol_ps:
    a   b   c
0   46  3   12
1   36  5   8
2   NaN 2   7
3   NaN NaN 11
4   82  NaN 15

# step 2: concat columns `a, b, c` and drop/remove the `Pollutants` 
df_final = pd.concat([df, df_pol_ps], axis = 1).drop('Pollutants', axis = 1)

df_final:
    StationID   a   b   c
0   8809    46  3   12
1   8810    36  5   8
2   8811    NaN 2   7
3   8812    NaN NaN 11
4   8813    82  NaN 15

Way 2: The above two steps can be combined in one go:

df_final = pd.concat([df, df['Pollutants'].apply(pd.Series)], axis = 1).drop('Pollutants', axis = 1)

df_final:
    StationID   a   b   c
0   8809    46  3   12
1   8810    36  5   8
2   8811    NaN 2   7
3   8812    NaN NaN 11
4   8813    82  NaN 15

How to implement "Access-Control-Allow-Origin" header in asp.net

Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.

Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:

{
  "/api": {
    "target": "http://localhost:49389",
    "secure": true,
    "pathRewrite": {
      "^/api": "/api"
    },
    "changeOrigin": true
  }
}

Put the file in the same directory the package.json then I modified the start command in the package.json file like below

"start": "ng serve --proxy-config proxy.conf.json"

now, the http call from the app component is as follows:

return this.http.get('/api/customers').map((res: Response) => res.json());

Lastly to run use npm start or ng serve --proxy-config proxy.conf.json

Storing Images in PostgreSQL

Try this. I've use the Large Object Binary (LOB) format for storing generated PDF documents, some of which were 10+ MB in size, in a database and it worked wonderfully.

What does ON [PRIMARY] mean?

ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

For Python set - signature_version s3v4

s3 = boto3.client(
   's3',
   aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
   aws_secret_access_key='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE',
   config=Config(signature_version='s3v4')
)