Programs & Examples On #Datafield

How to get coordinates of an svg element?

I use the consolidate function, like so:

 element.transform.baseVal.consolidate()

The .e and .f values correspond to the x and y coordinates

How to refresh Gridview after pressed a button in asp.net

I was totally lost on why my Gridview.Databind() would not refresh.

My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:

gvServerConfiguration.Databind()
uppServerConfiguration.Update()

uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.

Hope this helps someone.

How to fix date format in ASP .NET BoundField (DataFormatString)?

Formatting depends on the server's culture setting. If you use en-US culture, you can use Short Date Pattern like {0:d}

For example, it formats 6/15/2009 1:45:30 to 6/15/2009

You can check more formats from BoundField.DataFormatString

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}

ASP.NET Setting width of DataBound column in GridView

This is going to work for all situations while working with width.

`<asp:TemplateField HeaderText="DATE">
   <ItemTemplate>
   <asp:Label ID="Label1" runat="server" Text='<%# Bind("date") %>' Width="100px"></asp:Label>
   </ItemTemplate>
  </asp:TemplateField>`

How to delete row in gridview using rowdeleting event?

//message box before deletion
protected void grdEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach (DataControlFieldCell cell in e.Row.Cells)
        {
            foreach (Control control in cell.Controls)
            {
                LinkButton button = control as LinkButton;
                if (button != null && button.CommandName == "Delete")
                    button.OnClientClick = "if (!confirm('Are you sure " +
                           "you want to delete this record?')) return false;";
            }
        }
    }
}

//deletion
protected void grdEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    conn.Open();
    int empid = Convert.ToInt32(((Label)grdEmployee.Rows[e.RowIndex].Cells[0].FindControl("lblIdBind")).Text);
    SqlCommand cmdDelete = new SqlCommand("Delete from employee_details where id=" + empid, conn);
    cmdDelete.ExecuteNonQuery();
    conn.Close();
    grdEmployee_refreshdata();

}

Looping through GridView rows and Checking Checkbox Control

you have to iterate gridview Rows

for (int count = 0; count < grd.Rows.Count; count++)
{
    if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
    {     
      ((Label)grd.Rows[count].FindControl("labelID")).Text
    }
}

How to hide a column (GridView) but still access its value?

<head runat="server">
<title>Accessing GridView Hidden Column value </title>
<style type="text/css">
  .hiddencol
  {
    display: none;
  }
</style>

<asp:BoundField HeaderText="Email ID" DataField="EmailId" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
</asp:BoundField>

ArrayList EmailList = new ArrayList();
foreach (GridViewRow itemrow in gvEmployeeDetails.Rows)
{
  EmailList.Add(itemrow.Cells[YourIndex].Text);
}

How to convert int to char with leading zeros?

DECLARE @number1 INT, @number2 INT

SET @number1 = 1

SET @number2 = 867

-- Without the 'RTRIM', the value returned is 3__ !!!

SELECT RIGHT('000' + RTRIM(CAST(@number1 AS NCHAR(3)), 3 )) AS NUMBER_CONVERTED

-- Without the 'RTRIM', the value returned is 867___ !!!

SELECT RIGHT('000000' + RTRIM(CAST(@number2 AS NCHAR(6)), 6 )) AS NUMBER_CONVERTED

GridView sorting: SortDirection always Ascending

You can use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction.

Example:

DataTable sourceTable = GridAttendence.DataSource as DataTable;
DataView view = new DataView(sourceTable);
string[] sortData = ViewState["sortExpression"].ToString().Trim().Split(' ');
if (e.SortExpression == sortData[0])
{
    if (sortData[1] == "ASC")
    {
        view.Sort = e.SortExpression + " " + "DESC";
        this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC";
    }
    else
    {
        view.Sort = e.SortExpression + " " + "ASC";
        this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
    }
}
else
{
    view.Sort = e.SortExpression + " " + "ASC";
    this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}

Can I convert a boolean to Yes/No in a ASP.NET GridView

Nope - but you could use a template column:

<script runat="server">
  TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
     object o = DataBinder.Eval(Container.DataItem, field);
     if (converter == null) {
        return (TResult)o;
     }
     return converter((T)o);
  }
</script>

<asp:TemplateField>
  <ItemTemplate>
     <%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
  </ItemTemplate>
</asp:TemplateField>

Solutions for INSERT OR UPDATE on SQL Server

/*
CREATE TABLE ApplicationsDesSocietes (
   id                   INT IDENTITY(0,1)    NOT NULL,
   applicationId        INT                  NOT NULL,
   societeId            INT                  NOT NULL,
   suppression          BIT                  NULL,
   CONSTRAINT PK_APPLICATIONSDESSOCIETES PRIMARY KEY (id)
)
GO
--*/

DECLARE @applicationId INT = 81, @societeId INT = 43, @suppression BIT = 0

MERGE dbo.ApplicationsDesSocietes WITH (HOLDLOCK) AS target
--set the SOURCE table one row
USING (VALUES (@applicationId, @societeId, @suppression))
    AS source (applicationId, societeId, suppression)
    --here goes the ON join condition
    ON target.applicationId = source.applicationId and target.societeId = source.societeId
WHEN MATCHED THEN
    UPDATE
    --place your list of SET here
    SET target.suppression = source.suppression
WHEN NOT MATCHED THEN
    --insert a new line with the SOURCE table one row
    INSERT (applicationId, societeId, suppression)
    VALUES (source.applicationId, source.societeId, source.suppression);
GO

Replace table and field names by whatever you need. Take care of the using ON condition. Then set the appropriate value (and type) for the variables on the DECLARE line.

Cheers.

Java Pass Method as Parameter

First define an Interface with the method you want to pass as a parameter

public interface Callable {
  public void call(int param);
}

Implement a class with the method

class Test implements Callable {
  public void call(int param) {
    System.out.println( param );
  }
}

// Invoke like that

Callable cmd = new Test();

This allows you to pass cmd as parameter and invoke the method call defined in the interface

public invoke( Callable callable ) {
  callable.call( 5 );
}

<SELECT multiple> - how to allow only one item selected?

Why don't you want to remove the multiple attribute? The entire purpose of that attribute is to specify to the browser that multiple values may be selected from the given select element. If only a single value should be selected, remove the attribute and the browser will know to allow only a single selection.

Use the tools you have, that's what they're for.

How to clear out session on log out

session.abandon() will not remove the sessionID cookie from the browser. Therefore any new requests after this will take the same session ID. Hence, use Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); after session.abandon().

jQuery: How can I show an image popup onclick of the thumbnail?

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

Centering in CSS Grid

I know this question is a couple years old, but I am surprised to find that no one suggested:

   text-align: center;

this is a more universal property than justify-content, and is definitely not unique to grid, but I find that when dealing with text, which is what this question specifically asks about, that it aligns text to the center with-out affecting the space between grid items, or the vertical centering. It centers text horizontally where its stands on its vertical axis. I also find it to remove a layer of complexity that justify-content and align-items adds. justify-content and align-items affects the entire grid item or items, text-align centers the text without affecting the container it is in. Hope this helps.

How can I git stash a specific file?

EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>. For example:

git stash push -m welcome_cart app/views/cart/welcome.thtml

OLD ANSWER:

You can do that using git stash --patch (or git stash -p) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n to skip the files that you don't want to stash, y when you encounter the one that you want to stash, and q to quit and leave the remaining hunks unstashed. a will stash the shown hunk and the rest of the hunks in that file.

Not the most user-friendly approach, but it gets the work done if you really need it.

When to use @QueryParam vs @PathParam

You can use query parameters for filtering and path parameters for grouping. The following link has good info on this When to use pathParams or QueryParams

How to get Linux console window width in Python

I searched around and found a solution for windows at :

http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

and a solution for linux here.

So here is a version which works both on linux, os x and windows/cygwin :

""" getTerminalSize()
 - get width and height of console
 - works on linux,os x,windows,cygwin(windows)
"""

__all__=['getTerminalSize']


def getTerminalSize():
   import platform
   current_os = platform.system()
   tuple_xy=None
   if current_os == 'Windows':
       tuple_xy = _getTerminalSize_windows()
       if tuple_xy is None:
          tuple_xy = _getTerminalSize_tput()
          # needed for window's python in cygwin's xterm!
   if current_os == 'Linux' or current_os == 'Darwin' or  current_os.startswith('CYGWIN'):
       tuple_xy = _getTerminalSize_linux()
   if tuple_xy is None:
       print "default"
       tuple_xy = (80, 25)      # default value
   return tuple_xy

def _getTerminalSize_windows():
    res=None
    try:
        from ctypes import windll, create_string_buffer

        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12

        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
    except:
        return None
    if res:
        import struct
        (bufx, bufy, curx, cury, wattr,
         left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return sizex, sizey
    else:
        return None

def _getTerminalSize_tput():
    # get terminal width
    # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
    try:
       import subprocess
       proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       cols=int(output[0])
       proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       rows=int(output[0])
       return (cols,rows)
    except:
       return None


def _getTerminalSize_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0])

if __name__ == "__main__":
    sizex,sizey=getTerminalSize()
    print  'width =',sizex,'height =',sizey

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

How to get the correct range to set the value to a cell?

The following code does what is required

function doTest() {
  SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hello');
}

Where does R store packages?

Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.

  1. Go to where your R program is installed. This is referred to as R_Home in the literature. Once you find it, go to the /etc subdirectory.

    C:\R\R-2.10.1\etc
    
  2. Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:

    # my custom library path
    .libPaths("C:/R/library")
    

    (The comment added to keep track of what I did to the file.)

  3. In R, typing the .libPaths() function yields the first target at C:/R/Library

NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.

Overlapping Views in Android

The simples way arround is to put -40dp margin at the buttom of the top imageview

What is the default access modifier in Java?

Default access modifier is package-private - visible only from the same package

What is the correct way to start a mongod service on linux / OS X?

First Step

install mongodb in your linux machine with

apt install mongodb-client && apt install mongodb-server

second step is

change the database path instead of your system default path if you want.
so do the following steps and change it for yourself.

mongod --directoryperdb --dbpath /var/lib/mongodb/data/db --logpath /var/lib/mongodb/log/mongodb.log --logappend --rest

and in your windows machine do it just like that just put an --install flag. you have to get a successful message.

Best Regards...

Get file name from a file location in Java

Apache Commons IO provides the FilenameUtils class which gives you a pretty rich set of utility functions for easily obtaining the various components of filenames, although The java.io.File class provides the basics.

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like
  </div>
</a>

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

<div id="music" class="nav">Music I Like 
    <a href="http://www.google.com"> 
        <span class="hyperspan"></span>
    </a>   
</div>

http://jsfiddle.net/rBKXM/9

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

Python, how to read bytes from file and save it?

with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.

Make element fixed on scroll

I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.

window.addEventListener('scroll', function (evt) {

  // This value is your scroll distance from the top
  var distance_from_top = document.body.scrollTop;

  // The user has scrolled to the tippy top of the page. Set appropriate style.
  if (distance_from_top === 0) {

  }

  // The user has scrolled down the page.
  if(distance_from_top > 0) {

  }

});

JavaScript validation for empty input field

I would like to add required attribute in case user disabled javascript:

<input type="text" id="textbox" required/>

It works on all modern browsers.

How to set timeout on python's socket recv method?

Got a bit confused from the top answers so I've wrote a small gist with examples for better understanding.


Option #1 - socket.settimeout()

Will raise an exception in case the sock.recv() waits for more than the defined timeout.

import socket

sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.settimeout(timeout_seconds)
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = sock.recv(4096)
data = sock.recv(4096) # <- will raise a socket.timeout exception here

Option #2 - select.select()

Waits until data is sent until the timeout is reached. I've tweaked Daniel's answer so it will raise an exception

import select
import socket

def recv_timeout(sock, bytes_to_read, timeout_seconds):
    sock.setblocking(0)
    ready = select.select([sock], [], [], timeout_seconds)
    if ready[0]:
        return sock.recv(bytes_to_read)

    raise socket.timeout()

sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = recv_timeout(sock, 4096, timeout_seconds)
data = recv_timeout(sock, 4096, timeout_seconds) # <- will raise a socket.timeout exception here

Array Index Out of Bounds Exception (Java)

This is Very Good Example of minus Length of an array in java, i am giving here both examples

 public static int linearSearchArray(){

   int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
   int key = 7;
   int i = 0;
   int count = 0;
   for ( i = 0; i< arrayOFInt.length; i++){
        if ( arrayOFInt[i]  == key ){
         System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
         count ++;
        }
   }

   System.out.println("this Element found the ("+ count +") number of Times");
return i;  
}

this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.

Oracle - how to remove white spaces?

SQL Plus will format the columns to hold the maximum possible value, which in this case is 255 characters.

To confirm that your output does not actually contain those extra spaces, try this:

SELECT
  '/' || TRIM(A) || '/' AS COLUMN_A
 ,'/' || TRIM(B) || '/' AS COLUMN_B
FROM
  MY_TABLE;

If the '/' characters are separated from your output, then that indicates that it's not spaces, but some other whitespace character that got in there (tabs, for example). If that is the case, then it is probably an input validation issue somewhere in your application.

However, the most likely scenario is that the '/' characters will in fact touch the rest of your strings, thus proving that the whitespace is actually trimmed.

If you wish to output them together, then the answer given by Quassnoi should do it.

If it is purely a display issue, then the answer given by Tony Andrews should work fine.

How to get selected value of a dropdown menu in ReactJS

You can handle it all within the same function as following

_x000D_
_x000D_
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>_x000D_
_x000D_
  <option value="5">5 dollars</option>_x000D_
  <option value="10">10 dollars</option>_x000D_
                                         _x000D_
</select>
_x000D_
_x000D_
_x000D_

as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!

How to add line break for UILabel?

Just using label.numberOfLines = 0;

How do I search for names with apostrophe in SQL Server?

SELECT     *
FROM Header WHERE (userID LIKE '%''%')

What is the difference between jQuery: text() and html() ?

The different is .html() evaluate as a html, .text() avaluate as a text.
Consider a block of html
HTML

<div id="mydiv">
<div class="mydiv">
    This is a div container
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
    </ul>
    a text after ul
</div>
</div>

JS

var out1 = $('#mydiv').html();
var out2 = $('#mydiv').text();
console.log(out1) // This output all the html tag
console.log(out2) // This is output just the text 'This is a div container Link 1 Link 2 a text after ul'

The illustration is from this link http://api.jquery.com/text/

phpinfo() - is there an easy way for seeing it?

From the CLI:

php -r 'phpinfo();'

How can I scan barcodes on iOS?

I believe this can be done using AVFramework, here is the sample code to do this

import UIKit
import AVFoundation

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate
{

    @IBOutlet weak var lblQRCodeResult: UILabel!
    @IBOutlet weak var lblQRCodeLabel: UILabel!

    var objCaptureSession:AVCaptureSession?
    var objCaptureVideoPreviewLayer:AVCaptureVideoPreviewLayer?
    var vwQRCode:UIView?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.configureVideoCapture()
        self.addVideoPreviewLayer()
        self.initializeQRView()
    }

    func configureVideoCapture() {
        let objCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        var error:NSError?
        let objCaptureDeviceInput: AnyObject!
        do {
            objCaptureDeviceInput = try AVCaptureDeviceInput(device: objCaptureDevice) as AVCaptureDeviceInput

        } catch let error1 as NSError {
            error = error1
            objCaptureDeviceInput = nil
        }
        objCaptureSession = AVCaptureSession()
        objCaptureSession?.addInput(objCaptureDeviceInput as! AVCaptureInput)
        let objCaptureMetadataOutput = AVCaptureMetadataOutput()
        objCaptureSession?.addOutput(objCaptureMetadataOutput)
        objCaptureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        objCaptureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
    }

    func addVideoPreviewLayer() {
        objCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: objCaptureSession)
        objCaptureVideoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        objCaptureVideoPreviewLayer?.frame = view.layer.bounds
        self.view.layer.addSublayer(objCaptureVideoPreviewLayer!)
        objCaptureSession?.startRunning()
        self.view.bringSubviewToFront(lblQRCodeResult)
        self.view.bringSubviewToFront(lblQRCodeLabel)
    }

    func initializeQRView() {
        vwQRCode = UIView()
        vwQRCode?.layer.borderColor = UIColor.redColor().CGColor
        vwQRCode?.layer.borderWidth = 5
        self.view.addSubview(vwQRCode!)
        self.view.bringSubviewToFront(vwQRCode!)
    }

    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        if metadataObjects == nil || metadataObjects.count == 0 {
            vwQRCode?.frame = CGRectZero
            lblQRCodeResult.text = "QR Code wans't found"
            return
        }
        let objMetadataMachineReadableCodeObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
        if objMetadataMachineReadableCodeObject.type == AVMetadataObjectTypeQRCode {
            let objBarCode = objCaptureVideoPreviewLayer?.transformedMetadataObjectForMetadataObject(objMetadataMachineReadableCodeObject as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
            vwQRCode?.frame = objBarCode.bounds;
            if objMetadataMachineReadableCodeObject.stringValue != nil {
                lblQRCodeResult.text = objMetadataMachineReadableCodeObject.stringValue
            }
        }
    }
}

How to use SQL LIKE condition with multiple values in PostgreSQL?

You might be able to use IN, if you don't actually need wildcards.

SELECT * from table WHERE column IN ('AAA', 'BBB', 'CCC')

How to put two divs on the same line with CSS in simple_form in rails?

Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.

.left {
  float: left;
  width: 125px;
  text-align: right;
  margin: 2px 10px;
  display: inline;
}

.right {
  float: left;
  text-align: left;
  margin: 2px 10px;
  display: inline;
}

How to check if a column exists in a datatable

For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.

 private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
    {
        bool iscolumnExist = true;
        try
        {
            if (null != tableNameToCheck && tableNameToCheck.Columns != null)
            {
                foreach (string columnName in columnsNames)
                {
                    if (!tableNameToCheck.Columns.Contains(columnName))
                    {
                        iscolumnExist = false;
                        break;
                    }
                }
            }
            else
            {
                iscolumnExist = false;
            }
        }            
        catch (Exception ex)
        {

        }
        return iscolumnExist;
    }

Make selected block of text uppercase

Highlight the text you want to uppercase. Then hit CTRL+SHIFT+P to bring up the command palette. Then start typing the word "uppercase", and you'll see the Transform to Uppercase command. Click that and it will make your text uppercase.

Whenever you want to do something in VS Code and don't know how, it's a good idea to bring up the command palette with CTRL+SHIFT+P, and try typing in a keyword for you want. Oftentimes the command will show up there so you don't have to go searching the net for how to do something.

What does "publicPath" in Webpack do?

filename specifies the name of file into which all your bundled code is going to get accumulated after going through build step.

path specifies the output directory where the app.js(filename) is going to get saved in the disk. If there is no output directory, webpack is going to create that directory for you. for example:

module.exports = {
  output: {
    path: path.resolve("./examples/dist"),
    filename: "app.js"
  } 
}

This will create a directory myproject/examples/dist and under that directory it creates app.js, /myproject/examples/dist/app.js. After building, you can browse to myproject/examples/dist/app.js to see the bundled code

publicPath: "What should I put here?"

publicPath specifies the virtual directory in web server from where bundled file, app.js is going to get served up from. Keep in mind, the word server when using publicPath can be either webpack-dev-server or express server or other server that you can use with webpack.

for example

module.exports = {
  output: {
    path: path.resolve("./examples/dist"),
    filename: "app.js",
    publicPath: path.resolve("/public/assets/js")   
  } 
}

this configuration tells webpack to bundle all your js files into examples/dist/app.js and write into that file.

publicPath tells webpack-dev-server or express server to serve this bundled file ie examples/dist/app.js from specified virtual location in server ie /public/assets/js. So in your html file, you have to reference this file as

<script src="public/assets/js/app.js"></script>

So in summary, publicPath is like mapping between virtual directory in your server and output directory specified by output.path configuration, Whenever request for file public/assets/js/app.js comes, /examples/dist/app.js file will be served

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

ReferenceError: $ is not defined

i was facing the same problem in the wp-admin section of the site. I enqueued the underscore script cdn and it fixed the problem.

function kk_admin_scripts() {
    wp_enqueue_script('underscore', '//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js' );
}
add_action( 'admin_enqueue_scripts', 'kk_admin_scripts' );

What does -XX:MaxPermSize do?

In Java 8 that parameter is commonly used to print a warning message like this one:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size).

FYI: an article on Metaspace: http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html

Remove characters except digits from string using Python?

Ugly but works:

>>> s
'aaa12333bb445bb54b5b52'
>>> a = ''.join(filter(lambda x : x.isdigit(), s))
>>> a
'1233344554552'
>>>

Path of currently executing powershell script

In powershell 2.0

split-path $pwd

How to append to a file in Node?

My approach is rather special. I basically use the WriteStream solution but without actually 'closing' the fd by using stream.end(). Instead I use cork/uncork. This got the benefit of low RAM usage (if that matters to anyone) and I believe it's more safe to use for logging/recording (my original use case).

Following is a pretty simple example. Notice I just added a pseudo for loop for showcase -- in production code I am waiting for websocket messages.

var stream = fs.createWriteStream("log.txt", {flags:'a'});
for(true) {
  stream.cork();
  stream.write("some content to log");
  process.nextTick(() => stream.uncork());
}

uncork will flush the data to the file in the next tick.

In my scenario there are peaks of up to ~200 writes per second in various sizes. During night time however only a handful writes per minute are needed. The code is working super reliable even during peak times.

How do I get a YouTube video thumbnail from the YouTube API?

If you want the biggest image from YouTube for a specific video ID, then the URL should be something like this:

http://i3.ytimg.com/vi/SomeVideoIDHere/0.jpg

Using the API, you can pick up default thumbnail image. Simple code should be something like this:

//Grab the default thumbnail image
$attrs = $media->group->thumbnail[1]->attributes();
$thumbnail = $attrs['url'];
$thumbnail = substr($thumbnail, 0, -5);
$thumb1 = $thumbnail."default.jpg";

// Grab the third thumbnail image
$thumb2 = $thumbnail."2.jpg";

// Grab the fourth thumbnail image.
$thumb3 = $thumbnail."3.jpg";

// Using simple cURL to save it your server.
// You can extend the cURL below if you want it as fancy, just like
// the rest of the folks here.

$ch = curl_init ("$thumb1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata = curl_exec($ch);
curl_close($ch);

// Using fwrite to save the above
$fp = fopen("SomeLocationInReferenceToYourScript/AnyNameYouWant.jpg", 'w');

// Write the file
fwrite($fp, $rawdata);

// And then close it.
fclose($fp);

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

How do I encode and decode a base64 string?

You can display it like this:

var strOriginal = richTextBox1.Text;

byte[] byt = System.Text.Encoding.ASCII.GetBytes(strOriginal);

// convert the byte array to a Base64 string
string strModified = Convert.ToBase64String(byt);

richTextBox1.Text = "" + strModified;

Now, converting it back.

var base64EncodedBytes = System.Convert.FromBase64String(richTextBox1.Text);

richTextBox1.Text = "" + System.Text.Encoding.ASCII.GetString(base64EncodedBytes);
MessageBox.Show("Done Converting! (ASCII from base64)");

I hope this helps!

ld cannot find an existing library

Installing libgl1-mesa-dev from the Ubuntu repo resolved this problem for me.

How to call a function after a div is ready?

Through jQuery.ready function you can specify function that's executed when DOM is loaded. Whole DOM, not any div you want.

So, you should use ready in a bit different way

$.ready(function() {
    createGrid();
});

This is in case when you dont use AJAX to load your div

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

Styling input buttons for iPad and iPhone

I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css

p-button {
   -webkit-appearance: none !important;
}

i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)

button {
  -webkit-appearance: button;

}

Can Python test the membership of multiple values in a list?

This does what you want, and will work in nearly all cases:

>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
True

The expression 'a','b' in ['b', 'a', 'foo', 'bar'] doesn't work as expected because Python interprets it as a tuple:

>>> 'a', 'b'
('a', 'b')
>>> 'a', 5 + 2
('a', 7)
>>> 'a', 'x' in 'xerxes'
('a', True)

Other Options

There are other ways to execute this test, but they won't work for as many different kinds of inputs. As Kabie points out, you can solve this problem using sets...

>>> set(['a', 'b']).issubset(set(['a', 'b', 'foo', 'bar']))
True
>>> {'a', 'b'} <= {'a', 'b', 'foo', 'bar'}
True

...sometimes:

>>> {'a', ['b']} <= {'a', ['b'], 'foo', 'bar'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Sets can only be created with hashable elements. But the generator expression all(x in container for x in items) can handle almost any container type. The only requirement is that container be re-iterable (i.e. not a generator). items can be any iterable at all.

>>> container = [['b'], 'a', 'foo', 'bar']
>>> items = (i for i in ('a', ['b']))
>>> all(x in [['b'], 'a', 'foo', 'bar'] for x in items)
True

Speed Tests

In many cases, the subset test will be faster than all, but the difference isn't shocking -- except when the question is irrelevant because sets aren't an option. Converting lists to sets just for the purpose of a test like this won't always be worth the trouble. And converting generators to sets can sometimes be incredibly wasteful, slowing programs down by many orders of magnitude.

Here are a few benchmarks for illustration. The biggest difference comes when both container and items are relatively small. In that case, the subset approach is about an order of magnitude faster:

>>> smallset = set(range(10))
>>> smallsubset = set(range(5))
>>> %timeit smallset >= smallsubset
110 ns ± 0.702 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %timeit all(x in smallset for x in smallsubset)
951 ns ± 11.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

This looks like a big difference. But as long as container is a set, all is still perfectly usable at vastly larger scales:

>>> bigset = set(range(100000))
>>> bigsubset = set(range(50000))
>>> %timeit bigset >= bigsubset
1.14 ms ± 13.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit all(x in bigset for x in bigsubset)
5.96 ms ± 37 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Using subset testing is still faster, but only by about 5x at this scale. The speed boost is due to Python's fast c-backed implementation of set, but the fundamental algorithm is the same in both cases.

If your items are already stored in a list for other reasons, then you'll have to convert them to a set before using the subset test approach. Then the speedup drops to about 2.5x:

>>> %timeit bigset >= set(bigsubseq)
2.1 ms ± 49.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

And if your container is a sequence, and needs to be converted first, then the speedup is even smaller:

>>> %timeit set(bigseq) >= set(bigsubseq)
4.36 ms ± 31.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The only time we get disastrously slow results is when we leave container as a sequence:

>>> %timeit all(x in bigseq for x in bigsubseq)
184 ms ± 994 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

And of course, we'll only do that if we must. If all the items in bigseq are hashable, then we'll do this instead:

>>> %timeit bigset = set(bigseq); all(x in bigset for x in bigsubseq)
7.24 ms ± 78 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

That's just 1.66x faster than the alternative (set(bigseq) >= set(bigsubseq), timed above at 4.36).

So subset testing is generally faster, but not by an incredible margin. On the other hand, let's look at when all is faster. What if items is ten-million values long, and is likely to have values that aren't in container?

>>> %timeit hugeiter = (x * 10 for bss in [bigsubseq] * 2000 for x in bss); set(bigset) >= set(hugeiter)
13.1 s ± 167 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> %timeit hugeiter = (x * 10 for bss in [bigsubseq] * 2000 for x in bss); all(x in bigset for x in hugeiter)
2.33 ms ± 65.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Converting the generator into a set turns out to be incredibly wasteful in this case. The set constructor has to consume the entire generator. But the short-circuiting behavior of all ensures that only a small portion of the generator needs to be consumed, so it's faster than a subset test by four orders of magnitude.

This is an extreme example, admittedly. But as it shows, you can't assume that one approach or the other will be faster in all cases.

The Upshot

Most of the time, converting container to a set is worth it, at least if all its elements are hashable. That's because in for sets is O(1), while in for sequences is O(n).

On the other hand, using subset testing is probably only worth it sometimes. Definitely do it if your test items are already stored in a set. Otherwise, all is only a little slower, and doesn't require any additional storage. It can also be used with large generators of items, and sometimes provides a massive speedup in that case.

Getting char from string at specified index

char = split_string_to_char(text)(index)

------

Function split_string_to_char(text) As String()

   Dim chars() As String
   For char_count = 1 To Len(text)
      ReDim Preserve chars(char_count - 1)
      chars(char_count - 1) = Mid(text, char_count, 1)
   Next
   split_string_to_char = chars
End Function

ALTER TABLE, set null in not null column, PostgreSQL 9.1

ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html

Add new column with foreign key constraint in one command

In MS SQL SERVER:

With user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
CONSTRAINT fkName FOREIGN KEY(fkColumnName) 
   REFERENCES pkTableName(pkTableColumnName);

Without user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
FOREIGN KEY(fkColumnName) REFERENCES pkTableName(pkTableColumnName);

WPF ListView - detect when selected item is clicked

I couldn't get the accepted answer to work the way I wanted it to (see Farrukh's comment).

I came up with a slightly different solution which also feels more native because it selects the item on mouse button down and then you're able to react to it when the mouse button gets released:

XAML:

<ListView Name="MyListView" ItemsSource={Binding MyItems}>
<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        <EventSetter Event="PreviewMouseLeftButtonUp" Handler="ListViewItem_PreviewMouseLeftButtonUp" />
    </Style>
</ListView.ItemContainerStyle>

Code behind:

private void ListViewItem_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    MyListView.SelectedItems.Clear();

    ListViewItem item = sender as ListViewItem;
    if (item != null)
    {
        item.IsSelected = true;
        MyListView.SelectedItem = item;
    }
}

private void ListViewItem_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    ListViewItem item = sender as ListViewItem;
    if (item != null && item.IsSelected)
    {
        // do stuff
    }
}

How to get the selected row values of DevExpress XtraGrid?

Which one of their Grids are you using? XtraGrid or AspXGrid? Here is a piece taken from one of my app using XtraGrid.

private void grdContactsView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    _selectedContact = GetSelectedRow((DevExpress.XtraGrid.Views.Grid.GridView)sender);
}

private Contact GetSelectedRow(DevExpress.XtraGrid.Views.Grid.GridView view)
{
    return (Contact)view.GetRow(view.FocusedRowHandle);
}

My Grid have a list of Contact objects bound to it. Every time a row is clicked I load the selected row into _selectedContact. Hope this helps. You will find lots of information on using their controls buy visiting their support and documentation sites.

MySQL - How to select rows where value is in array?

If you use the FIND_IN_SET function:

FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others

AND

FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others

So if record1 is (a,b,c) and record2 is (a)

FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

Get cart item name, quantity all details woocommerce

you can get the product name like this

foreach ( $cart_object->cart_contents as  $value ) {
        $_product     = apply_filters( 'woocommerce_cart_item_product', $value['data'] );

        if ( ! $_product->is_visible() ) {
                echo $_product->get_title();
        } else {
                echo $_product->get_title();
        }


     }

How to remove docker completely from ubuntu 14.04

@miyuru. As suggested by him run all the steps.

Ubuntu version 16.04

Still when I ran docker --version it was returning a version. So to uninstall it completely

Again run the dpkg -l | grep -i docker which will list package still there in system.

For example:

ii  docker-ce-cli      5:19.03.6~3-0~ubuntu-xenial               
amd64        Docker CLI: the open-source application container engine

Now remove them as show below :

sudo apt-get purge -y docker-ce-cli

sudo apt-get autoremove -y --purge docker-ce-cli

sudo apt-get autoclean

Hope this will resolve it, as it did in my case.

CSS display:table-row does not expand when width is set to 100%

If you're using display:table-row etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:

<tr style="width:100%">
    <td>Type</td>
    <td style="float:right">Name</td>
</tr>

Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table, thead, tbody, etc.)

Instead, add an outer element with display:table, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats with table elements. It'll cause so many headaches.

markup:

<div class="view-table">
    <div class="view-row">
        <div class="view-type">Type</div>
        <div class="view-name">Name</div>                
    </div>
</div>

CSS:

.view-table
{
    display:table;
    width:100%;
}
.view-row,
{
    display:table-row;
}
.view-row > div
{
    display: table-cell;
}
.view-name 
{
    text-align:right;
}

How do I free my port 80 on localhost Windows?

Skype likes to use port 80 and blocks IIS. That was my prob.

Is it wrong to place the <script> tag after the </body> tag?

Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.

How to calculate UILabel width based on text length?

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

this question might have your answer, it worked for me.


For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers

// yourLabel is your UILabel.

float widthIs = 
 [self.yourLabel.text
  boundingRectWithSize:self.yourLabel.frame.size                                           
  options:NSStringDrawingUsesLineFragmentOrigin
  attributes:@{ NSFontAttributeName:self.yourLabel.font }
  context:nil]
   .size.width;

NSLog(@"the width of yourLabel is %f", widthIs);

C++ program converts fahrenheit to celsius

In C++, 5/9 computes the result as an integer as both the operands are integers. You need to give an hint to the compiler that you want the result as a float/double. You can do it by explictly casting one of the operands like ((double)5)/9;

EDIT Since it is tagged C++, you can do the casting bit more elegantly using the static_cast. For example: static_cast<double>(5)/9. Although in this particular case you can directly use 5.0/9 to get the desired result, the casting will be helpful when you have variables instead of constant values such as 5.

Bootstrap 4 Center Vertical and Horizontal Alignment

Bootstrap has text-center to center a text. For example

<div class="container text-center">

You change the following

<div class="row justify-content-center align-items-center">

to the following

<div class="row text-center">

react-native - Fit Image in containing View, not the whole screen size

Set the dimensions to the View and make sure your Image is styled with height and width set to 'undefined' like the example below :

    <View style={{width: 10, height:10 }} >
      <Image style= {{flex:1 , width: undefined, height: undefined}}    
       source={require('../yourfolder/yourimage')}
        />
    </View>

This will make sure your image scales and fits perfectly into your view.

Vue 2 - Mutating props vue-warn

Below is a snack bar component, when I give the snackbar variable directly into v-model like this if will work but in the console, it will give an error as

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.

<template>
        <v-snackbar v-model="snackbar">
        {{ text }}
      </v-snackbar>
</template>

<script>
    export default {
        name: "loader",

        props: {
            snackbar: {type: Boolean, required: true},
            text: {type: String, required: false, default: ""},
        },

    }
</script>

Correct Way to get rid of this mutation error is use watcher

<template>
        <v-snackbar v-model="snackbarData">
        {{ text }}
      </v-snackbar>
</template>

<script>
/* eslint-disable */ 
    export default {
        name: "loader",
         data: () => ({
          snackbarData:false,
        }),
        props: {
            snackbar: {type: Boolean, required: true},
            text: {type: String, required: false, default: ""},
        },
        watch: { 
        snackbar: function(newVal, oldVal) { 
          this.snackbarData=!this.snackbarDatanewVal;
        }
      }
    }
</script>

So in the main component where you will load this snack bar you can just do this code

 <loader :snackbar="snackbarFlag" :text="snackText"></loader>

This Worked for me

How to fix Invalid AES key length?

You can verify the key length limit:

int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("MaxAllowedKeyLength=[" + maxKeyLen + "].");

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
         \________________/
                 ||
             your result

SQLite - getting number of rows in a database

You can query the actual number of rows with

SELECT Count(*) FROM tblName
see https://www.w3schools.com/sql/sql_count_avg_sum.asp

How can I create a memory leak in Java?

One possibility is to create a wrapper for an ArrayList that only provides one method: one that adds things to the ArrayList. Make the ArrayList itself private. Now, construct one of these wrapper objects in global scope (as a static object in a class) and qualify it with the final keyword (e.g. public static final ArrayListWrapper wrapperClass = new ArrayListWrapper()). So now the reference cannot be altered. That is, wrapperClass = null won't work and can't be used to free the memory. But there's also no way to do anything with wrapperClass other than add objects to it. Therefore, any objects you do add to wrapperClass are impossible to recycle.

Is it possible to get an Excel document's row count without loading the entire document into memory?

This might be extremely convoluted and I might be missing the obvious, but without OpenPyXL filling in the column_dimensions in Iterable Worksheets (see my comment above), the only way I can see of finding the column size without loading everything is to parse the xml directly:

from xml.etree.ElementTree import iterparse
from openpyxl import load_workbook
wb=load_workbook("/path/to/workbook.xlsx", use_iterators=True)
ws=wb.worksheets[0]
xml = ws._xml_source
xml.seek(0)

for _,x in iterparse(xml):

    name= x.tag.split("}")[-1]
    if name=="col":
        print "Column %(max)s: Width: %(width)s"%x.attrib # width = x.attrib["width"]

    if name=="cols":
        print "break before reading the rest of the file"
        break

How to properly override clone method?

Use serialization to make deep copies. This is not the quickest solution but it does not depend on the type.

How to write lists inside a markdown table?

If you use the html approach:

don't add blank lines

Like this:

<table>
    <tbody>

        <tr>
            <td>1</td>
            <td>2</td>
        </tr>

        <tr>
            <td>1</td>
            <td>2</td>
        </tr>

    </tbody>
</table>

the markup will break.

Remove blank lines:

<table>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
    </tbody>
</table>

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

python -m pip install --user opencv-contrib-python

After doing this just Restart your system and then if you are on Opencv >= 4.* use :
recognizer = cv2.face.LBPHFaceRecognizer_create()

This should solve 90% of the problem.

How to set the 'selected option' of a select dropdown list with jquery

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

make: *** [ ] Error 1 error

From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.

‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.

So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.

Changing API level Android Studio

File>Project Structure>Modules you can change it from there

Python append() vs. + operator on lists, why do these give different results?

See the documentation:

list.append(x)

  • Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L) - Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

c.append(c) "appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.

c += c is equivalent to extend(c), which appends the elements of c to c.

convert ArrayList<MyCustomClass> to JSONArray

Add to your gradle:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Convert ArrayList to JsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);

Remove Fragment Page from ViewPager in Android

You can combine both for better :

private class MyPagerAdapter extends FragmentStatePagerAdapter {

    //... your existing code

    @Override
    public int getItemPosition(Object object){

      if(Any_Reason_You_WantTo_Update_Positions) //this includes deleting or adding pages
 return PagerAdapter.POSITION_NONE;
    }
else
return PagerAdapter.POSITION_UNCHANGED; //this ensures high performance in other operations such as editing list items.

}

reducing number of plot ticks

in case somebody still needs it, and since nothing here really worked for me, i came up with a very simple way that keeps the appearance of the generated plot "as is" while fixing the number of ticks to exactly N:

import numpy as np
import matplotlib.pyplot as plt

f, ax = plt.subplots()
ax.plot(range(100))

ymin, ymax = ax.get_ylim()
ax.set_yticks(np.round(np.linspace(ymin, ymax, N), 2))

Find unique rows in numpy.array

np.unique when I run it on np.random.random(100).reshape(10,10) returns all the unique individual elements, but you want the unique rows, so first you need to put them into tuples:

array = #your numpy array of lists
new_array = [tuple(row) for row in array]
uniques = np.unique(new_array)

That is the only way I see you changing the types to do what you want, and I am not sure if the list iteration to change to tuples is okay with your "not looping through"

Find the last element of an array while using a foreach loop in PHP

I kinda like the following as I feel it is fairly neat. Let's assume we're creating a string with separators between all the elements: e.g. a,b,c

$first = true;
foreach ( $items as $item ) {
    $str = ($first)?$first=false:", ".$item;
}

"sed" command in bash

Here sed is replacing all occurrences of % with $ in its standard input.

As an example

$ echo 'foo%bar%' | sed -e 's,%,$,g'

will produce "foo$bar$".

how to check and set max_allowed_packet mysql variable

max_allowed_packet is set in mysql config, not on php side

[mysqld]
max_allowed_packet=16M 

You can see it's curent value in mysql like this:

SHOW VARIABLES LIKE 'max_allowed_packet';

You can try to change it like this, but it's unlikely this will work on shared hosting:

SET GLOBAL max_allowed_packet=16777216;

You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html

EDIT

The [mysqld] is necessary to make the max_allowed_packet working since at least mysql version 5.5.

Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet. It you set the value under [mysqld_safe] (which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld] and restarted the mysqld, it worked.

How to restrict the selectable date ranges in Bootstrap Datepicker?

Most answers and explanations are not to explain what is a valid string of endDate or startDate. Danny gave us two useful example.

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

But why?let's take a look at the source code at bootstrap-datetimepicker.js. There are some code begin line 1343 tell us how does it work.

if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
            var part_re = /([-+]\d+)([dmwy])/,
                parts = date.match(/([-+]\d+)([dmwy])/g),
                part, dir;
            date = new Date();
            for (var i = 0; i < parts.length; i++) {
                part = part_re.exec(parts[i]);
                dir = parseInt(part[1]);
                switch (part[2]) {
                    case 'd':
                        date.setUTCDate(date.getUTCDate() + dir);
                        break;
                    case 'm':
                        date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
                        break;
                    case 'w':
                        date.setUTCDate(date.getUTCDate() + dir * 7);
                        break;
                    case 'y':
                        date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
                        break;
                }
            }
            return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
        }

There are four kinds of expressions.

  • w means week
  • m means month
  • y means year
  • d means day

Look at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$. You can do more than these -0d or +1m.

Try harder like startDate:'+1y,-2m,+0d,-1w'.And the separator , could be one of [\f\n\r\t\v,]

typecast string to integer - Postgres

you can use this query

SUM(NULLIF(conversion_units, '')::numeric)

Android LinearLayout : Add border with shadow around a LinearLayout

That's why CardView exists. CardView | Android Developers
It's just a FrameLayout that supports elevation in pre-lollipop devices.

<android.support.v7.widget.CardView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:cardUseCompatPadding="true"
    app:cardElevation="4dp"
    app:cardCornerRadius="3dp" >

    <!-- put whatever you want -->

</android.support.v7.widget.CardView>

To use this you need to add dependency to build.gradle:

compile 'com.android.support:cardview-v7:23.+'

How to change the decimal separator of DecimalFormat from comma to dot/point?

BigDecimal does not seem to respect Locale settings.

Locale.getDefault(); //returns sl_SI

Slovenian locale should have a decimal comma. Guess I had strange misconceptions regarding numbers.

a = new BigDecimal("1,2") //throws exception
a = new BigDecimal("1.2") //is ok

a.toPlainString() // returns "1.2" always

I have edited a part of my message that made no sense since it proved to be due the human error (forgot to commit data and was looking at the wrong thing).

Same as BigDecimal can be said for any Java .toString() functions. I guess that is good in some ways. Serialization for example or debugging. There is an unique string representation.

Also as others mentioned using formatters works OK. Just use formatters, same for the JSF frontend, formatters do the job properly and are aware of the locale.

uncaught syntaxerror unexpected token U JSON

That error is normally seen when the value given to JSON.parse is actually undefined. So, I would check the code that is trying to parse this - most likely you are not parsing the actual string shown here.

How to unload a package without restarting R

Just go to OUTPUT window, then click on Packages icon (it is located between Plot and Help icons). Remove "tick / check mark" from the package you wanted be unload.

For again using the package just put a "tick or Check mark" in front of package or use :

library (lme4)

How do I make a newline after a twitter bootstrap element?

Like KingCronus mentioned in the comments you can use the row class to make the list or heading on its own line. You could use the row class on either or both elements:

<ul class="nav nav-tabs span2 row">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>

<div class="well span6 row">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>

ReferenceError: document is not defined (in plain JavaScript)

Try adding the script element just before the /body tag like that

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>

Why would one mark local variables and method parameters as "final" in Java?

final has three good reasons:

  • instance variables set by constructor only become immutable
  • methods not to be overridden become final, use this with real reasons, not by default
  • local variables or parameters to be used in anonimous classes inside a method need to be final

Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.

C# Collection was modified; enumeration operation may not execute

As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:

foreach (KeyValuePair<int, int> kvp in rankings)
{
    .....

    if((double)(similarModules/modules.Count)>0.6)
    {
        rankings[kvp.Key] = rankings[kvp.Key] + 4;  // <--- This line is the problem
    }
    .....

What may not be obvious from the code above is where the Enumerator comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach loop gets expanded to by the compiler. The generated code will look something like:

{
    IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
                                                       // is where the Enumerator
                                                       // comes from.
    try
    { 
        int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
        while(e.MoveNext())
        {
            // loop code goes here
        }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
}

If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator() returns) you will see:

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.

ScalaTest in sbt: is there a way to run a single test without tags?

I don't see a way to run a single untagged test within a test class but I am providing my workflow since it seems to be useful for anyone who runs into this question.

From within a sbt session:

test:testOnly *YourTestClass

(The asterisk is a wildcard, you could specify the full path com.example.specs.YourTestClass.)

All tests within that test class will be executed. Presumably you're most concerned with failing tests, so correct any failing implementations and then run:

test:testQuick

... which will only execute tests that failed. (Repeating the most recently executed test:testOnly command will be the same as test:testQuick in this case, but if you break up your test methods into appropriate test classes you can use a wildcard to make test:testQuick a more efficient way to re-run failing tests.)

Note that the nomenclature for test in ScalaTest is a test class, not a specific test method, so all untagged methods are executed.

If you have too many test methods in a test class break them up into separate classes or tag them appropriately. (This could be a signal that the class under test is in violation of single responsibility principle and could use a refactoring.)

How to create a function in SQL Server

You can use stuff in place of replace for avoiding the bug that Hamlet Hakobyan has mentioned

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250)) 
RETURNS VARCHAR(250) 
AS BEGIN
   DECLARE @Work VARCHAR(250)
   SET @Work = @Input

   --SET @Work = REPLACE(@Work, 'www.', '')
   SET @Work = Stuff(@Work,1,4, '')
   SET @Work = REPLACE(@Work, '.com', '')

   RETURN @work 
END

Event handlers for Twitter Bootstrap dropdowns?

In Bootstrap 3 'dropdown.js' provides us with the various events that are triggered.

click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown

etc

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

How can I get the console logs from the iOS Simulator?

iOS Simulator > Menu Bar > Debug > Open System Log


Old ways:

iOS Simulator prints its logs directly to stdout, so you can see the logs mixed up with system logs.

Open the Terminal and type: tail -f /var/log/system.log

Then run the simulator.

EDIT:

This stopped working on Mavericks/Xcode 5. Now you can access the simulator logs in its own folder: ~/Library/Logs/iOS Simulator/<sim-version>/system.log

You can either use the Console.app to see this, or just do a tail (iOS 7.0.3 64 bits for example):

tail -f ~/Library/Logs/iOS\ Simulator/7.0.3-64/system.log

EDIT 2:

They are now located in ~/Library/Logs/CoreSimulator/<simulator-hash>/system.log

tail -f ~/Library/Logs/CoreSimulator/<simulator-hash>/system.log

"Could not find or load main class" Error while running java program using cmd prompt

I removed bin from the CLASSPATH. I found out that I was executing the java command from the directory where the HelloWorld.java is located, i.e.:

C:\Users\xyz\Documents\Java\javastudy\src\org\tij\exercises>java HelloWorld

So I moved back to the main directory and executed:

java org.tij.exercises.HelloWorld

and it worked, i.e.:

C:\Users\xyz\Documents\Java\javastudy\src>java org.tij.exercises.HelloWorld

Hello World!!

How can I do GUI programming in C?

C is more of a hardware programming language, there are easy GUI builders for C, GTK, Glade, etc. The problem is making a program in C that is the easy part, making a GUI that is a easy part, the hard part is to combine both, to interface between your program and the GUI is a headache, and different GUI use different ways, some threw global variables, some use slots. It would be nice to have a GUI builder that would bind easily your C program variables, and outputs. CLI programming is easy when you overcome memory allocation and pointers, GUI you can use a IDE that uses drag and drop. But all around I think it could be simpler.

Circular (or cyclic) imports in Python

There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.

Imports are pretty straightforward really. Just remember the following:

'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.

Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.

Take that lot together and you shouldn't get any surprises when importing modules.

Python iterating through object attributes

You can use the standard Python idiom, vars():

for attr, value in vars(k).items():
    print(attr, '=', value)

How to use a filter in a controller?

Simple date example using $filter in a controller would be:

var myDate = new Date();
$scope.dateAsString = $filter('date')(myDate, "yyyy-MM-dd"); 

As explained here - https://stackoverflow.com/a/20131782/262140

What type of hash does WordPress use?

Start phpMyAdmin and access wp_users from your wordpress instance. Edit record and select user_pass function to match MD5. Write the string that will be your new password in VALUE. Click, GO. Go to your wordpress website and enter your new password. Back to phpMyAdmin you will see that WP changed the HASH to something like $P$B... enjoy!

Localhost : 404 not found

I had the same problem and here is how it worked for me :

1) Open XAMPP control panel.

2)On the right top corner go to config > Service and Port setting and change the port (I did 81 from 80).

3)Open config in Apache just right(next) to Apache admin Option and click on that and select first one (httpd.conf) it will open in the notepad.

4) There you find port listen 80 and replace it with 81 in all place and save the file.

5) Now restart Apache and MYSql

6) Now type following in Browser : http://localhost:81/phpmyadmin/

I hope this works.

Countdown timer in React

The one downside with setInterval is that it can slow down the main thread. You can do a countdown timer using requestAnimationFrame instead to prevent this. For example, this is my generic countdown timer component:

class Timer extends Component {
  constructor(props) {
    super(props)
    // here, getTimeRemaining is a helper function that returns an 
    // object with { total, seconds, minutes, hours, days }
    this.state = { timeLeft: getTimeRemaining(props.expiresAt) }
  }

  // Wait until the component has mounted to start the animation frame
  componentDidMount() {
    this.start()
  }

  // Clean up by cancelling any animation frame previously scheduled
  componentWillUnmount() {
    this.stop()
  }

  start = () => {
    this.frameId = requestAnimationFrame(this.tick)
  }

  tick = () => {
    const timeLeft = getTimeRemaining(this.props.expiresAt)
    if (timeLeft.total <= 0) {
      this.stop()
      // ...any other actions to do on expiration
    } else {
      this.setState(
        { timeLeft },
        () => this.frameId = requestAnimationFrame(this.tick)
      )
    }
  }

  stop = () => {
    cancelAnimationFrame(this.frameId)
  }

  render() {...}
}

Get month name from date in Oracle

to_char(mydate, 'MONTH') will do the job.

How do function pointers in C work?

Starting from scratch function has Some Memory Address From Where They start executing. In Assembly Language They Are called as (call "function's memory address").Now come back to C If function has a memory address then they can be manipulated by Pointers in C.So By the rules of C

1.First you need to declare a pointer to function 2.Pass the Address of the Desired function

****Note->the functions should be of same type****

This Simple Programme will Illustrate Every Thing.

#include<stdio.h>
void (*print)() ;//Declare a  Function Pointers
void sayhello();//Declare The Function Whose Address is to be passed
                //The Functions should Be of Same Type
int main()
{
 print=sayhello;//Addressof sayhello is assigned to print
 print();//print Does A call To The Function 
 return 0;
}

void sayhello()
{
 printf("\n Hello World");
}

enter image description hereAfter That lets See How machine Understands Them.Glimpse of machine instruction of the above programme in 32 bit architecture.

The red mark area is showing how the address is being exchanged and storing in eax. Then their is a call instruction on eax. eax contains the desired address of the function.

Bootstrap 3: Text overlay on image

You need to set the thumbnail class to position relative then the post-content to absolute.

Check this fiddle

.post-content {
    top:0;
    left:0;
    position: absolute;
}

.thumbnail{
    position:relative;

}

Giving it top and left 0 will make it appear in the top left corner.

How can I scale an image in a CSS sprite

try using background size: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm

is there something stopping you from rendering the images at the size you want them in the first place?

Mipmap drawables for icons

If you build an APK for a target screen resolution like HDPI, the Android asset packageing tool,AAPT,can strip out the drawables for other resolution you don’t need.But if it’s in the mipmap folder,then these assets will stay in the APK, regardless of the target resolution.

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

How can I multiply all items in a list together with Python?

Starting Python 3.8, a .prod function has been included to the math module in the standard library:

math.prod(iterable, *, start=1)

The method returns the product of a start value (default: 1) times an iterable of numbers:

import math
math.prod([1, 2, 3, 4, 5, 6])

>>> 720

If the iterable is empty, this will produce 1 (or the start value, if provided).

Difference between git stash pop and git stash apply

git stash pop throws away the (topmost, by default) stash after applying it, whereas git stash apply leaves it in the stash list for possible later reuse (or you can then git stash drop it).

This happens unless there are conflicts after git stash pop, in which case it will not remove the stash, leaving it to behave exactly like git stash apply.

Another way to look at it: git stash pop is git stash apply && git stash drop.

How do I comment on the Windows command line?

: this is one way to comment

As a result:

:: this will also work
:; so will this
:! and this

Above styles work outside codeblocks, otherwise:

REM is another way to comment.

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Delete certain lines in a txt file via a batch file

You can accomplish the same solution as @paxdiablo's using just findstr by itself. There's no need to pipe multiple commands together:

findstr /V "ERROR REFERENCE" infile.txt > outfile.txt

Details of how this works:

  • /v finds lines that don't match the search string (same switch @paxdiablo uses)
  • if the search string is in quotes, it performs an OR search, using each word (separator is a space)
  • findstr can take an input file, you don't need to feed it the text using the "type" command
  • "> outfile.txt" will send the results to the file outfile.txt instead printing them to your console. (Note that it will overwrite the file if it exists. Use ">> outfile.txt" instead if you want to append.)
  • You might also consider adding the /i switch to do a case-insensitive match.

Programmatically switching between tabs within Swift

1.Create a new class which supers UITabBarController. E.g:

class xxx: UITabBarController {
override func viewDidLoad() {
        super.viewDidLoad()
}

2.Add the following code to the function viewDidLoad():

self.selectedIndex = 1; //set the tab index you want to show here, start from 0

3.Go to storyboard, and set the Custom Class of your Tab Bar Controller to this new class. (MyVotes1 as the example in the pic)

enter image description here

How to wrap async function calls into a sync function in Node.js or Javascript?

I struggled with this at first with node.js and async.js is the best library I have found to help you deal with this. If you want to write synchronous code with node, approach is this way.

var async = require('async');

console.log('in main');

doABunchOfThings(function() {
  console.log('back in main');
});

function doABunchOfThings(fnCallback) {
  async.series([
    function(callback) {
      console.log('step 1');
      callback();
    },
    function(callback) {
      setTimeout(callback, 1000);
    },
    function(callback) {
      console.log('step 2');
      callback();
    },
    function(callback) {
      setTimeout(callback, 2000);
    },
    function(callback) {
      console.log('step 3');
      callback();
    },
  ], function(err, results) {
    console.log('done with things');
    fnCallback();
  });
}

this program will ALWAYS produce the following...

in main
step 1
step 2
step 3
done with things
back in main

What exactly is a Maven Snapshot and why do we need it?

I'd like to make a point about terminology. The other answers gave good explanations about what a "snapshot" version is in the context of Maven. But does it follow that a non-snapshot version should be termed a "release" version?

There is some tension between the semantic versioning idea of a "release" version, which would seem to be any version that does not have a qualifier such as -SNAPSHOT but also does not have a qualifier such as -beta.4; and Maven's idea idea of a "release" version, which only seems to include the absence of -SNAPSHOT.

In other words, there is a semantic ambiguity of whether "release" means "we can release it to Maven Central" or "the software is in its final release to the public". We could consider -beta.4 to be a "release" version if we release it to the public, but it's not a "final release". Semantic versioning clearly says that something like -beta.4 is a "pre-release" version, so it wouldn't make sense for it to be called a "release" version, even without -SNAPSHOT. In fact by definition even -rc.5 is a release candidate, not an actual release, even though we may allow public access for testing.

So Maven notwithstanding, in my opinion it seems more appropriate only to call a "release" version one that doesn't have any qualifier at all, not even -beta.4. Perhaps a better name for a Maven non-snapshot version would be a "stable" version (inspired by another answer). Thus we would have:

  • 1.2.3-beta.4-SNAPSHOT: A snapshot version of a pre-release version.
  • 1.2.3-SNAPSHOT: A snapshot version of a release version.
  • 1.2.3-beta.4: A stable version of a pre-release version.
  • 1.2.3: A release version (which is a stable, non-snapshot version, obviously).

Initialising an array of fixed size in python

One thing I find easy to do is i set an array of empty strings for the size I prefer, for example

Code:

import numpy as np

x= np.zeros(5,str)
print x

Output:

['' '' '' '' '']

Hope this is helpful :)

Substring in excel

In Excel, the substring function is called MID function, and indexOf is called FIND for case-sensitive location and SEARCH function for non-case-sensitive location. For the first portion of your text parsing the LEFT function may also be useful.

See all the text functions here: Text Functions (reference).

Full worksheet function reference lists available at:

    Excel functions (by category)
    Excel functions (alphabetical)

MySQL convert date string to Unix timestamp

You will certainly have to use both STR_TO_DATE to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP to get the timestamp from it.

Given the format of your date, something like

UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))

Will gives you a valid timestamp. Look the STR_TO_DATE documentation to have more information on the format string.

How do I move a redis database from one server to another?

I just published a command line interface utility to npm and github that allows you to copy keys that match a given pattern (even *) from one Redis database to another.

You can find the utility here:

https://www.npmjs.com/package/redis-utils-cli

DELETE ... FROM ... WHERE ... IN

You can achieve this using exists:

DELETE
  FROM table1
 WHERE exists(
           SELECT 1
             FROM table2
            WHERE table2.stn = table1.stn
              and table2.jaar = year(table1.datum)
       )

NoClassDefFoundError in Java: com/google/common/base/Function

you don't have the "google-collections" library on your classpath.

There are a number of ways to add libraries to your classpath, so please provide more info regarding how you are executing your program.

if from the command line, you can add libraries to the classpath via

java -classpath path/lib.jar ...

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

Error: Argument is not a function, got undefined

Remove the [] from the name ([myApp]) of module

angular.module('myApp', [])

And add ng-app="myApp" to the html and it should work.

ScrollIntoView() causing the whole page to move

I had this problem too, and spent many hours trying to deal with it. I hope my resolution may still help some people.

My fix ended up being:

  • For Chrome: changing .scrollIntoView() to .scrollIntoView({block: 'nearest'}) (thanks to @jfrohn).
  • For Firefox: apply overflow: -moz-hidden-unscrollable; on the container element that shifts.
  • Not tested in other browsers.

How do I count the number of occurrences of a char in a String?

Here is a slightly different style recursion solution:

public static int countOccurrences(String haystack, char needle)
{
    return countOccurrences(haystack, needle, 0);
}

private static int countOccurrences(String haystack, char needle, int accumulator)
{
    if (haystack.length() == 0) return accumulator;
    return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);
}

How to make URL/Phone-clickable UILabel?

Swift 4.2, Xcode 9.3 version

class LinkedLabel: UILabel {

    fileprivate let layoutManager = NSLayoutManager()
    fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
    fileprivate var textStorage: NSTextStorage?


    override init(frame aRect:CGRect){
        super.init(frame: aRect)
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.initialize()
    }

    func initialize(){

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTapOnLabel))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tap)
    }

    override var attributedText: NSAttributedString?{
        didSet{
            if let _attributedText = attributedText{
                self.textStorage = NSTextStorage(attributedString: _attributedText)

                self.layoutManager.addTextContainer(self.textContainer)
                self.textStorage?.addLayoutManager(self.layoutManager)

                self.textContainer.lineFragmentPadding = 0.0;
                self.textContainer.lineBreakMode = self.lineBreakMode;
                self.textContainer.maximumNumberOfLines = self.numberOfLines;
            }

        }
    }

    @objc func handleTapOnLabel(tapGesture:UITapGestureRecognizer){

        let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
        let labelSize = tapGesture.view?.bounds.size
        let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
        let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
        let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)


        self.attributedText?.enumerateAttribute(NSAttributedStringKey.link, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
            (attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in

            if NSLocationInRange(indexOfCharacter, range){
                if let _attrs = attrs{

                    UIApplication.shared.openURL(URL(string: _attrs as! String)!)
                }
            }
        })

    }}

When are static variables initialized?

From See Java Static Variable Methods:

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object.

Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.

What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.

In case of inner classes, they can not have static fields

An inner class is a nested class that is not explicitly or implicitly declared static.

...

Inner classes may not declare static initializers (§8.7) or member interfaces...

Inner classes may not declare static members, unless they are constant variables...

See JLS 8.1.3 Inner Classes and Enclosing Instances

final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.

final class Demo
{
    private final int x;
    private static final int z;  //must be initialized here.

    static 
    {
        z = 10;  //It can be initialized here.
    }

    public Demo(int x)
    {
        this.x=x;  //This is possible.
        //z=15; compiler-error - can not assign a value to a final variable z
    }
}

This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.

How to hide columns in HTML table?

You can also do what vs dev suggests programmatically by assigning the style with Javascript by iterating through the columns and setting the td element at a specific index to have that style.

Importing a csv into mysql via command line

try this:

mysql -uusername -ppassword --local-infile scrapping -e "LOAD DATA LOCAL INFILE 'CSVname.csv'  INTO TABLE table_name  FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"

Convert PEM to PPK file format

PuTTYgen for Ubuntu/Linux and PEM to PPK

sudo apt install putty-tools
puttygen -t rsa -b 2048 -C "user@host" -o keyfile.ppk

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

My appologies. The syntax was off due to me being in a hurry and sloppy. Here you go...

     $('#tester').live("keyup", function (evt)
        {
            var txt = $(this).val();
            txt = txt.substring(0, 1).toUpperCase() + txt.substring(1);
            $(this).val(txt);
        });

Simple but works. You would def want to make this more general and plug and playable. This is just to offer another idea, with less code. My philosophy with coding, is making it as general as possible, and with as less code as possible.

Hope this helps. Happy coding! :)

How does String substring work in Swift

Swift 5
let desiredIndex: Int = 7 let substring = str[String.Index(encodedOffset: desiredIndex)...]
This substring variable will give you the result.
Simply here Int is converted to Index and then you can split the strings. Unless you will get errors.

Could not load file or assembly for Oracle.DataAccess in .NET

I'm going to give you the answers from what I've just went through on Windows Server 2008 R2 which is a 64 bit operating system. The application suite of libraries I was given were developed using .net 3.5 x86 with the older DLL libraries and I was stuck because I had installed the newer x64 clients from oracle.

What I found was the following: Install the latest x64 client from Oracle for Windows Server 2008. I believe this would be the 2.7.0 client. When you select the installation, make sure you do custom and select the .NET libraries. Configure your tnsnames files and test your tnsping against your data source.

Next, if you are running a 32 bit application, install the same version of the client for 32 bit. Also, follow the same installation routine, and select the same home.

When your finished, you will find that you have a single app/product with two client directories (Client1 and Client2).

If you navigate to the windows/assemblies directory you will find that you have a reference to the Oracle.DataAccess.dll (x2) with one for x86 and one for AMD64.

Now, depending on if you have developers or are developing on the machine yourself, you may be ok here, however, if they are using older drivers, then you need to perform one last step.

Navigate to the app\name\product\version\client_1\odp.net\publisher policy\2.x directory. Included in here are two policy files. use gacutil /i to install the Policy.2.111.Oracle.DataAccess.dll into the GAC. This will redirect legacy oracle ODP calls to the newer versions. So, if someone developed with the 10g client, it will now work with the 11 client.

FYI -- Some may be installing the latest ODP.NET with the 2.111.7.20. The main oracle client itself comes with 2.111.7.0 .. I've not had any success with the 7.20 but have no issues with the 7.0 client.

jQuery: Check if button is clicked

$('input[type="button"]').click(function (e) {
    if (e.target) {
        alert(e.target.id + ' clicked');
    }
});

you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.

What does HTTP/1.1 302 mean exactly?

For anyone who might be curious about the naming, I'm just going to add that it's probably called "Found" because the main resource(e.g., a private web page) the user intends to receive is not available at that moment(e.g., the user has not proved their identity yet), so instead the server has found a new resource that the user can receive(which is a login page in the most common use case).

Also it's "getting lost and found" in the hide-and-seek manner, meaning a lost resource under a 302 status is only lost temporarily, it is not supposed to be lost forever(unless a player has some bad intentions;)).

How to close the command line window after running a batch file?

Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.

 tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
 exit 0

VC++ fatal error LNK1168: cannot open filename.exe for writing

This can also be a problem from the improper use of functions like FindNextFile when a FindClose is never executed. The process of the built file is terminated, and the build itself can be deleted, but LNK1168 will prevent a rebuild because of the open handle. This can create a handle leak in Explorer which can be addressed by terminating and restarting Explorer, but in many cases an immediate reboot is necessary.

CSS: How to align vertically a "label" and "input" inside a "div"?

I'm aware this question was asked over two years ago, but for any recent viewers, here's an alternative solution, which has a few advantages over Marc-François's solution:

div {
    height: 50px;
    border: 1px solid blue;
    line-height: 50px;
}

Here we simply only add a line-height equal to that of the height of the div. The advantage being you can now change the display property of the div as you see fit, to inline-block for instance, and it's contents will remain vertically centered. The accepted solution requires you treat the div as a table cell. This should work perfectly, cross-browser.

The only other advantage being it's just one more CSS rule instead of two :)

Cheers!

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

Session state can only be used when enableSessionState is set to true either in a configuration

Session State may be broken if you have the following in Web.Config:

<httpModules>
  <clear/>
</httpModules>

If this is the case, you may want to comment out such section, and you won't need any other changes to fix this issue.

How to write connection string in web.config file and read from it?

Try this After open web.config file in application and add sample db connection in connectionStrings section like this

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >

How do I find the maximum of 2 numbers?

max(value,run)

should do it.

How to use JNDI DataSource provided by Tomcat in Spring?

If using Spring's XML schema based configuration, setup in the Spring context like this:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
...
<jee:jndi-lookup id="dbDataSource"
   jndi-name="jdbc/DatabaseName"
   expected-type="javax.sql.DataSource" />

Alternatively, setup using simple bean configuration like this:

<bean id="DatabaseName" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/DatabaseName"/>
</bean>

You can declare the JNDI resource in tomcat's server.xml using something like this:

<GlobalNamingResources>
    <Resource name="jdbc/DatabaseName"
              auth="Container"
              type="javax.sql.DataSource"
              username="dbUser"
              password="dbPassword"
              url="jdbc:postgresql://localhost/dbname"
              driverClassName="org.postgresql.Driver"
              initialSize="20"
              maxWaitMillis="15000"
              maxTotal="75"
              maxIdle="20"
              maxAge="7200000"
              testOnBorrow="true"
              validationQuery="select 1"
              />
</GlobalNamingResources>

And reference the JNDI resource from Tomcat's web context.xml like this:

  <ResourceLink name="jdbc/DatabaseName"
   global="jdbc/DatabaseName"
   type="javax.sql.DataSource"/>

Reference documentation:

Edit: This answer has been updated for Tomcat 8 and Spring 4. There have been a few property name changes for Tomcat's default datasource resource pool setup.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

ES6 export default with multiple functions referring to each other

The export default {...} construction is just a shortcut for something like this:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { foo(); bar() }
}

export default funcs

It must become obvious now that there are no foo, bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export.

So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { funcs.foo(); funcs.bar() } // here is the fix
}

export default funcs

Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out.

Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:

function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }

export default {foo, bar, baz}

And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:

// util.js

export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }

export default {foo, bar, baz}

// a.js, using default export

import util from './util'
util.foo()

// b.js, using named exports

import {bar} from './util'
bar()

Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.

Viewing contents of a .jar file

Jad is klunky and no longer maintained. I've switched to "Java Decompiler", which has a slick UI and support for new language features.

Every decompiler I've used, though, runs into code it doesn't successfully decompile. For those, it helps to understand the disassembled Java byte code produced by the standard JDK tool, javap.

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

Difference in make_shared and normal shared_ptr in C++

I see one problem with std::make_shared, it doesn't support private/protected constructors

Event listener for when element becomes visible?

I had this same problem and created a jQuery plugin to solve it for our site.

https://github.com/shaunbowe/jquery.visibilityChanged

Here is how you would use it based on your example:

$('#contentDiv').visibilityChanged(function(element, visible) {
    alert("do something");
});

Why is PHP session_destroy() not working?

It works , but sometimes it doesn't (check the below example)

<?php
session_start();
$_SESSION['name']="shankar";
if(isset($_SESSION['name']))
{
    echo $_SESSION['name']; // Outputs shankar
}
session_destroy();
echo $_SESSION['name']; // Still outputs shankar

Weird!! Right ?


How to overcome this ?

In the above scenario , if you replace session_destroy(); with unset($_SESSION['name']); it works as expected.

But i want to destroy all variables not just a single one !

Yeah there is a fix for this too. Just unset the $_SESSION array. [Credits Ivo Pereira]

unset($_SESSION);

SET versus SELECT when assigning variables?

Aside from the one being ANSI and speed etc., there is a very important difference that always matters to me; more than ANSI and speed. The number of bugs I have fixed due to this important overlook is large. I look for this during code reviews all the time.

-- Arrange
create table Employee (EmployeeId int);
insert into dbo.Employee values (1);
insert into dbo.Employee values (2);
insert into dbo.Employee values (3);

-- Act
declare @employeeId int;
select @employeeId = e.EmployeeId from dbo.Employee e;

-- Assert
-- This will print 3, the last EmployeeId from the query (an arbitrary value)
-- Almost always, this is not what the developer was intending. 
print @employeeId; 

Almost always, that is not what the developer is intending. In the above, the query is straight forward but I have seen queries that are quite complex and figuring out whether it will return a single value or not, is not trivial. The query is often more complex than this and by chance it has been returning single value. During developer testing all is fine. But this is like a ticking bomb and will cause issues when the query returns multiple results. Why? Because it will simply assign the last value to the variable.

Now let's try the same thing with SET:

 -- Act
 set @employeeId = (select e.EmployeeId from dbo.Employee e);

You will receive an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

That is amazing and very important because why would you want to assign some trivial "last item in result" to the @employeeId. With select you will never get any error and you will spend minutes, hours debugging.

Perhaps, you are looking for a single Id and SET will force you to fix your query. Thus you may do something like:

-- Act
-- Notice the where clause
set @employeeId = (select e.EmployeeId from dbo.Employee e where e.EmployeeId = 1);
print @employeeId;

Cleanup

drop table Employee;

In conclusion, use:

  • SET: When you want to assign a single value to a variable and your variable is for a single value.
  • SELECT: When you want to assign multiple values to a variable. The variable may be a table, temp table or table variable etc.

What is the purpose of willSet and didSet in Swift?

NOTE

willSet and didSet observers are not called when a property is set in an initializer before delegation takes place

How to get Current Directory?

WCHAR path[MAX_PATH] = {0};
GetModuleFileName(NULL, path, MAX_PATH);
PathRemoveFileSpec(path);

How to programmatically tell if a Bluetooth device is connected?

There is an isConnected function in BluetoothDevice system API in https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java

If you want to know if the a bounded(paired) device is currently connected or not, the following function works fine for me:

public static boolean isConnected(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("isConnected", (Class[]) null);
        boolean connected = (boolean) m.invoke(device, (Object[]) null);
        return connected;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

html <input type="text" /> onchange event not working

Firstly, what 'doesn't work'? Do you not see the alert?

Also, Your code could be simplified to this

<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />

function checkInput(obj) {
    alert(obj.value); 
}

Convert row names into first column

Or by using DBIs sqlRownamesToColumn

library(DBI)
sqlRownamesToColumn(df)

How can you use php in a javascript function

Simply return it:

<html>
    <?php
        $num = 1;
        echo $num;
    ?>
    <input type="button"
       name="lol" 
       value="Click to increment"
       onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {
            Return <?php
            $num = 2;
            echo $num;
            ?>;
        }
    </script>
</html>

Case Insensitive String comp in C

As others have stated, there is no portable function that works on all systems. You can partially circumvent this with simple ifdef:

#include <stdio.h>

#ifdef _WIN32
#include <string.h>
#define strcasecmp _stricmp
#else // assuming POSIX or BSD compliant system
#include <strings.h>
#endif

int main() {
    printf("%d", strcasecmp("teSt", "TEst"));
}

MySQl Error #1064

At first you need to add semi colon (;) after quantity INT NOT NULL) then remove ** from ,genre,quantity)**. to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.

PHP's array_map including keys

I always like the javascript variant of array map. The most simple version of it would be:

/**
 * @param  array    $array
 * @param  callable $callback
 * @return array
 */
function arrayMap(array $array, callable $callback)
{
    $newArray = [];

    foreach( $array as $key => $value )
    {
        $newArray[] = call_user_func($callback, $value, $key, $array);
    }

    return $newArray;
}

So now you can just pass it a callback function how to construct the values.

$testArray = [
    "first_key" => "first_value", 
    "second_key" => "second_value"
];

var_dump(
    arrayMap($testArray, function($value, $key) {
        return $key . ' loves ' . $value;
    });
);

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

How to format numbers by prepending 0 to single-digit numbers?

My version:

`${Math.trunc(num / 10)}${Math.trunc(num % 10)}`;

_x000D_
_x000D_
const func = (num) => `${Math.trunc(num / 10)}${Math.trunc(num % 10)}`;

const nums = [1, 3, 5, 6, 8, 9, 10, 20, 56, 80];
nums.forEach(num => console.log(func(num)));
_x000D_
_x000D_
_x000D_

Remove all files in a directory

Another way I've done this:

os.popen('rm -f ./yourdir')

Commit history on remote repository

This is what worked for me:

git fetch --all 
git log production/master

Note that this fetches from ALL remotes, i.e. potentially you "have to clone 2GB worth of objects just to look through the commit logs".

Eclipse: How do I add the javax.servlet package to a project?

  1. Download the file from http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadjavaxservletjar.htm

  2. Make a folder ("lib") inside the project folder and move that jar file to there.

  3. In Eclipse, right click on project > BuildPath > Configure BuildPath > Libraries > Add External Jar

Thats all

How to format a Java string with leading zero?

Use Apache Commons StringUtils.leftPad (or look at the code to make your own function).

Set cURL to use local virtual hosts

Either use a real fully qualified domain name (like dev.yourdomain.com) that pointing to 127.0.0.1 or try editing the proper hosts file (usually /etc/hosts in *nix environments).

Compiling C++11 with g++

Flags (or compiler options) are nothing but ordinary command line arguments passed to the compiler executable.

Assuming you are invoking g++ from the command line (terminal):

$ g++ -std=c++11 your_file.cpp -o your_program

or

$ g++ -std=c++0x your_file.cpp -o your_program

if the above doesn't work.

mysqli_fetch_array while loop columns

Both will works perfectly in mysqli_fetch_array in while loops

while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
    $posts[] = $row['post_id'].$row['post_title'].$row['content'];
}

(OR)

while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    $posts[] = $row['post_id'].$row['post_title'].$row['content'];
}

mysqli_fetch_array() - has second argument $resulttype.

MYSQLI_ASSOC: Fetch associative array

MYSQLI_NUM: Fetch numeric array

MYSQLI_BOTH: Fetch both associative and numeric array.

How to make div go behind another div?

container can not come front to inner container. but try this below :

Css :
----------------------
.container { position:relative; }
    .div1 { width:100px; height:100px; background:#9C3; position:absolute; 
            z-index:1000; left:50px; top:50px; }
    .div2 { width:200px; height:200px; background:#900; }

HTMl : 
-----------------------
<div class="container">
    <div class="div1">
       Div1 content here .........
    </div>
    <div class="div2">
       Div2 contenet here .........
    </div>
</div>

Java code for getting current time

You can use new Date () and it'll give you current time.

If you need to represent it in some format (and usually you need to do it) then use formatters.

DateFormat df = DateFormat.getDateTimeInstance (DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale ("en", "EN"));
String formattedDate = df.format (new Date ());

Can't resolve module (not found) in React.js

you should change import Header from './src/components/header/header' to

import Header from '../src/components/header/header'

Case insensitive searching in Oracle

There are 3 main ways to perform a case-insensitive search in Oracle without using full-text indexes.

Ultimately what method you choose is dependent on your individual circumstances; the main thing to remember is that to improve performance you must index correctly for case-insensitive searching.

1. Case your column and your string identically.

You can force all your data to be the same case by using UPPER() or LOWER():

select * from my_table where upper(column_1) = upper('my_string');

or

select * from my_table where lower(column_1) = lower('my_string');

If column_1 is not indexed on upper(column_1) or lower(column_1), as appropriate, this may force a full table scan. In order to avoid this you can create a function-based index.

create index my_index on my_table ( lower(column_1) );

If you're using LIKE then you have to concatenate a % around the string you're searching for.

select * from my_table where lower(column_1) LIKE lower('my_string') || '%';

This SQL Fiddle demonstrates what happens in all these queries. Note the Explain Plans, which indicate when an index is being used and when it isn't.

2. Use regular expressions.

From Oracle 10g onwards REGEXP_LIKE() is available. You can specify the _match_parameter_ 'i', in order to perform case-insensitive searching.

In order to use this as an equality operator you must specify the start and end of the string, which is denoted by the carat and the dollar sign.

select * from my_table where regexp_like(column_1, '^my_string$', 'i');

In order to perform the equivalent of LIKE, these can be removed.

select * from my_table where regexp_like(column_1, 'my_string', 'i');

Be careful with this as your string may contain characters that will be interpreted differently by the regular expression engine.

This SQL Fiddle shows you the same example output except using REGEXP_LIKE().

3. Change it at the session level.

The NLS_SORT parameter governs the collation sequence for ordering and the various comparison operators, including = and LIKE. You can specify a binary, case-insensitive, sort by altering the session. This will mean that every query performed in that session will perform case-insensitive parameters.

alter session set nls_sort=BINARY_CI

There's plenty of additional information around linguistic sorting and string searching if you want to specify a different language, or do an accent-insensitive search using BINARY_AI.

You will also need to change the NLS_COMP parameter; to quote:

The exact operators and query clauses that obey the NLS_SORT parameter depend on the value of the NLS_COMP parameter. If an operator or clause does not obey the NLS_SORT value, as determined by NLS_COMP, the collation used is BINARY.

The default value of NLS_COMP is BINARY; but, LINGUISTIC specifies that Oracle should pay attention to the value of NLS_SORT:

Comparisons for all SQL operations in the WHERE clause and in PL/SQL blocks should use the linguistic sort specified in the NLS_SORT parameter. To improve the performance, you can also define a linguistic index on the column for which you want linguistic comparisons.

So, once again, you need to alter the session

alter session set nls_comp=LINGUISTIC

As noted in the documentation you may want to create a linguistic index to improve performance

create index my_linguistc_index on my_table 
   (NLSSORT(column_1, 'NLS_SORT = BINARY_CI'));

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

How to get the part of a file after the first line that matches a regular expression?

sed is a much better tool for the job: sed -n '/re/,$p' file

where re is regexp.

Another option is grep's --after-context flag. You need to pass in a number to end at, using wc on the file should give the right value to stop at. Combine this with -n and your match expression.

Excel CSV - Number cell format

This has been driving me crazy all day (since indeed you can't control the Excel column types before opening the CSV file), and this worked for me, using VB.NET and Excel Interop:

        'Convert .csv file to .txt file.
        FileName = ConvertToText(FileName)

        Dim ColumnTypes(,) As Integer = New Integer(,) {{1, xlTextFormat}, _
                                                        {2, xlTextFormat}, _
                                                        {3, xlGeneralFormat}, _
                                                        {4, xlGeneralFormat}, _
                                                        {5, xlGeneralFormat}, _
                                                        {6, xlGeneralFormat}}

        'We are using OpenText() in order to specify the column types.
        mxlApp.Workbooks.OpenText(FileName, , , Excel.XlTextParsingType.xlDelimited, , , True, , True, , , , ColumnTypes)
        mxlWorkBook = mxlApp.ActiveWorkbook
        mxlWorkSheet = CType(mxlApp.ActiveSheet, Excel.Worksheet)


Private Function ConvertToText(ByVal FileName As String) As String
    'Convert the .csv file to a .txt file.
    'If the file is a text file, we can specify the column types.
    'Otherwise, the Codes are first converted to numbers, which loses trailing zeros.

    Try
        Dim MyReader As New StreamReader(FileName)
        Dim NewFileName As String = FileName.Replace(".CSV", ".TXT")
        Dim MyWriter As New StreamWriter(NewFileName, False)
        Dim strLine As String

        Do While Not MyReader.EndOfStream
            strLine = MyReader.ReadLine
            MyWriter.WriteLine(strLine)
        Loop

        MyReader.Close()
        MyReader.Dispose()
        MyWriter.Close()
        MyWriter.Dispose()

        Return NewFileName
    Catch ex As Exception
        MsgBox(ex.Message)
        Return ""
    End Try

End Function

HTTP Error 500.19 and error code : 0x80070021

I also was getting the same problem but after brain storming with IIS and google for many hours. I found out the solution. This error is because some settings are disabled in IIS applicationHost.config.

Below are the steps to solution:

  1. Go to C:\Windows\System32\inetsrv\config\applicationHost.config and open in notepad
  2. Change the following key value present in

    • <section name="handlers" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"

    • <section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"

It worked for me.

Excel SUMIF between dates

One more solution when you want to use data from any sell ( in the key C3)

=SUMIF(Sheet6!M:M;CONCATENATE("<";TEXT(C3;"dd.mm.yyyy"));Sheet6!L:L)

how to display employee names starting with a and then b in sql

From A to Z:

select employee_name from employees ORDER BY employee_name ;

From Z to A:

select employee_name from employees ORDER BY employee_name desc ;

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

List of IP addresses/hostnames from local network in Python

Try:

import socket

print ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])

Copy Paste in Bash on Ubuntu on Windows

As others have said, there is now an option for Ctrl+Shf+Vfor paste in Windows 10 Insider build #17643.

Unfortunately this isn't in my muscle memory and as a user of TTY terminals I'd like to use Shf+Ins as I do on all the Linux boxes I connect to.

This is possible on Windows 10 if you install ConEmu which wraps the terminal in a new GUI and allows Shf+Ins for paste. It also allows you to tweak the behaviour in the Properties.

The Console looks like this:ConEmu Console

Copy options:ConEmu Copy properties

Paste options:ConEmu Paste properties

Shf+Ins works out of the box. I can't remember if you need to configure bash as one of the shells it uses but if you do, here is the task properties to add it:ConEmu Bash Task Properties

Also allows tabbed Consoles (including different types, cmd.exe, powershell etc). I've been using this since early Windows 7 and in those days it made the command line on Windows usable!

Check if a value exists in pandas dataframe index

df = pandas.DataFrame({'g':[1]}, index=['isStop'])

#df.loc['g']

if 'g' in df.index:
    print("find g")

if 'isStop' in df.index:
    print("find a") 

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

I see what you are trying to do, you are trying to use the <body> tag as the container for the main content of the page. Instead, use the <main> tag, as specified in the HTML5 spec. I use this layout:

    <!DOCTYPE html>
    <html>
        <head> *Metadata* </head>
        <body>
            <header>
                *<h1> and other important stuff </h1>*
                <nav> *Usually a formatted <Ul>* </nav>
            </header>
            <main> *All my content* </main>
            <footer> *Copyright, links, social media etc* </footer>
        </body>
    </html>

I'm not 100% sure but I think that anything outside the <body> tag is considered metadata and will not be rendered by the browser. I don't think that the DOM can access it either.

To conclude, use the <main> tag for your content and keep formatting your HTML the correct way as you have in your first code snippet. You used the <section> tag but I think that comes with some weird formatting issues when you try to apply CSS.

Check if event exists on element

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

git push to specific branch

git push origin amd_qlp_tester will work for you. If you just type git push, then the remote of the current branch is the default value.

Syntax of push looks like this - git push <remote> <branch>. If you look at your remote in .git/config file, you will see an entry [remote "origin"] which specifies url of the repository. So, in the first part of command you will tell Git where to find repository for this project, and then you just specify a branch.

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

Create a List of primitive int?

In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type.

Instead use the Integer class which is a wrapper for int:

List<Integer> list = new ArrayList<Integer>();

If your using Java 7 you can simplify this declaration using the diamond operator:

List<Integer> list = new ArrayList<>();

With autoboxing in Java the primitive type int will become an Integer when necessary.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

So the following is valid:

int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);

System.out.println(list.get(0)); //prints 1

Launch custom android application from android browser

Look @JRuns answer in here. The idea is to create html with your custom scheme and upload it somewhere. Then if you click on your custom link on your html-file, you will be redirected to your app. I used this article for android. But dont forget to set full name Name = "MyApp.Mobile.Droid.MainActivity" attribute to your target activity.

Is there a JavaScript strcmp()?

How about:

String.prototype.strcmp = function(s) {
    if (this < s) return -1;
    if (this > s) return 1;
    return 0;
}

Then, to compare s1 with 2:

s1.strcmp(s2)

Count number of 1's in binary representation

The below method can count the number of 1s in negative numbers as well.

private static int countBits(int number)    {
    int result = 0;
    while(number != 0)  {
        result += number & 1;
        number = number >>> 1;
    }
    return result;
}

However, a number like -1 is represented in binary as 11111111111111111111111111111111 and so will require a lot of shifting. If you don't want to do so many shifts for small negative numbers, another way could be as follows:

private static int countBits(int number)    {
    boolean negFlag = false;
    if(number < 0)  { 
        negFlag = true;
        number = ~number;
    }

    int result = 0;
    while(number != 0)  {
        result += number & 1;
        number = number >> 1;
    }
    return negFlag? (32-result): result;
}