Programs & Examples On #Least astonishment

Don't surprise the programmer by behaving/working differently than expected.

"Least Astonishment" and the Mutable Default Argument

This behavior is easy explained by:

  1. function (class etc.) declaration is executed only once, creating all default value objects
  2. everything is passed by reference

So:

def x(a=0, b=[], c=[], d=0):
    a = a + 1
    b = b + [1]
    c.append(1)
    print a, b, c
  1. a doesn't change - every assignment call creates new int object - new object is printed
  2. b doesn't change - new array is build from default value and printed
  3. c changes - operation is performed on same object - and it is printed

Map HTML to JSON

I just wrote this function that does what you want; try it out let me know if it doesn't work correctly for you:

// Test with an element.
var initElement = document.getElementsByTagName("html")[0];
var json = mapDOM(initElement, true);
console.log(json);

// Test with a string.
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
console.log(json);

function mapDOM(element, json) {
    var treeObject = {};
    
    // If string convert to document Node
    if (typeof element === "string") {
        if (window.DOMParser) {
              parser = new DOMParser();
              docNode = parser.parseFromString(element,"text/xml");
        } else { // Microsoft strikes again
              docNode = new ActiveXObject("Microsoft.XMLDOM");
              docNode.async = false;
              docNode.loadXML(element); 
        } 
        element = docNode.firstChild;
    }
    
    //Recursively loop through DOM elements and assign properties to object
    function treeHTML(element, object) {
        object["type"] = element.nodeName;
        var nodeList = element.childNodes;
        if (nodeList != null) {
            if (nodeList.length) {
                object["content"] = [];
                for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].nodeType == 3) {
                        object["content"].push(nodeList[i].nodeValue);
                    } else {
                        object["content"].push({});
                        treeHTML(nodeList[i], object["content"][object["content"].length -1]);
                    }
                }
            }
        }
        if (element.attributes != null) {
            if (element.attributes.length) {
                object["attributes"] = {};
                for (var i = 0; i < element.attributes.length; i++) {
                    object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
                }
            }
        }
    }
    treeHTML(element, treeObject);
    
    return (json) ? JSON.stringify(treeObject) : treeObject;
}

Working example: http://jsfiddle.net/JUSsf/ (Tested in Chrome, I can't guarantee full browser support - you will have to test this).

?It creates an object that contains the tree structure of the HTML page in the format you requested and then uses JSON.stringify() which is included in most modern browsers (IE8+, Firefox 3+ .etc); If you need to support older browsers you can include json2.js.

It can take either a DOM element or a string containing valid XHTML as an argument (I believe, I'm not sure whether the DOMParser() will choke in certain situations as it is set to "text/xml" or whether it just doesn't provide error handling. Unfortunately "text/html" has poor browser support).

You can easily change the range of this function by passing a different value as element. Whatever value you pass will be the root of your JSON map.

IIS Express Windows Authentication

If none of the answers helps, you might need to adjust the project properties. Check this other StackOverflow answer on how to do that:

https://stackoverflow.com/a/20857049/56621

Dynamically adding properties to an ExpandoObject

Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.


    public static class dynamicHelper
        {
            public static ExpandoObject convertToExpando(object obj)
            {
                //Get Properties Using Reflections
                BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
                PropertyInfo[] properties = obj.GetType().GetProperties(flags);

                //Add Them to a new Expando
                ExpandoObject expando = new ExpandoObject();
                foreach (PropertyInfo property in properties)
                {
                    AddProperty(expando, property.Name, property.GetValue(obj));
                }

                return expando;
            }

            public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
            {
                //Take use of the IDictionary implementation
                var expandoDict = expando as IDictionary;
                if (expandoDict.ContainsKey(propertyName))
                    expandoDict[propertyName] = propertyValue;
                else
                    expandoDict.Add(propertyName, propertyValue);
            }
        }

Usage:

//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);

//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");

How to make clang compile to llvm IR

If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.

Instead, you want to compile with link-time-optimization

clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o

and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm

clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program

This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing

clang program.bc -o program

although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.

Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option

-B/home/jeremy/fakebin

to any linking steps above.

HTML5 Email input pattern attribute

I had this exact problem with HTML5s email input, using Alwin Keslers answer above I added the regex to the HTML5 email input so the user must have .something at the end.

<input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" />

How do I concatenate text in a query in sql server?

Another option is the CONCAT command:

SELECT CONCAT(MyTable.TextColumn, 'Text') FROM MyTable

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

How to display a JSON representation and not [Object Object] on the screen

We can use angular pipe json

{{ jsonObject | json }}

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

SQL Server Linked Server Example Query

PostgreSQL:

  1. You must provide a database name in the Data Source DSN.
  2. Run Management Studio as Administrator
  3. You must omit the DBName from the query:

    SELECT * FROM OPENQUERY([LinkedServer], 'select * from schema."tablename"')

How can I stop Chrome from going into debug mode?

For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.

For me it was the "breakOnLoad": true line in VS Code launch.json config.

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

Styling Google Maps InfoWindow

google.maps.event.addListener(infowindow, 'domready', function() {

    // Reference to the DIV that wraps the bottom of infowindow
    var iwOuter = $('.gm-style-iw');

    /* Since this div is in a position prior to .gm-div style-iw.
     * We use jQuery and create a iwBackground variable,
     * and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
    */
    var iwBackground = iwOuter.prev();

    // Removes background shadow DIV
    iwBackground.children(':nth-child(2)').css({'display' : 'none'});

    // Removes white background DIV
    iwBackground.children(':nth-child(4)').css({'display' : 'none'});

    // Moves the infowindow 115px to the right.
    iwOuter.parent().parent().css({left: '115px'});

    // Moves the shadow of the arrow 76px to the left margin.
    iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

    // Moves the arrow 76px to the left margin.
    iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

    // Changes the desired tail shadow color.
    iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'rgba(72, 181, 233, 0.6) 0px 1px 6px', 'z-index' : '1'});

    // Reference to the div that groups the close button elements.
    var iwCloseBtn = iwOuter.next();

    // Apply the desired effect to the close button
    iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #48b5e9', 'border-radius': '13px', 'box-shadow': '0 0 5px #3990B9'});

    // If the content of infowindow not exceed the set maximum height, then the gradient is removed.
    if($('.iw-content').height() < 140){
      $('.iw-bottom-gradient').css({display: 'none'});
    }

    // The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
    iwCloseBtn.mouseout(function(){
      $(this).css({opacity: '1'});
    });
  });

//CSS put in stylesheet

.gm-style-iw {
  background-color: rgb(237, 28, 36);
    border: 1px solid rgba(72, 181, 233, 0.6);
    border-radius: 10px;
    box-shadow: 0 1px 6px rgba(178, 178, 178, 0.6);
    color: rgb(255, 255, 255) !important;
    font-family: gothambook;
    text-align: center;
    top: 15px !important;
    width: 150px !important;
}

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

How to find/identify large commits in git history?

If you are on Windows, here is a PowerShell script that will print the 10 largest files in your repository:

$revision_objects = git rev-list --objects --all;
$files = $revision_objects.Split() | Where-Object {$_.Length -gt 0 -and $(Test-Path -Path $_ -PathType Leaf) };
$files | Get-Item -Force | select fullname, length | sort -Descending -Property Length | select -First 10

Activate tabpage of TabControl

You can use the method SelectTab.

There are 3 versions:

public void SelectTab(int index);
public void SelectTab(string tabPageName);
public void SelectTab(TabPage tabPage);

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

FormData.append("key", "value") is not working

React Version

Make sure to have a header with 'content-type': 'multipart/form-data'

_handleSubmit(e) {
    e.preventDefault();
    const formData = new FormData();
          formData.append('file', this.state.file);
    const config = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }

     axios.post("/upload", formData, config)
         .then((resp) => {
             console.log(resp)
         }).catch((error) => {
    })
  }

  _handleImageChange(e) {
    e.preventDefault();
    let file = e.target.files[0];
    this.setState({
      file: file
    });
  }

View

  #html
 <input className="form-control"
    type="file" 
    onChange={(e)=>this._handleImageChange(e)} 
 />

Git branching: master vs. origin/master vs. remotes/origin/master

Short answer for dummies like me (stolen from Torek):

  • origin/master is "where master was over there last time I checked"
  • master is "where master is over here based on what I have been doing"

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

ImportError: No module named apiclient.discovery

for python3 this worked for me:

sudo pip3 install --upgrade google-api-python-client

Scala best way of turning a Collection into a Map-by-key?

This works for me:

val personsMap = persons.foldLeft(scala.collection.mutable.Map[Int, PersonDTO]()) {
    (m, p) => m(p.id) = p; m
}

The Map has to be mutable and the Map has to be return since adding to a mutable Map does not return a map.

How to get ID of button user just clicked?

$("button").click(function() {
    alert(this.id); // or alert($(this).attr('id'));
});

Convert datetime to Unix timestamp and convert it back in python

solution is

import time
import datetime
d = datetime.date(2015,1,5)

unixtime = time.mktime(d.timetuple())

Simple If/Else Razor Syntax

To get rid of the if/else awkwardness you could use a using block:

@{
    var count = 0;
    foreach (var item in Model)
    {
        using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
        {
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Truncate(item.Details, 75)
            </td>
            <td>
                <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                    alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
                @Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
            </td>
        }
    }
}

Reusable element that make it easier to add attributes:

//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
    private object _htmlAttributes;
    private TagBuilder _tr;

    public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
    {
        _htmlAttributes = htmlAttributes;
    }

    public override void BeginBlock()
    {
        _tr = new TagBuilder("tr");
        _tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
    }

    protected override void EndBlock()
    {
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
    }
}

Helper method to make razor syntax clearer:

public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
    var tableRow = new TableRow(self, htmlAttributes);
    tableRow.BeginBlock();
    return tableRow;
}

Is an empty href valid?

it's valid but like UpTheCreek said 'There are some downsides to each approach'

if you're calling ajax through an tag leave the href="" like this will keep the page reloading and the ajax code will never be called ...

just got this thought would be good to share

UITableView, Separator color where to set?

Swift 3, xcode version 8.3.2, storyboard->choose your table View->inspector->Separator.

Swift 3, xcode version 8.3.2

How to update data in one table from corresponding data in another table in SQL Server 2005

use test1

insert into employee(deptid) select deptid from test2.dbo.employee

For Restful API, can GET method use json data?

In theory, there's nothing preventing you from sending a request body in a GET request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.

However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.

The simple option is to use POST instead of GET as recommended by other answers. Since POST is not standardized by HTTP, you'll have to document how exactly that's supposed to work.

Another option, which I prefer, is to implement your application assuming the GET payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override, which is a popular convention for clients to emulate HTTP methods with POST. So, if a client has a broken implementation, it can write the GET request as a POST, sending the X-HTTP-Method-Override: GET method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

I got a similar problem , I parsed the youtube url. The code is;

$json_is = "http://gdata.youtube.com/feeds/api/videos?q=".$this->video_url."&max-results=1&alt=json";
$video_info = json_decode ( file_get_contents ( $json_is ), true );     
$video_title = is_array ( $video_info ) ? $video_info ['feed'] ['entry'] [0] ['title'] ['$t'] : '';

Then I realise that $this->video_url include the whitespace. I solved that using trim($this->video_url).

Maybe it will help you . Good Luck

Convert multiple rows into one with comma as separator

If you're executing this through PHP, what about this?

$hQuery = mysql_query("SELECT * FROM users");
while($hRow = mysql_fetch_array($hQuery)) {
    $hOut .= $hRow['username'] . ", ";
}
$hOut = substr($hOut, 0, strlen($hOut) - 1);
echo $hOut;

No grammar constraints (DTD or XML schema) detected for the document

This worked for me in Eclipse 3.7.1: Go to the Preferences window, then XML -> XML Files -> Validation. Then in the Validating files section of the preferences panel on the right, choose Ignore in the drop down box for the "No grammar specified" preference. You may need to close the file and then reopen it to make the warning go away.

(I know this question is old but it was the first one I found when searching on the warning, so I'm posting the answer here for other searchers.)

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

Cmake is not able to find Python-libraries

You can fix the errors by appending to the cmake command the -DPYTHON_LIBRARY and -DPYTHON_INCLUDE_DIR flags filled with the respective folders.

Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reliable. This may work independently of your python location/version (also for Anaconda users):

$ cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))")

If the version of python that you want to link against cmake is Python3.X and the default python symlink points to Python2.X, python3 -c ... can be used instead of python -c ....

In case that the error persists, you may need to update the cmake to a higher version as stated by @pdpcosta and repeat the process again.

How to declare a vector of zeros in R

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

Python socket connection timeout

If you are using Python2.6 or newer, it's convenient to use socket.create_connection

sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

Create a shortcut on Desktop

Here is a piece of code that has no dependency on an external COM object (WSH), and supports 32-bit and 64-bit programs:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

namespace TestShortcut
{
    class Program
    {
        static void Main(string[] args)
        {
            IShellLink link = (IShellLink)new ShellLink();

            // setup shortcut information
            link.SetDescription("My Description");
            link.SetPath(@"c:\MyPath\MyProgram.exe");

            // save it
            IPersistFile file = (IPersistFile)link;
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            file.Save(Path.Combine(desktopPath, "MyLink.lnk"), false);
        }
    }

    [ComImport]
    [Guid("00021401-0000-0000-C000-000000000046")]
    internal class ShellLink
    {
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("000214F9-0000-0000-C000-000000000046")]
    internal interface IShellLink
    {
        void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
        void GetIDList(out IntPtr ppidl);
        void SetIDList(IntPtr pidl);
        void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
        void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
        void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
        void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
        void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
        void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
        void GetHotkey(out short pwHotkey);
        void SetHotkey(short wHotkey);
        void GetShowCmd(out int piShowCmd);
        void SetShowCmd(int iShowCmd);
        void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
        void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
        void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
        void Resolve(IntPtr hwnd, int fFlags);
        void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
    }
}

How to post SOAP Request from PHP

I needed to do many very simple XML requests and after reading @Ivan Krechetov's comment about the speed hit of SOAP, I tried his code and discovered http_post_data() is not built into PHP 5.2. Not really wanting to install it, I tried cURL which is on all my servers. Although I do not know how fast cURL is compared to SOAP, it sure was easy to do what I needed. Below is a sample with cURL for anyone needing it.

$xml_data = '<?xml version="1.0" encoding="UTF-8" ?>
<priceRequest><customerNo>123</customerNo><password>abc</password><skuList><SKU>99999</SKU><lineNumber>1</lineNumber></skuList></priceRequest>';
$URL = "https://test.testserver.com/PriceAvailability";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);


print_r($output);

How to center a <p> element inside a <div> container?

This solution works fine for all major browsers, except IE. So keep that in mind.

In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.

_x000D_
_x000D_
        .container {_x000D_
            /* set the the position to relative */_x000D_
            position: relative;_x000D_
            width: 30rem;_x000D_
            height: 20rem;_x000D_
            background-color: #2196F3;_x000D_
        }_x000D_
_x000D_
_x000D_
        .paragh {_x000D_
            /* set the the position to absolute */_x000D_
            position: absolute;_x000D_
            /* set the the position of the helper container into the middle of its space */_x000D_
            top: 50%;_x000D_
            left: 50%;_x000D_
            font-size: 30px;_x000D_
            /* make sure padding and margin do not disturb the calculation of the center point */_x000D_
            padding: 0;_x000D_
            margin: 0;_x000D_
            /* using centers for the transform */_x000D_
            transform-origin: center center;_x000D_
            /* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
            transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
        }
_x000D_
<div class="container">_x000D_
    <p class="paragh">Text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I hope this help.

TypeScript error TS1005: ';' expected (II)

Just try to without changing anything npm install [email protected] X.X.X is your current version

composer laravel create project

you first need to install laravel using command: composer global require laravel/installer then use composer create-project command your problem will be solved. I hope your problem is now solved.

How to change menu item text dynamically in Android

I would suggest keeping a reference within the activity to the Menu object you receive in onCreateOptionsMenu and then using that to retrieve the MenuItem that requires the change as and when you need it. For example, you could do something along the lines of the following:

public class YourActivity extends Activity {

  private Menu menu;
  private String inBedMenuTitle = "Set to 'In bed'";
  private String outOfBedMenuTitle = "Set to 'Out of bed'";
  private boolean inBed = false;

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    // Create your menu...

    this.menu = menu;
    return true;
  }

  private void updateMenuTitles() {
    MenuItem bedMenuItem = menu.findItem(R.id.bedSwitch);
    if (inBed) {
      bedMenuItem.setTitle(outOfBedMenuTitle);
    } else {
      bedMenuItem.setTitle(inBedMenuTitle);
    }
  }

}

Alternatively, you can override onPrepareOptionsMenu to update the menu items each time the menu is displayed.

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

AlertDialog.Builder with custom layout and EditText; cannot access view

In case any one wants it in Kotlin :

val dialogBuilder = AlertDialog.Builder(this)
// ...Irrelevant code for customizing the buttons and title
val dialogView = layoutInflater.inflate(R.layout.alert_label_editor, null)
dialogBuilder.setView(dialogView)

val editText =  dialogView.findViewById(R.id.label_field)
editText.setText("test label")
val alertDialog = dialogBuilder.create()
alertDialog.show()

Reposted @user370305's answer.

What is the best IDE to develop Android apps in?

I Feel Eclipse IDE is more suitable for android applications rather than other IDEs. Because its providing us more than five perspectives which will make our project flexible and ease.You may try Eclipse ides starts with 3.6 and above will provide you better performance.

Eclipse_jee_indigo
Eclipse_java_indigo
Eclipse_classic

The above eclipses are belongs to the version3.7.2 which are all latest and supports all kind of access.

What does 'URI has an authority component' mean?

I also faced similar problem while working on Affable Bean e-commerce site development. I received an error:

Module has not been deployed.

I checked the sun-resources.xml file and found the following statements which resulted in the error.

<resources>
    <jdbc-resource enabled="true"
                   jndi-name="jdbc/affablebean"
                   object-type="user"
                   pool-name="AffableBeanPool">
    </jdbc-resource>

    <jdbc-connection-pool allow-non-component-callers="false"
                          associate-with-thread="false"
                          connection-creation-retry-attempts="0"
                          connection-creation-retry-interval-in-seconds="10"
                          connection-leak-reclaim="false"
                          connection-leak-timeout-in-seconds="0"
                          connection-validation-method="auto-commit"
                          datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                          fail-all-connections="false"
                          idle-timeout-in-seconds="300"
                          is-connection-validation-required="false"
                          is-isolation-level-guaranteed="true"
                          lazy-connection-association="false"
                          lazy-connection-enlistment="false"
                          match-connections="false"
                          max-connection-usage-count="0"
                          max-pool-size="32"
                          max-wait-time-in-millis="60000"
                          name="AffableBeanPool"
                          non-transactional-connections="false"
                          pool-resize-quantity="2"
                          res-type="javax.sql.ConnectionPoolDataSource"
                          statement-timeout-in-seconds="-1"
                          steady-pool-size="8"
                          validate-atmost-once-period-in-seconds="0"
                          wrap-jdbc-objects="false">

        <description>Connects to the affablebean database</description>
        <property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

Then I changed the statements to the following which is simple and works. I was able to run the file successfully.

<resources>
    <jdbc-resource enabled="true" jndi-name="jdbc/affablebean" object-type="user" pool-name="AffablebeanPool">
        <description/>
    </jdbc-resource>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="AffablebeanPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="URL" value="jdbc:mysql://localhost:3306/AffableBean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

Setting a backgroundImage With React Inline Styles

try this it worked in my case

backgroundImage: `url("${Background}")`

Count the Number of Tables in a SQL Server Database

Try this:

SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

How do I create a MessageBox in C#?

Also you can use a MessageBox with OKCancel options, but it requires many codes. The if block is for OK, the else block is for Cancel. Here is the code:

if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
    MessageBox.Show("You pressed OK!");
}
else
{
    MessageBox.Show("You pressed Cancel!");
}

You can also use a MessageBox with YesNo options:

if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    MessageBox.Show("You are pressed Yes!");
}
else
{
    MessageBox.Show("You are pressed No!");
}

Laravel 5 Carbon format datetime

Try that:

$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');

HttpContext.Current.Session is null when routing requests

I think this part of code make changes to the context.

 Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

Also this part of code is useless:

 if (page != null)
 {
     return page;
 }
 return page;

It will always return the page wither it's null or not.

height: 100% for <div> inside <div> with display: table-cell

When you use % for setting heights or widths, always set the widths/heights of parent elements as well:

_x000D_
_x000D_
.table {_x000D_
    display: table;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
    border: 2px solid black;_x000D_
    vertical-align: top;_x000D_
    display: table-cell;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    height: 100%;_x000D_
    border: 2px solid green;_x000D_
    -moz-box-sizing: border-box;_x000D_
}
_x000D_
<div class="table">_x000D_
    <div class="cell">_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
    </div>_x000D_
    <div class="cell">_x000D_
        <div class="container">Text</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is my attempt:

Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp

    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.

        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If

    End With
End Function

*.h or *.hpp for your class definitions

As many here have already mentioned, I also prefer using .hpp for header-only libraries that use template classes/functions. I prefer to use .h for header files accompanied by .cpp source files or shared or static libraries.

Most of the libraries I develop are template based and thus need to be header only, but when writing applications I tend to separate declaration from implementation and end up with .h and .cpp files

What is the difference between DTR/DSR and RTS/CTS flow control?

  • DTR - Data Terminal Ready
  • DSR - Data Set Ready
  • RTS - Request To Send
  • CTS - Clear To Send

There are multiple ways of doing things because there were never any protocols built into the standards. You use whatever ad-hoc "standard" your equipment implements.

Just based on the names, RTS/CTS would seem to be a natural fit. However, it's backwards from the needs that developed over time. These signals were created at a time when a terminal would batch-send a screen full of data, but the receiver might not be ready, thus the need for flow control. Later the problem would be reversed, as the terminal couldn't keep up with data coming from the host, but the RTS/CTS signals go the wrong direction - the interface isn't orthogonal, and there's no corresponding signals going the other way. Equipment makers adapted as best they could, including using the DTR and DSR signals.

EDIT

To add a bit more detail, its a two level hierarchy so "officially" both must happen for communication to take place. The behavior is defined in the original CCITT (now ITU-T) standard V.28.

enter image description here

The DCE is a modem connecting between the terminal and telephone network. In the telephone network was another piece of equipment which split off to the data network, eg. X.25.

The modem has three states: Powered off, Ready (Data Set Ready is true), and connected (Data Carrier Detect)

The terminal can't do anything until the modem is connected.

When the modem wants to send data, it raises RTS and the modem grants the request with CTS. The modem lowers CTS when its internal buffer is full.

So nostalgic!

Java 8 stream map to list of keys sorted by values

Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "A");

List<String> list = map.values()
                       .stream()
                       .sorted()
                       .collect(Collectors.toList());

Output: [A, B, C, D]

How to use XMLReader in PHP?

XMLReader is well documented on PHP site. This is a XML Pull Parser, which means it's used to iterate through nodes (or DOM Nodes) of given XML document. For example, you could go through the entire document you gave like this:

<?php
$reader = new XMLReader();
if (!$reader->open("data.xml"))
{
    die("Failed to open 'data.xml'");
}
while($reader->read())
{
    $node = $reader->expand();
    // process $node...
}
$reader->close();
?>

It is then up to you to decide how to deal with the node returned by XMLReader::expand().

Get current date in Swift 3?

You say in a comment you want to get "15.09.2016".

For this, use Date and DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

let result = formatter.string(from: date)

Set your label:

label.text = result

Result:

15.09.2016

Lists in ConfigParser

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

Convert negative data into positive data in SQL Server

You are thinking in the function ABS, that gives you the absolute value of numeric data.

SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable

How to serve an image using nodejs

Let me just add to the answers above, that optimizing images, and serving responsive images helps page loading times dramatically since >90% of web traffic are images. You might want to pre-process images using JS / Node modules such as imagemin and related plug-ins, ideally during the build process with Grunt or Gulp.

Optimizing images means processing finding an ideal image type, and selecting optimal compression to achieve a balance between image quality and file size.

Serving responsive images translates into creating several sizes and formats of each image automatically and using srcset in your HTML allows you to serve optimal image set (that is, the ideal format and dimensions, thus optimal file size) for every single browser).

Image processing automation during the build process means incorporating it up once, and presenting optimized images further on, requiring minimum extra time.

Some great read on responsive images, minification in general, imagemin node module and using srcset.

What does "async: false" do in jQuery.ajax()?

Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.

How to download a file with Node.js (without using third-party libraries)?

var requestModule=require("request");

requestModule(filePath).pipe(fs.createWriteStream('abc.zip'));

Android/Eclipse: how can I add an image in the res/drawable folder?

Drop in the image in /res/drawable folder. Then in Eclipse Menu, do ->Project -> Clean. This will do a clean build if set to build automatically.

How to find integer array size in java

Integer Array doesn't contain size() or length() method. Try the below code, it'll work. ArrayList contains size() method. String contains length(). Since you have used int array[], so it will be array.length

public class Example {

    int array[] = {1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554, 22, 22, 211};

    public void Printrange() {

        for (int i = 0; i < array.length; i++) {
            if (array[i] > 100 && array[i] < 500) {
                System.out.println("numbers with in range" + i);
            }
        }
    }
}

Change placeholder text

Using jquery you can do this by following code:

<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>

$('#tbxEmail').attr('placeholder','Some New Text');

AJAX POST and Plus Sign ( + ) -- How to Encode?

Use encodeURIComponent() in JS and in PHP you should receive the correct values.

Note: When you access $_GET, $_POST or $_REQUEST in PHP, you are retrieving values that have already been decoded.

Example:

In your JS:

// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B

On your server:

echo $_GET['string']; // "+"

It is only the raw HTTP request that contains the url encoded data.

For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING']. For a urlencoded POST, file_get_contents('php://stdin')

NB:

decode() only works for single byte encoded characters. It will not work for the full UTF-8 range.

eg:

text = "\u0100"; // A
// incorrect
escape(text); // %u0100 
// correct
encodeURIComponent(text); // "%C4%80"

Note: "%C4%80" is equivalent to: escape('\xc4\x80')

Which is the byte sequence (\xc4\x80) that represents A in UTF-8. So if you use encodeURIComponent() your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.

Python: Is there an equivalent of mid, right, and left from BASIC?

These work great for reading left / right "n" characters from a string, but, at least with BBC BASIC, the LEFT$() and RIGHT$() functions allowed you to change the left / right "n" characters too...

E.g.:

10 a$="00000"
20 RIGHT$(a$,3)="ABC"
30 PRINT a$

Would produce:

00ABC

Edit : Since writing this, I've come up with my own solution...

def left(s, amount = 1, substring = ""):
    if (substring == ""):
        return s[:amount]
    else:
        if (len(substring) > amount):
            substring = substring[:amount]
        return substring + s[:-amount]

def right(s, amount = 1, substring = ""):
    if (substring == ""):
        return s[-amount:]
    else:
        if (len(substring) > amount):
            substring = substring[:amount]
        return s[:-amount] + substring

To return n characters you'd call

substring = left(string,<n>)

Where defaults to 1 if not supplied. The same is true for right()

To change the left or right n characters of a string you'd call

newstring = left(string,<n>,substring)

This would take the first n characters of substring and overwrite the first n characters of string, returning the result in newstring. The same works for right().

Is there a way to 'pretty' print MongoDB shell output to a file?

Using print and JSON.stringify you can simply produce a valid JSON result.
Use --quiet flag to filter shell noise from the output.
Use --norc flag to avoid .mongorc.js evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output) Use DBQuery.shellBatchSize = ? replacing ? with the limit of the actual result to avoid paging.

And finally, use tee to pipe the terminal output to a file:

// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json

// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
  print(JSON.stringify(data, null, 2));
}

toPrint(
  db.getCollection('myCollection').find().toArray()
);

Hope this helps!

Javascript: Extend a Function

Another option could be:

var initial = function() {
    console.log( 'initial function!' );
}

var iWantToExecuteThisOneToo = function () {
    console.log( 'the other function that i wanted to execute!' );
}

function extendFunction( oldOne, newOne ) {
    return (function() {
        oldOne();
        newOne();
    })();
}

var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );

Implement an input with a mask

You can achieve this also by using JavaScripts's native method. Its pretty simple and doesn't require any extra library to import.

<input type="text" name="date" placeholder="yyyy-mm-dd" onkeyup="
  var date = this.value;
  if (date.match(/^\d{4}$/) !== null) {
     this.value = date + '-';
  } else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
     this.value = date + '-';
  }" maxlength="10">

Java balanced expressions check {[()]}

import java.util.Objects;
import java.util.Stack;

public class BalanceBrackets {

    public static void main(String[] args) {
        String input="(a{[d]}b)";
        System.out.println(isBalance(input));  ;
    }

    private static boolean isBalance(String input) {
        Stack <Character> stackFixLength = new Stack();

        if(input == null || input.length() < 2) {
            throw  new IllegalArgumentException("in-valid arguments");
        }

        for (int i = 0; i < input.length(); i++) {

            if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
                stackFixLength.push(input.charAt(i));
            }

            if (input.charAt(i) == ')' || input.charAt(i) == '}' || input.charAt(i) == ']') {

                if(stackFixLength.empty()) return false;

                char b = stackFixLength.pop();

                if (input.charAt(i) == ')' && b == '(' || input.charAt(i) == '}' && b == '{' || input.charAt(i) == ']' && b == '[') {
                    continue;
                } else {
                    return false;
                }
            }
        }

        return stackFixLength.isEmpty();
    }
}

mongodb service is not starting up

Removing the .lock file and reinstalling did not solve the issue on my machine (Ubuntu 19.10). The problem was that after unexpected shutdown, the MongoDB sock does not belong to the MongoDB group and user anymore.

So, I follow the steps below:

  1. cd /tmp
  2. ls *.sock
  3. Change the user:group permission:

    chown mongodb:mongodb <YOUR_SOCK>
    
  4. sudo systemctl start mongod

  5. sudo systemctl status mongod

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:

Quote:

JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons.

Another quote: for the code

var a
a
=
3 console.log(a)

JavaScript does not treat the second line break as a semicolon because it can continue parsing the longer statement a = 3;

and:

two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line. The first exception involves the return, break, and continue statements

... If a line break appears after any of these words ... JavaScript will always interpret that line break as a semicolon.

... The second exception involves the ++ and -- operators ... If you want to use either of these operators as postfix operators, they must appear on the same line as the expression they apply to. Otherwise, the line break will be treated as a semicolon, and the ++ or -- will be parsed as a prefix operator applied to the code that follows. Consider this code, for example:

x 
++ 
y

It is parsed as x; ++y;, not as x++; y

So I think to simplify it, that means:

In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like return, break, continue, and (2) if it sees ++ or -- on a new line, then it will add the ; at the end of the previous line.

The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.

With the above said, that means for return with a line break, the JavaScript interpreter will insert a ;

(quoted again: If a line break appears after any of these words [such as return] ... JavaScript will always interpret that line break as a semicolon)

and due to this reason, the classic example of

return
{ 
  foo: 1
}

will not work as expected, because the JavaScript interpreter will treat it as:

return;   // returning nothing
{
  foo: 1
}

There has to be no line-break immediately after the return:

return { 
  foo: 1
}

for it to work properly. And you may insert a ; yourself if you were to follow the rule of using a ; after any statement:

return { 
  foo: 1
};

Unfamiliar symbol in algorithm: what does ? mean?

In math, ? means FOR ALL.

Unicode character (\u2200, ?).

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

How to get a password from a shell script without echoing

I found to be the the askpass command useful

password=$(/lib/cryptsetup/askpass "Give a password")

Every input character is replaced by *. See: Give a password ****

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Any way you mentioned /root/.m2/settings.xml.

But in my Case i missed the settings.xml to configure in the maven preferences. enter image description here so that maven will search for the relative_path pom.xml from the remote_repository which is configured in settings.xml

How to get POSTed JSON in Flask?

The following codes can be used:

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
  content = request.json['text']
  print content
  return uuid

Here is a screenshot of me getting the json data:

enter image description here

You can see that what is returned is a dictionary type of data.

Printing everything except the first field with awk

Yet another way...

...this rejoins the fields 2 thru NF with the FS and outputs one line per line of input

awk '{for (i=2;i<=NF;i++){printf $i; if (i < NF) {printf FS};}printf RS}'

I use this with git to see what files have been modified in my working dir:

git diff| \
    grep '\-\-git'| \
    awk '{print$NF}'| \
    awk -F"/" '{for (i=2;i<=NF;i++){printf $i; if (i < NF) {printf FS};}printf RS}'

Pass props to parent component in React.js

This is an example without using the onClick event. I simply pass a callback function to the child by props. With that callback the child call also send data back. I was inspired by the examples in the docs.

Small example (this is in a tsx files, so props and states must be declared fully, I deleted some logic out of the components, so it is less code).

*Update: Important is to bind this to the callback, otherwise the callback has the scope of the child and not the parent. Only problem: it is the "old" parent...

SymptomChoser is the parent:

interface SymptomChooserState {
  // true when a symptom was pressed can now add more detail
  isInDetailMode: boolean
  // since when user has this symptoms
  sinceDate: Date,
}

class SymptomChooser extends Component<{}, SymptomChooserState> {

  state = {
    isInDetailMode: false,
    sinceDate: new Date()
  }

  helloParent(symptom: Symptom) {
    console.log("This is parent of: ", symptom.props.name);
    // TODO enable detail mode
  }

  render() {
    return (
      <View>
        <Symptom name='Fieber' callback={this.helloParent.bind(this)} />
      </View>
    );
  }
}

Symptom is the child (in the props of the child I declared the callback function, in the function selectedSymptom the callback is called):

interface SymptomProps {
  // name of the symptom
  name: string,
  // callback to notify SymptomChooser about selected Symptom.
  callback: (symptom: Symptom) => void
}

class Symptom extends Component<SymptomProps, SymptomState>{

  state = {
    isSelected: false,
    severity: 0
  }

  selectedSymptom() {
    this.setState({ isSelected: true });
    this.props.callback(this);
  }

  render() {
    return (
      // symptom is not selected
      <Button
        style={[AppStyle.button]}
        onPress={this.selectedSymptom.bind(this)}>
        <Text style={[AppStyle.textButton]}>{this.props.name}</Text>
      </Button>
    );
  }
}

Get Selected Item Using Checkbox in Listview

Assuming you want to get items of row whose check boxes are checked at the click of a button. Assumption based on your title "Get Selected Item Using Checkbox in Listview when I click a Button".

Try the below. Make only changes as below. Keep the rest the same.

Explanation and discussion on the topic @

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

MainActivity.java

public class MainActivity extends Activity {
     AppInfoAdapter adapter ;
     AppInfo app_info[] ;
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            final ListView listApplication = (ListView)findViewById(R.id.listApplication);
            Button b= (Button) findViewById(R.id.button1);
            b.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    StringBuilder result = new StringBuilder();
                    for(int i=0;i<adapter.mCheckStates.size();i++)
                    {
                        if(adapter.mCheckStates.get(i)==true)
                        {

                                           result.append(app_info[i].applicationName);
                            result.append("\n");
                        }

                    }
                    Toast.makeText(MainActivity.this, result, 1000).show();
                }

            });

            ApplicationInfo applicationInfo = getApplicationInfo();
            PackageManager pm = getPackageManager();
            List<PackageInfo> pInfo = new ArrayList<PackageInfo>();
            pInfo.addAll(pm.getInstalledPackages(0));
            app_info = new AppInfo[pInfo.size()];

            int counter = 0;
            for(PackageInfo item: pInfo){
                try{

                    applicationInfo = pm.getApplicationInfo(item.packageName, 1);

                    app_info[counter] = new AppInfo(pm.getApplicationIcon(applicationInfo), 
                            String.valueOf(pm.getApplicationLabel(applicationInfo)));

                    System.out.println(counter);

                }
                catch(Exception e){
                     System.out.println(e.getMessage());
                }

                counter++;
            }

           adapter = new AppInfoAdapter(this, R.layout.listview_item_row, app_info);
            listApplication.setAdapter(adapter);

        }
}

activity_main.xml ListView with button at the buton

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:layout_width="fill_parent"
        android:id="@+id/listApplication"
        android:layout_height="fill_parent"
        android:layout_above="@+id/button1"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

</RelativeLayout>

AppInfoAdapter

public class AppInfoAdapter extends ArrayAdapter<AppInfo> implements CompoundButton.OnCheckedChangeListener
{  SparseBooleanArray mCheckStates; 

    Context context;
    int layoutResourceId;
    AppInfo  data[] = null;

    public AppInfoAdapter(Context context, int layoutResourceId, AppInfo[] data){
        super(context, layoutResourceId,data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
        mCheckStates = new SparseBooleanArray(data.length);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        View row = convertView;
        AppInfoHolder holder= null;

        if (row == null){

            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new AppInfoHolder();

            holder.imgIcon = (ImageView) row.findViewById(R.id.imageView1);
            holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
            holder.chkSelect = (CheckBox) row.findViewById(R.id.checkBox1);

            row.setTag(holder);

        }
        else{
            holder = (AppInfoHolder)row.getTag();
        }


        AppInfo appinfo = data[position];
        holder.txtTitle.setText(appinfo.applicationName);
        holder.imgIcon.setImageDrawable(appinfo.icon);
       // holder.chkSelect.setChecked(true);
        holder.chkSelect.setTag(position);
        holder.chkSelect.setChecked(mCheckStates.get(position, false));
        holder.chkSelect.setOnCheckedChangeListener(this);
        return row;

    }
    public boolean isChecked(int position) {
        return mCheckStates.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mCheckStates.put(position, isChecked);

    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));

    }
@Override
public void onCheckedChanged(CompoundButton buttonView,
        boolean isChecked) {

     mCheckStates.put((Integer) buttonView.getTag(), isChecked);    

}
static class AppInfoHolder
{
    ImageView imgIcon;
    TextView txtTitle;
    CheckBox chkSelect;

}
}

Here's the snap shot

enter image description here

How to change indentation in Visual Studio Code?

In the toolbar in the bottom right corner you will see a item that looks like the following: enter image description here After clicking on it you will get the option to indent using either spaces or tabs. After selecting your indent type you will then have the option to change how big an indent is. In the case of the example above, indentation is set to 4 space characters per indent. If tab is selected as your indentation character then you will see Tab Size instead of Spaces

If you want to have this apply to all files and not on an idividual file basis, override the Editor: Tab Size and Editor: Insert Spaces settings in either User Settings or Workspace Settings depending on your needs

Edit 1

To get to your user or workspace settings go to Preferences -> Settings. Verify that you are on the User or Workspace tab depending on your needs and use the search bar to locate the settings. You may also want to disable Editor: Detect Indentation as this setting will override what you set for Editor: Insert Spaces and Editor: Tab Size when it is enabled

How to add a .dll reference to a project in Visual Studio

For Visual Studio 2019 you may not find Project -> Add Reference option. Use Project -> Add Project Reference. Then in dialog window navigate to Browse tab and use Browse to find and attach your dll.

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

JAXB: How to ignore namespace during unmarshalling XML document?

I have encoding problems with XMLFilter solution, so I made XMLStreamReader to ignore namespaces:

class XMLReaderWithoutNamespace extends StreamReaderDelegate {
    public XMLReaderWithoutNamespace(XMLStreamReader reader) {
      super(reader);
    }
    @Override
    public String getAttributeNamespace(int arg0) {
      return "";
    }
    @Override
    public String getNamespaceURI() {
      return "";
    }
}

InputStream is = new FileInputStream(name);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
Unmarshaller um = jc.createUnmarshaller();
Object res = um.unmarshal(xr);

Using Sockets to send and receive data

the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".

Good ways to manage a changelog using git?

For a GNU style changelog, I've cooked the function

gnuc() {
  {
    printf "$(date "+%Y-%m-%d")  John Doe  <[email protected]>\n\n"
    git diff-tree --no-commit-id --name-only -r HEAD | sed 's/^/\t* /'
  } | tee /dev/tty | xsel -b
}

With this:

  • I commit my changes periodically to backup and rebase them before doing the final edit to the ChangeLog
  • then run: gnuc

and now my clipboard contains something like:

2015-07-24  John Doe  <[email protected]>

        * gdb/python/py-linetable.c (): .
        * gdb/python/py-symtab.c (): .

Then I use the clipboard as a starting point to update the ChangeLog.

It is not perfect (e.g. files should be relative to their ChangeLog path, so python/py-symtab.c without gdb/ since I will edit the gdb/ChangeLog), but is a good starting point.

More advanced scripts:

I have to agree with Tromey though: duplicating git commit data in the ChangeLog is useless.

If you are going to make a changelog, make it a good summary of what is going on, possibly as specified at http://keepachangelog.com/

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

How to validate IP address in Python?

def is_valid_ip(ip):
    """Validates IP addresses.
    """
    return is_valid_ipv4(ip) or is_valid_ipv6(ip)

IPv4:

def is_valid_ipv4(ip):
    """Validates IPv4 addresses.
    """
    pattern = re.compile(r"""
        ^
        (?:
          # Dotted variants:
          (?:
            # Decimal 1-255 (no leading 0's)
            [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
          |
            0x0*[0-9a-f]{1,2}  # Hexadecimal 0x0 - 0xFF (possible leading 0's)
          |
            0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's)
          )
          (?:                  # Repeat 0-3 times, separated by a dot
            \.
            (?:
              [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
            |
              0x0*[0-9a-f]{1,2}
            |
              0+[1-3]?[0-7]{0,2}
            )
          ){0,3}
        |
          0x0*[0-9a-f]{1,8}    # Hexadecimal notation, 0x0 - 0xffffffff
        |
          0+[0-3]?[0-7]{0,10}  # Octal notation, 0 - 037777777777
        |
          # Decimal notation, 1-4294967295:
          429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}|
          42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}|
          4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8}
        )
        $
    """, re.VERBOSE | re.IGNORECASE)
    return pattern.match(ip) is not None

IPv6:

def is_valid_ipv6(ip):
    """Validates IPv6 addresses.
    """
    pattern = re.compile(r"""
        ^
        \s*                         # Leading whitespace
        (?!.*::.*::)                # Only a single whildcard allowed
        (?:(?!:)|:(?=:))            # Colon iff it would be part of a wildcard
        (?:                         # Repeat 6 times:
            [0-9a-f]{0,4}           #   A group of at most four hexadecimal digits
            (?:(?<=::)|(?<!::):)    #   Colon unless preceeded by wildcard
        ){6}                        #
        (?:                         # Either
            [0-9a-f]{0,4}           #   Another group
            (?:(?<=::)|(?<!::):)    #   Colon unless preceeded by wildcard
            [0-9a-f]{0,4}           #   Last group
            (?: (?<=::)             #   Colon iff preceeded by exacly one colon
             |  (?<!:)              #
             |  (?<=:) (?<!::) :    #
             )                      # OR
         |                          #   A v4 address with NO leading zeros 
            (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
            (?: \.
                (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
            ){3}
        )
        \s*                         # Trailing whitespace
        $
    """, re.VERBOSE | re.IGNORECASE | re.DOTALL)
    return pattern.match(ip) is not None

The IPv6 version uses "(?:(?<=::)|(?<!::):)", which could be replaced with "(?(?<!::):)" on regex engines that support conditionals with look-arounds. (i.e. PCRE, .NET)

Edit:

  • Dropped the native variant.
  • Expanded the regex to comply with the RFC.
  • Added another regex for IPv6 addresses.

Edit2:

I found some links discussing how to parse IPv6 addresses with regex:

Edit3:

Finally managed to write a pattern that passes all tests, and that I am also happy with.

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

check if a number already exist in a list in python

If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

s = set()
if number1 not in s:
  s.add(number1)
if number2 not in s:
  s.add(number2)
...
s = sorted(s)  #Now a list in ascending order

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

What is the difference between dynamic and static polymorphism in Java?

Method Overloading is known as Static Polymorphism and also Known as Compile Time Polymorphism or Static Binding because overloaded method calls get resolved at compile time by the compiler on the basis of the argument list and the reference on which we are calling the method.

And Method Overriding is known as Dynamic Polymorphism or simple Polymorphism or Runtime Method Dispatch or Dynamic Binding because overridden method call get resolved at runtime.

In order to understand why this is so let's take an example of Mammal and Human class

class Mammal {
    public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
}

class Human extends Mammal {

    @Override
    public void speak() { System.out.println("Hello"); }

    public void speak(String language) {
        if (language.equals("Hindi")) System.out.println("Namaste");
        else System.out.println("Hello");
    }

}

I have included output as well as bytecode of in below lines of code

Mammal anyMammal = new Mammal();
anyMammal.speak();  // Output - ohlllalalalalalaoaoaoa
// 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

Mammal humanMammal = new Human();
humanMammal.speak(); // Output - Hello
// 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

Human human = new Human();
human.speak(); // Output - Hello
// 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V

human.speak("Hindi"); // Output - Namaste
// 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V

And by looking at above code we can see that the bytecodes of humanMammal.speak() , human.speak() and human.speak("Hindi") are totally different because the compiler is able to differentiate between them based on the argument list and class reference. And this is why Method Overloading is known as Static Polymorphism.

But bytecode for anyMammal.speak() and humanMammal.speak() is same because according to compiler both methods are called on Mammal reference but the output for both method calls is different because at runtime JVM knows what object a reference is holding and JVM calls the method on the object and this is why Method Overriding is known as Dynamic Polymorphism.

So from above code and bytecode, it is clear that during compilation phase calling method is considered from the reference type. But at execution time method will be called from the object which the reference is holding.

If you want to know more about this you can read more on How Does JVM Handle Method Overloading and Overriding Internally.

How to install numpy on windows using pip install?

Install miniconda (here)

After installed, open Anaconda Prompt (search this in Start Menu)

Write:

pip install numpy

After installed, test:

import numpy as np

Formatting a Date String in React Native

function getParsedDate(date){
  date = String(date).split(' ');
  var days = String(date[0]).split('-');
  var hours = String(date[1]).split(':');
  return [parseInt(days[0]), parseInt(days[1])-1, parseInt(days[2]), parseInt(hours[0]), parseInt(hours[1]), parseInt(hours[2])];
}
var date = new Date(...getParsedDate('2016-01-04 10:34:23'));
console.log(date);

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

... as described in the resource:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

svn cleanup: sqlite: database disk image is malformed

Marked answer might be the correct one, according to subversion cleanup. But the error is definitely a generic one, which led me here, this question page.

Our project has the dependency System.Data.SQLite and the error message was the same:

database disk image is malformed

In my case, I've executed following check script and the followings via SQLiteStudio 3.1.1.

pragma integrity_check

(I don't have any idea if these statistics would help, but I'm going to share them anyway...)

The DataBase file is being used on everyday usage for 1.5 year, via the connection journal mode on Memory, and was about 750 MB large. There were approximately 140K records per table and 6 tables was this large.

After the execution of Integrity Check script, 11 rows was returned after 30 minutes of execution time.

wrong # of entries in index sqlite_autoindex_MyTableName_1
wrong # of entries in index MyOtherTableAndOrIndexName_1
wrong # of entries in index sqlite_autoindex_MyOtherTableAndOrIndexName_2
etc...

All the results were about the indexes. Following-up the re-building each indexes, my problem was resolved.

reindex sqlite_autoindex_MyTableName_1;
reindex MyOtherTableAndOrIndexName_1;
reindex sqlite_autoindex_MyOtherTableAndOrIndexName_2;

After re-indexing, the integrity check resulted "ok".

I've got this error last year, and I was restored the DB from the backup, and then re-committed all the changes, which was a real nightmare...

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

Here's what Oracle's documentation has to say:

By default the heap dump is created in a file called java_pid.hprof in the working directory of the VM, as in the example above. You can specify an alternative file name or directory with the -XX:HeapDumpPath= option. For example -XX:HeapDumpPath=/disk2/dumps will cause the heap dump to be generated in the /disk2/dumps directory.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How to get autocomplete in jupyter notebook without using tab?

There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.

In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

Button inside of anchor link works in Firefox but not in Internet Explorer?

You can't have a <button> inside an <a> element. As W3's content model description for the <a> element states:

"there must be no interactive content descendant."

(a <button> is considered interactive content)

To get the effect you're looking for, you can ditch the <a> tags and add a simple event handler to each button which navigates the browser to the desired location, e.g.

<input type="button" value="stackoverflow.com" onClick="javascript:location.href = 'http://stackoverflow.com';" />

Please consider not doing this, however; there's a reason regular links work as they do:

  • Users can instantly recognize links and understand that they navigate to other pages
  • Search engines can identify them as links and follow them
  • Screen readers can identify them as links and advise their users appropriately

You also add a completely unnecessary requirement to have JavaScript enabled just to perform a basic navigation; this is such a fundamental aspect of the web that I would consider such a dependency as unacceptable.

You can style your links, if desired, using a background image or background color, border and other techniques, so that they look like buttons, but under the covers, they should be ordinary links.

Define an alias in fish shell

This is how I define a new function foo, run it, and save it persistently.

sthorne@pearl~> function foo
                    echo 'foo was here'
                end
sthorne@pearl~> foo
foo was here
sthorne@pearl~> funcsave foo

Why do you use typedef when declaring an enum in C++?

You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.

typedef enum MyEnum { 
  //...
} MyEnum;

allowed functions taking a parameter of the enum to be defined as

void f( MyEnum x )

instead of the longer

void f( enum MyEnum x )

Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.

In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.

// C++
enum MyEnum {
   // ...
};
void f( MyEnum x ); // Correct C++, Error in C

undefined reference to 'std::cout'

Assuming code.cpp is the source code, the following will not throw errors:

make code
./code

Here the first command compiles the code and creates an executable with the same name, and the second command runs it. There is no need to specify g++ keyword in this case.

Does hosts file exist on the iPhone? How to change it?

I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).

  • Installed OpenSSH onto iPhone via Cydia
  • Using a SFTP client like FileZilla on my computer, I connected to my iPhone
    • Address: [use your phone's IP address or hostname, eg. simophone.local]
    • Username: root
    • Password: alpine
  • Located the /etc/hosts file
  • Made a backup on my computer (in case I want to revert my changes later)
  • Edited the hosts file in a decent text editor (such as Notepad++). See here for an explanation of the hosts file.
  • Uploaded the changes, overwriting the hosts file on the iPhone

The phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.

Simon.

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

How to run Spring Boot web application in Eclipse itself?

This answer is late, but I was having the same issue. I found something that works.
In eclipse Project Explorer, right click the project name -> select "Run As" -> "Maven Build..."
In the goals, enter spring-boot:run then click Run button.

I have the STS plug-in (i.e. SpringSource Tool Suite), so on some projects I will get a "Spring Boot App" option under Run As. But, it doesn't always show up for some reason. I use the above workaround for those.
Here is a reference that explains how to run Spring boot apps:
Spring boot tutorial

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

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

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

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

The usual way to do this is to set the Form's AcceptButton to the button you want "clicked". You can do this either in the VS designer or in code and the AcceptButton can be changed at any time.

This may or may not be applicable to your situation, but I have used this in conjunction with GotFocus events for different TextBoxes on my form to enable different behavior based on where the user hit Enter. For example:

void TextBox1_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox1;
}

void TextBox2_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox2;
}

One thing to be careful of when using this method is that you don't leave the AcceptButton set to ProcessTextBox1 when TextBox3 becomes focused. I would recommend using either the LostFocus event on the TextBoxes that set the AcceptButton, or create a GotFocus method that all of the controls that don't use a specific AcceptButton call.

Getting output of system() calls in Ruby

I didn't find this one here so adding it, I had some issues getting the full output.

You can redirect STDERR to STDOUT if you want to capture STDERR using backtick.

output = `grep hosts /private/etc/* 2>&1`

source: http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html

How to clear or stop timeInterval in angularjs?

When you want to create interval store promise to variable:

var p = $interval(function() { ... },1000);

And when you want to stop / clear the interval simply use:

$interval.cancel(p);

How to use XPath contains() here?

I already gave my +1 to Jeff Yates' solution.

Here is a quick explanation why your approach does not work. This:

//ul[@class='featureList' and contains(li, 'Model')]

encounters a limitation of the contains() function (or any other string function in XPath, for that matter).

The first argument is supposed to be a string. If you feed it a node list (giving it "li" does that), a conversion to string must take place. But this conversion is done for the first node in the list only.

In your case the first node in the list is <li><b>Type:</b> Clip Fan</li> (converted to a string: "Type: Clip Fan") which means that this:

//ul[@class='featureList' and contains(li, 'Type')]

would actually select a node!

SOAP vs REST (differences)

Addition for:

++ A mistake that’s often made when approaching REST is to think of it as “web services with URLs”—to think of REST as another remote procedure call (RPC) mechanism, like SOAP, but invoked through plain HTTP URLs and without SOAP’s hefty XML namespaces.

++ On the contrary, REST has little to do with RPC. Whereas RPC is service oriented and focused on actions and verbs, REST is resource oriented, emphasizing the things and nouns that comprise an application.

change Oracle user account status from EXPIRE(GRACE) to OPEN

Compilation from jonearles' answer, http://kishantha.blogspot.com/2010/03/oracle-enterprise-manager-console.html and http://blog.flimatech.com/2011/07/17/changing-oracle-password-in-11g-using-alter-user-identified-by-values/ (Oracle 11g):

To stop this happening in the future do the following.

  • Login to sqlplus as sysdba -> sqlplus "/as sysdba"
  • Execute ->ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED PASSWORD_LIFE_TIME UNLIMITED;

To reset users' status, run the query:

select
'alter user ' || su.name || ' identified by values'
   || ' ''' || spare4 || ';'    || su.password || ''';'
from sys.user$ su 
join dba_users du on ACCOUNT_STATUS like 'EXPIRED%' and su.name = du.username;

and execute some or all of the result set.

How to set RelativeLayout layout params in code not in xml?

Just a basic example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

As you can see, this is what you have to do:

  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

Extracting extension from filename in Python

worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.

os.path.splitext(filename)[1][1:].strip().lower()

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Found this on a different forum

If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.

What you are doing is passing 664 which in octal is 1230

In your case you would need

os.chmod("/tmp/test_file", 436)

[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666

How do I turn off autocommit for a MySQL client?

You do this in 3 different ways:

  1. Before you do an INSERT, always issue a BEGIN; statement. This will turn off autocommits. You will need to do a COMMIT; once you want your data to be persisted in the database.

  2. Use autocommit=0; every time you instantiate a database connection.

  3. For a global setting, add a autocommit=0 variable in your my.cnf configuration file in MySQL.

How can I perform a short delay in C# without using sleep?

By adding using System.Timers; to your program you can use this function:

private static void delay(int Time_delay)
{
   int i=0;
  //  ameTir = new System.Timers.Timer();
    _delayTimer = new System.Timers.Timer();
    _delayTimer.Interval = Time_delay;
    _delayTimer.AutoReset = false; //so that it only calls the method once
    _delayTimer.Elapsed += (s, args) => i = 1;
    _delayTimer.Start();
    while (i == 0) { };
}

Delay is a function and can be used like:

delay(5000);

Android Split string

.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Also, this came from: Android split not working correctly

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

how do you pass images (bitmaps) between android activities using bundles?

Write this code from where you want to Intent into next activity.

    yourimageView.setDrawingCacheEnabled(true); 
    Drawable drawable = ((ImageView)view).getDrawable(); 
    Bitmap bitmap = imageView.getDrawingCache();
    Intent intent = new Intent(getBaseContext(), NextActivity.class);
    intent.putExtra("Image", imageBitmap);

In onCreate Function of NextActivity.class

Bitmap hotel_image;
Intent intent = getIntent();
hotel_image= intent.getParcelableExtra("Image");

How to change value of process.env.PORT in node.js?

use the below command to set the port number in node process while running node JS programme:

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

How can I export Excel files using JavaScript?

I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info

How to configure Eclipse build path to use Maven dependencies?

Right click on the project Configure > convert to Maven project

Then you can see all the Maven related Menu for you project.

Fixed header, footer with scrollable content

Here's what worked for me. I had to add a margin-bottom so the footer wouldn't eat up my content:

header {
  height: 20px;
  background-color: #1d0d0a;
  position: fixed;
  top: 0;
  width: 100%;
  overflow: hide;
}

content {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 100px;
  margin-top: 20px;
  overflow: auto;
  width: 80%;
}

footer {
  position: fixed;
  bottom: 0px;
  overflow: hide;
  width: 100%;
}

In C can a long printf statement be broken up into multiple lines?

Just some other formatting options:

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
        a,        b,        c,        d);

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
              a,        b,        c,            d);

printf("name: %s\t"      "args: %s\t"      "value %d\t"      "arraysize %d\n", 
        very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d);

You can add variations on the theme. The idea is that the printf() conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").

nginx: send all requests to a single html page

Using just try_files didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.

The Nginx docs had some additional details:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

So I ended up using the following:

root /var/www/mysite;

location / {
    try_files $uri /base.html;
}

location = /base.html {
    expires 30s;
}

java.lang.IllegalStateException: Fragment not attached to Activity

I Found Very Simple Solution isAdded() method which is one of the fragment method to identify that this current fragment is attached to its Activity or not.

we can use this like everywhere in fragment class like:

if(isAdded())
{

// using this method, we can do whatever we want which will prevent   **java.lang.IllegalStateException: Fragment not attached to Activity** exception.

}

What is the correct way to do a CSS Wrapper?

Most basic example (live example here):

CSS:

    #wrapper {
        width: 500px;
        margin: 0 auto;
    }

HTML:

    <body>
        <div id="wrapper">
            Piece of text inside a 500px width div centered on the page
        </div>
    </body>

How the principle works:

Create your wrapper and assign it a certain width. Then apply an automatic horizontal margin to it by using margin: 0 auto; or margin-left: auto; margin-right: auto;. The automatic margins make sure your element is centered.

PHP removing a character in a string

While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).

$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
  if ($urlString[$i] === '?') {
    $urlString[$i+1] = '';
    break;
  }
}

Weird, I know.

How to disable sort in DataGridView?

You can disable it in the ColumnAdded event:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    dataGridView1.Columns[e.Column.Index].SortMode = DataGridViewColumnSortMode.NotSortable;
}

$location / switching between html5 and hashbang mode / link rewriting

This took me a while to figure out so this is how I got it working - Angular WebAPI ASP Routing without the # for SEO

  1. add to Index.html - base href="/">
  2. Add $locationProvider.html5Mode(true); to app.config

  3. I needed a certain controller (which was in the home controller) to be ignored for uploading images so I added that rule to RouteConfig

         routes.MapRoute(
            name: "Default2",
            url: "Home/{*.}",
            defaults: new { controller = "Home", action = "SaveImage" }
        );
    
  4. In Global.asax add the following - making sure to ignore api and image upload paths let them function as normal otherwise reroute everything else.

     private const string ROOT_DOCUMENT = "/Index.html";
    
    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        var path = Request.Url.AbsolutePath;
        var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
        var isImageUpload = path.StartsWith("/home", StringComparison.InvariantCultureIgnoreCase);
    
        if (isApi || isImageUpload)
            return;
    
        string url = Request.Url.LocalPath;
        if (!System.IO.File.Exists(Context.Server.MapPath(url)))
            Context.RewritePath(ROOT_DOCUMENT);
    }
    
  5. Make sure to use $location.url('/XXX') and not window.location ... to redirect

  6. Reference the CSS files with absolute path

and not

<link href="app/content/bootstrapwc.css" rel="stylesheet" />

Final note - doing it this way gave me full control and I did not need to do anything to the web config.

Hope this helps as this took me a while to figure out.

How to restore the dump into your running mongodb

I have been through a lot of trouble so I came up with my own solution, I created this script, just set the path inside script and db name and run it, it will do the trick

#!/bin/bash

FILES= #absolute or relative path to dump directory
DB=`db` #db name
for file in $FILES
do

    name=$(basename $file)
    collection="${name%.*}"
    echo `mongoimport --db "$DB" --file "$name" --collection "$collection"`

done

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

Try to add a s after http

Like this:

http://integration.jsite.com/data/vis => https://integration.jsite.com/data/vis

It works for me

Unable to add window -- token null is not valid; is your activity running?

I had the same problem as you, it looks like you used the tutorial from http://www.piwai.info/chatheads-basics like I did. The problem is that you cannot reliably pass the current activity to the popup window, because you have no control over the current activity. It looks like there might be a unreliable way to get the current activity, but I don't recommend that.

The way I fixed it for my app was to not use the popup window, but instead make my own through the window manager.

private void showCustomPopupMenu()
    {
                windowManager2 = (WindowManager)getSystemService(WINDOW_SERVICE);
                LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view=layoutInflater.inflate(R.layout.xxact_copy_popupmenu, null);
                params=new WindowManager.LayoutParams(
                        WindowManager.LayoutParams.WRAP_CONTENT,
                        WindowManager.LayoutParams.WRAP_CONTENT,
                        WindowManager.LayoutParams.TYPE_PHONE,
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        PixelFormat.TRANSLUCENT);

                params.gravity=Gravity.CENTER|Gravity.CENTER;
                params.x=0;
                params.y=0;
                windowManager2.addView(view, params);  
    }

If you want this to look like a popup window, just add a transparent gray view as the background and add a onClickListener to it to remove the view from the windowManager object.

I know this isn't as convenient as a popup, but from my experience, it is the most reliable way.

and don't forget to add permission in your manifest file

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

PHP Adding 15 minutes to Time value

Quite easy

$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));

PHP: if !empty & empty

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}

Matplotlib color according to class labels

The accepted answer has it spot on, but if you might want to specify which class label should be assigned to a specific color or label you could do the following. I did a little label gymnastics with the colorbar, but making the plot itself reduces to a nice one-liner. This works great for plotting the results from classifications done with sklearn. Each label matches a (x,y) coordinate.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = [4,8,12,16,1,4,9,16]
y = [1,4,9,16,4,8,12,3]
label = [0,1,2,3,0,1,2,3]
colors = ['red','green','blue','purple']

fig = plt.figure(figsize=(8,8))
plt.scatter(x, y, c=label, cmap=matplotlib.colors.ListedColormap(colors))

cb = plt.colorbar()
loc = np.arange(0,max(label),max(label)/float(len(colors)))
cb.set_ticks(loc)
cb.set_ticklabels(colors)

Scatter plot color labels

Using a slightly modified version of this answer, one can generalise the above for N colors as follows:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

N = 23 # Number of labels

# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))
# define the data
x = np.random.rand(1000)
y = np.random.rand(1000)
tag = np.random.randint(0,N,1000) # Tag each point with a corresponding label    

# define the colormap
cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0,N,N+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x,y,c=tag,s=np.random.randint(100,500,N),cmap=cmap,     norm=norm)
# create the colorbar
cb = plt.colorbar(scat, spacing='proportional',ticks=bounds)
cb.set_label('Custom cbar')
ax.set_title('Discrete color mappings')
plt.show()

Which gives:

enter image description here

Removing double quotes from variables in batch file creates problems with CMD environment

I learned from this link, if you are using XP or greater that this will simply work by itself:

SET params = %~1

I could not get any of the other solutions here to work on Windows 7.

To iterate over them, I did this:

FOR %%A IN (%params%) DO (    
   ECHO %%A    
)

Note: You will only get double quotes if you pass in arguments separated by a space typically.

How to read a file without newlines?

Try this:

u=open("url.txt","r")  
url=u.read().replace('\n','')  
print(url)  

python - if not in list

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)

HTML code for an apostrophe

If you are looking for single quote, it is

&#39;

Wrap a text within only two lines inside div

See http://jsfiddle.net/SWcCt/.

Just set a line-height the half of height:

line-height:20px;
height:40px;

Of course, in order to make text-overflow: ellipsis work you also need:

overflow:hidden;
white-space: pre;

Sass .scss: Nesting and multiple classes?

You can use the parent selector reference &, it will be replaced by the parent selector after compilation:

For your example:

.container {
    background:red;
    &.desc{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
.container.desc {
    background: blue;
}

The & will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &.

This notation is most often used to write pseudo-elements and -classes:

.element{
    &:hover{ ... }
    &:nth-child(1){ ... }
}

However, you can place the & at virtually any position you like*, so the following is possible too:

.container {
    background:red;
    #id &{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
#id .container {
    background: blue;
}

However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.

*: No other characters than whitespaces are allowed in front of the &. So you cannot do a direct concatenation of selector+& - #id& would throw an error.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

Your persistence.xml is not valid and the EntityManagerFactory can't get created. It should be:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
  <persistence-unit name="customerManager" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>Customer</class>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
      <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.connection.username" value="root"/>
      <property name="hibernate.connection.password" value="1234"/>
      <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/general"/>
      <property name="hibernate.max_fetch_depth" value="3"/>
    </properties>
  </persistence-unit>
</persistence>

(Note how the <property> elements are closed, they shouldn't be nested)

Update: I went through the tutorial and you will also have to change the Id generation strategy when using MySQL (as MySQL doesn't support sequences). I suggest using the AUTO strategy (defaults to IDENTITY with MySQL). To do so, remove the SequenceGenerator annotation and change the code like this:

@Entity
@Table(name="TAB_CUSTOMER")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="CUSTOMER_ID", precision=0)
    private Long customerId = null;

   ...
}

This should help.

PS: you should also provide a log4j.properties as suggested.

Remove 'standalone="yes"' from generated XML

If you make document dependent on DOCTYPE (e.g. use named entities) then it will stop being standalone, thus standalone="yes" won't be allowed in XML declaration.

However standalone XML can be used anywhere, while non-standalone is problematic for XML parsers that don't load externals.

I don't see how this declaration could be a problem, other than for interoperability with software that doesn't support XML, but some horrible regex soup.

Push items into mongo array via mongoose

Use $push to update document and insert new value inside an array.

find:

db.getCollection('noti').find({})

result for find:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

update:

db.getCollection('noti').findOneAndUpdate(
   { _id: ObjectId("5bc061f05a4c0511a9252e88") }, 
   { $push: { 
             graph: {
               "date" : ISODate("2018-10-24T08:55:13.331Z"),
               "count" : 3.0
               }  
           } 
   })

result for update:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }, 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 3.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

@Scope("prototype") bean scope not creating new bean

@controller is a singleton object, and if inject a prototype bean to a singleton class will make the prototype bean also as singleton unless u specify using lookup-method property which actually create a new instance of prototype bean for every call you make.

What does asterisk * mean in Python?

I find * useful when writing a function that takes another callback function as a parameter:

def some_function(parm1, parm2, callback, *callback_args):
    a = 1
    b = 2
    ...
    callback(a, b, *callback_args)
    ...

That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example:

def my_callback_function(a, b, x, y, z):
    ...

x = 5
y = 6
z = 7

some_function('parm1', 'parm2', my_callback_function, x, y, z)

Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().

Relative paths in Python

What worked for me is using sys.path.insert. Then I specified the directory I needed to go. For example I just needed to go up one directory.

import sys
sys.path.insert(0, '../')

rotate image with css

Perform rotation using transform: rotate(xdeg) and also apply overflow: hidden to the parent component to avoid overlapping effect

.div-parent {
   overflow: hidden
}

.div-child {
   transform: rotate(270deg);
}

R dates "origin" must be supplied

by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".

(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)

Grab a segment of an array in Java without creating a new array on heap

I needed to iterate through the end of an array and didn't want to copy the array. My approach was to make an Iterable over the array.

public static Iterable<String> sliceArray(final String[] array, 
                                          final int start) {
  return new Iterable<String>() {
    String[] values = array;
    int posn = start;

    @Override
    public Iterator<String> iterator() {
      return new Iterator<String>() {
        @Override
        public boolean hasNext() {
          return posn < values.length;
        }

        @Override
        public String next() {
          return values[posn++];
        }

        @Override
        public void remove() {
          throw new UnsupportedOperationException("No remove");
        }
      };
    }
  };
}

ASP.NET MVC: What is the purpose of @section?

A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.

How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?

You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.

Validating file types by regular expression

Your regexp seems to validate both the file name and the extension. Is that what you need? I'll assume it's just the extension and would use a regexp like this:

\.(jpg|gif|doc|pdf)$

And set the matching to be case insensitive.

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I got this error when stubbing with sinon.

The fix is to use npm package sinon-as-promised when resolving or rejecting promises with stubs.

Instead of ...

sinon.stub(Database, 'connect').returns(Promise.reject( Error('oops') ))

Use ...

require('sinon-as-promised');
sinon.stub(Database, 'connect').rejects(Error('oops'));

There is also a resolves method (note the s on the end).

See http://clarkdave.net/2016/09/node-v6-6-and-asynchronously-handled-promise-rejections

Regular expression to match a dot

This expression,

(?<=\s|^)[^.\s]+\.[^.\s]+(?=@)

might also work OK for those specific types of input strings.

Demo

Test

import re

expression = r'(?<=^|\s)[^.\s]+\.[^.\s]+(?=@)'
string = '''
blah blah blah [email protected] blah blah
blah blah blah test.this @gmail.com blah blah
blah blah blah [email protected] blah blah
'''

matches = re.findall(expression, string)

print(matches)

Output

['test.this']

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Why can't static methods be abstract in Java?

Because 'abstract' means the method is meant to be overridden and one can't override 'static' methods.

Can a JSON value contain a multiline string

I believe it depends on what json interpreter you're using... in plain javascript you could use line terminators

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : "this is a very long line which is not easily readble. \
                  so i would like to write it in multiple lines. \
                  but, i do NOT require any new lines in the output."
    }
  }
}

Add element to a list In Scala

Use import scala.collection.mutable.MutableList or similar if you really need mutation.

import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)

Numpy converting array from float to strings

If the main problem is the loss of precision when converting from a float to a string, one possible way to go is to convert the floats to the decimalS: http://docs.python.org/library/decimal.html.

In python 2.7 and higher you can directly convert a float to a decimal object.

IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

Compare two files report difference in python

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])

Using CSS td width absolute, position

The reason it doesn't work in the link your provided is because you are trying to display a 300px column PLUS 52 columns the span 7 columns each. Shrink the number of columns and it works. You can't fit that many on the screen.

If you want to force the columns to fit try setting:

body {min-width:4150px;}

see my jsfiddle: http://jsfiddle.net/Mkq8L/6/ @mike I can't comment yet.

Calling Non-Static Method In Static Method In Java

You can call a non static method within a static one using: Classname.class.method()

How does the bitwise complement operator (~ tilde) work?

It's easy:

Before starting please remember that 
 1  Positive numbers are represented directly into the memory.
 2. Whereas, negative numbers are stored in the form of 2's compliment.
 3. If MSB(Most Significant bit) is 1 then the number is negative otherwise number is 
    positive.

You are finding ~2:

Step:1 Represent 2 in a binary format 
       We will get, 0000 0010
Step:2 Now we have to find ~2(means 1's compliment of 2)
                  1's compliment       
       0000 0010 =================> 1111 1101 

       So, ~2 === 1111 1101, Here MSB(Most significant Bit) is 1(means negative value). So, 
       In memory it will be represented as 2's compliment(To find 2's compliment first we 
       have to find 1's compliment and then add 1 to it.)
Step3:  Finding 2's compliment of ~2 i.e 1111 1101

                   1's compliment                   Adding 1 to it
        1111 1101 =====================> 0000 0010 =================> 0000 0010
                                                                      +       1
                                                                      ---------
                                                                      0000 0011 
        So, 2's compliment of 1111 1101, is 0000 0011 

Step4:  Converting back to decimal format.
                   binary format
        0000 0011 ==============> 3
        
       In step2: we have seen that the number is negative number so the final answer would  
       be -3
                                    
                                So, ~2 === -3

SHA512 vs. Blowfish and Bcrypt

I agree with erickson's answer, with one caveat: for password authentication purposes, bcrypt is far better than a single iteration of SHA-512 - simply because it is far slower. If you don't get why slowness is an advantage in this particular game, read the article you linked to again (scroll down to "Speed is exactly what you don’t want in a password hash function.").

You can of course build a secure password hashing algorithm around SHA-512 by iterating it thousands of times, just like the way PHK's MD5 algorithm works. Ulrich Drepper did exactly this, for glibc's crypt(). There's no particular reason to do this, though, if you already have a tested bcrypt implementation available.

How to do a HTTP HEAD request from the windows command line?

On Linux, I often use curl with the --head parameter. It is available for several operating systems, including Windows.

[edit] related to the answer below, gknw.net is currently down as of February 23 2012. Check curl.haxx.se for updated info.

How do I dump the data of some SQLite3 tables?

You could do a select on the tables inserting commas after each field to produce a csv, or use a GUI tool to return all the data and save it to a csv.

Language Books/Tutorials for popular languages

For Java, I highly recommend Core Java. It's a large tome (or two large tomes), but I've found it to be one of the best references on Java I've read.

How to merge a list of lists with same type of items to a single list of items?

Here's the C# integrated syntax version:

var items =
    from list in listOfList
    from item in list
    select item;

Reliable way for a Bash script to get the full path to itself

If we use Bash I believe this is the most convenient way as it doesn't require calls to any external commands:

THIS_PATH="${BASH_SOURCE[0]}";
THIS_DIR=$(dirname $THIS_PATH)

Replacing last character in a String with java

org.apache.commons.lang3.StringUtils.removeEnd() and org.springframework.util.StringUtils.trimTrailingCharacter() are your friends:

StringUtils.removeEnd(null, *)      = null
StringUtils.removeEnd("", *)        = ""
StringUtils.removeEnd(*, null)      = *
StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "")    = "abc"
    @Test
    public void springStringUtils() {
        String url = "https://some.site/path/";

        String result = org.springframework.util.StringUtils.trimTrailingCharacter(url, '/');

        assertThat(result, equalTo("https://some.site/path"));
    }

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

Building on the answer of @paibamboo

He said: Go to: Tools > Options > Projects and Solutions > Web Projects > Use the 64 bit version of IIS Express

My coworker had this box checked (he explicitly looked for it), but had the error message in question. After some hours he unchecked the box and checked it again. Lo and behold: The code now ran with success.

It seems, that there are two places where the state of this box ist saved which became out of sync. Un- and rechecking it synced it again.

Question for more knowledgable users: Was there an update or something last week (for VS 2015) which de-synced the states?

How to allow only a number (digits and decimal point) to be typed in an input?

First of all Big thanks to Adam thomas I used the same Adam's logic for this with a small modification to accept the decimal values.

Note: This will allow digits with only 2 decimal values

Here is my Working Example

HTML

<input type="text" ng-model="salary" valid-number />

Javascript

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

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

    app.directive('validNumber', function() {
      return {
        require: '?ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
          if(!ngModelCtrl) {
            return; 
          }

          ngModelCtrl.$parsers.push(function(val) {
            if (angular.isUndefined(val)) {
                var val = '';
            }
            var clean = val.replace(/[^0-9\.]/g, '');
            var decimalCheck = clean.split('.');

            if(!angular.isUndefined(decimalCheck[1])) {
                decimalCheck[1] = decimalCheck[1].slice(0,2);
                clean =decimalCheck[0] + '.' + decimalCheck[1];
            }

            if (val !== clean) {
              ngModelCtrl.$setViewValue(clean);
              ngModelCtrl.$render();
            }
            return clean;
          });

          element.bind('keypress', function(event) {
            if(event.keyCode === 32) {
              event.preventDefault();
            }
          });
        }
      };
    });

How to call URL action in MVC with javascript function?

Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:

 <input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />

Then you just get the value in your ajax call:

var path = $("#GetIndexDataPath").val();
$.ajax({
        type: "GET",
        url: path,
        data: { id = e.value},  
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.

How to calculate percentage with a SQL statement

This one is working well in MS SQL. It transforms varchar to the result of two-decimal-places-limited float.

Select field1, cast(Try_convert(float,(Count(field2)* 100) / 
Try_convert(float, (Select Count(*) From table1))) as decimal(10,2)) as new_field_name 
From table1 
Group By field1, field2;

Convert double to float in Java

This is a nice way to do it:

Double d = 0.5;
float f = d.floatValue();

if you have d as a primitive type just add one line:

double d = 0.5;
Double D = Double.valueOf(d);
float f = D.floatValue();

How to find the date of a day of the week from a date using PHP?

Try

$date = '2012-10-11';
$day  = 1;
$days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday', 'Saturday');
echo date('Y-m-d', strtotime($days[$day], strtotime($date)));

Load content with ajax in bootstrap modal

The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Try it yourself: https://jsfiddle.net/ednon5d1/

htaccess Access-Control-Allow-Origin

In Zend Framework 2.0 i had this problem. Can be solved in two way .htaccess or php header i prefer .htaccess so i modified .htaccess from:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

to

RewriteEngine On

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

and it start to work

Check whether $_POST-value is empty

isset is testing whether or not the key you are checking in the hash (or associative array) is "set". Set in this context just means if it knows the value. Nothing is a value. So it is defined as being an empty string.

For that reason, as long as you have an input field named userName, regardless of if they fill it in, this will be true. What you really want to do is check if the userName is equal to an empty string ''

How to select the first element in the dropdown using jquery?

Here is a simple javascript solution which works in most cases:

document.getElementById("selectId").selectedIndex = "0";

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

To alter a stored procedure, here's the C# code:

SqlConnection con = new SqlConnection("your connection string");
con.Open();
cmd.CommandType = System.Data.CommandType.Text;
string sql = File.ReadAllText(YUOR_SP_SCRIPT_FILENAME);
cmd.CommandText = sql;   
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();

Things to note:

  1. Make sure the USER in the connection string have the right to alter SP
  2. Remove all the GO,SET ANSI_NULLS XX,SET QUOTED_IDENTIFIER statements from the script file. (If you don't, the SqlCommand will throw an error).

Maximum and Minimum values for ints

If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:

np.iinfo(np.intp).max

This is same as sys.maxsize however advantage is that you don't need import sys just for this.

If you want max for native int on the machine:

np.iinfo(np.intc).max

You can look at other available types in doc.

For floats you can also use sys.float_info.max.

How to run cron job every 2 hours

To Enter into crontab :

crontab -e

write this into the file:

0 */2 * * * python/php/java yourfilepath

Example :0 */2 * * * python ec2-user/home/demo.py

and make sure you have keep one blank line after the last cron job in your crontab file

Catch multiple exceptions at once?

Note that I did find one way to do it, but this looks more like material for The Daily WTF:

catch (Exception ex)
{
    switch (ex.GetType().Name)
    {
        case "System.FormatException":
        case "System.OverflowException":
            WebId = Guid.Empty;
            break;
        default:
            throw;
    }
}

When do I need to use a semicolon vs a slash in Oracle SQL?

From my understanding, all the SQL statement don't need forward slash as they will run automatically at the end of semicolons, including DDL, DML, DCL and TCL statements.

For other PL/SQL blocks, including Procedures, Functions, Packages and Triggers, because they are multiple line programs, Oracle need a way to know when to run the block, so we have to write a forward slash at the end of each block to let Oracle run it.