Programs & Examples On #Magic mouse

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

css width: calc(100% -100px); alternative using jquery

If you have a browser that doesn't support the calc expression, it's not hard to mimic with jQuery:

$('#yourEl').css('width', '100%').css('width', '-=100px');

It's much easier to let jQuery handle the relative calculation than doing it yourself.

Best Python IDE on Linux

I haven't played around with it much but eclipse/pydev feels nice.

Remove a marker from a GoogleMap

For those that are following the example on this GoogleMaps - MapWithMarker project, you may remove the marker by doing so

override fun onMapReady(googleMap: GoogleMap?) {
    googleMap?.apply {

        // Remove marker
        clear()

        val sydney = LatLng(-33.852, 151.211)
        addMarker(
            MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney")
        )
        moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

When using a Settings.settings file in .NET, where is the config actually stored?

Here is the snippet you can use to programmatically get user.config file location:

public static string GetDefaultExeConfigPath(ConfigurationUserLevel userLevel)
{
  try
  {
    var UserConfig = ConfigurationManager.OpenExeConfiguration(userLevel);
    return UserConfig.FilePath;
  }
  catch (ConfigurationException e)
  {
    return e.Filename;
  }
}

ApplicationSettings (i.e. settings.settings) use PerUserRoamingAndLocal for user settings by default (as I remembered).

Update: Strange but there are too many incorrect answers here. If you are looking for you user scoped settings file (user.config) it will be located in the following folder (for Windows XP):

C:\Documents and Settings\(username)\Local Settings\Application Data\(company-name-if-exists)\(app-name).exe_(Url|StrongName)_(hash)\(app-version)\

Url or StrongName depends on have you application assembly strong name or not.

jQuery document.createElement equivalent?

since jQuery1.8, using $.parseHTML() to create elements is a better choice.

there are two benefits:

1.if you use the old way, which may be something like $(string), jQuery will examine the string to make sure you want to select a html tag or create a new element. By using $.parseHTML(), you tell jQuery that you want to create a new element explicitly, so the performance may be a little better.

2.much more important thing is that you may suffer from cross site attack (more info) if you use the old way. if you have something like:

    var userInput = window.prompt("please enter selector");
    $(userInput).hide();

a bad guy can input <script src="xss-attach.js"></script> to tease you. fortunately, $.parseHTML() avoid this embarrassment for you:

var a = $('<div>')
// a is [<div>?</div>?]
var b = $.parseHTML('<div>')
// b is [<div>?</div>?]
$('<script src="xss-attach.js"></script>')
// jQuery returns [<script src=?"xss-attach.js">?</script>?]
$.parseHTML('<script src="xss-attach.js"></script>')
// jQuery returns []

However, please notice that a is a jQuery object while b is a html element:

a.html('123')
// [<div>?123?</div>?]
b.html('123')
// TypeError: Object [object HTMLDivElement] has no method 'html'
$(b).html('123')
// [<div>?123?</div>?]

How to prevent http file caching in Apache httpd (MAMP)

Based on the example here: http://drupal.org/node/550488

The following will probably work in .htaccess

 <IfModule mod_expires.c>
   # Enable expirations.
   ExpiresActive On

   # Cache all files for 2 weeks after access (A).
   ExpiresDefault A1209600

  <FilesMatch (\.js|\.html)$>
     ExpiresActive Off
  </FilesMatch>
 </IfModule>

Rename all files in a folder with a prefix in a single command

Try the rename command in the folder with the files:

rename 's/^/Unix_/' *

The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.

Remove plot axis values

@Richie Cotton has a pretty good answer above. I can only add that this page provides some examples. Try the following:

x <- 1:20
y <- runif(20)
plot(x,y,xaxt = "n")
axis(side = 1, at = x, labels = FALSE, tck = -0.01)

Is PowerShell ready to replace my Cygwin shell on Windows?

PowerShell is very powerful, more powerful than the standard built-ins of the Unix shells (but only because it includes much of the functionality usually shelled out to subprograms). Also, consider that you can write applets in any .NET language, including IronPython, IronRuby, PerlNet, etc.. or you can simply call your Cygwin commands from PowerShell, ignoring all the extra functionality and it will work similarly to Bash, KornShell, or whatever...

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

  1. The fd is already closed somewhere.
  2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

Does bootstrap have builtin padding and margin classes?

There are built in classes, namely:

.padding-xs { padding: .25em; }
.padding-sm { padding: .5em; }
.padding-md { padding: 1em; }
.padding-lg { padding: 1.5em; }
.padding-xl { padding: 3em; }

.padding-x-xs { padding: .25em 0; }
.padding-x-sm { padding: .5em 0; }
.padding-x-md { padding: 1em 0; }
.padding-x-lg { padding: 1.5em 0; }
.padding-x-xl { padding: 3em 0; }

.padding-y-xs { padding: 0 .25em; }
.padding-y-sm { padding: 0 .5em; }
.padding-y-md { padding: 0 1em; }
.padding-y-lg { padding: 0 1.5em; }
.padding-y-xl { padding: 0 3em; }

.padding-top-xs { padding-top: .25em; }
.padding-top-sm { padding-top: .5em; }
.padding-top-md { padding-top: 1em; }
.padding-top-lg { padding-top: 1.5em; }
.padding-top-xl { padding-top: 3em; }

.padding-right-xs { padding-right: .25em; }
.padding-right-sm { padding-right: .5em; }
.padding-right-md { padding-right: 1em; }
.padding-right-lg { padding-right: 1.5em; }
.padding-right-xl { padding-right: 3em; }

.padding-bottom-xs { padding-bottom: .25em; }
.padding-bottom-sm { padding-bottom: .5em; }
.padding-bottom-md { padding-bottom: 1em; }
.padding-bottom-lg { padding-bottom: 1.5em; }
.padding-bottom-xl { padding-bottom: 3em; }

.padding-left-xs { padding-left: .25em; }
.padding-left-sm { padding-left: .5em; }
.padding-left-md { padding-left: 1em; }
.padding-left-lg { padding-left: 1.5em; }
.padding-left-xl { padding-left: 3em; }

.margin-xs { margin: .25em; }
.margin-sm { margin: .5em; }
.margin-md { margin: 1em; }
.margin-lg { margin: 1.5em; }
.margin-xl { margin: 3em; }

.margin-x-xs { margin: .25em 0; }
.margin-x-sm { margin: .5em 0; }
.margin-x-md { margin: 1em 0; }
.margin-x-lg { margin: 1.5em 0; }
.margin-x-xl { margin: 3em 0; }

.margin-y-xs { margin: 0 .25em; }
.margin-y-sm { margin: 0 .5em; }
.margin-y-md { margin: 0 1em; }
.margin-y-lg { margin: 0 1.5em; }
.margin-y-xl { margin: 0 3em; }

.margin-top-xs { margin-top: .25em; }
.margin-top-sm { margin-top: .5em; }
.margin-top-md { margin-top: 1em; }
.margin-top-lg { margin-top: 1.5em; }
.margin-top-xl { margin-top: 3em; }

.margin-right-xs { margin-right: .25em; }
.margin-right-sm { margin-right: .5em; }
.margin-right-md { margin-right: 1em; }
.margin-right-lg { margin-right: 1.5em; }
.margin-right-xl { margin-right: 3em; }

.margin-bottom-xs { margin-bottom: .25em; }
.margin-bottom-sm { margin-bottom: .5em; }
.margin-bottom-md { margin-bottom: 1em; }
.margin-bottom-lg { margin-bottom: 1.5em; }
.margin-bottom-xl { margin-bottom: 3em; }

.margin-left-xs { margin-left: .25em; }
.margin-left-sm { margin-left: .5em; }
.margin-left-md { margin-left: 1em; }
.margin-left-lg { margin-left: 1.5em; }
.margin-left-xl { margin-left: 3em; }

How to stretch a table over multiple pages

You should \usepackage{longtable}.

What is %0|%0 and how does it work?

This is the Windows version of a fork bomb.

%0 is the name of the currently executing batch file. A batch file that contains just this line:

%0|%0

Is going to recursively execute itself forever, quickly creating many processes and slowing the system down.

This is not a bug in windows, it is just a very stupid thing to do in a batch file.

Remove legend ggplot 2.2

If your chart uses both fill and color aesthetics, you can remove the legend with:

+ guides(fill=FALSE, color=FALSE)

Android Google Maps API V2 Zoom to Current Location

youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 is the zoom level

jQuery get content between <div> tags

This is probably what you need:

$('div').html();

demo

This says get the div and return all the contents inside it. See more here: http://api.jquery.com/html/

If you had many divs on the page and needed to target just one, you could set an id on the div and call it like so

$('#whatever').html();

where whatever is the id

EDIT

Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:

var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);

Demo Here

  1. get the length of the string.
  2. find out where the first div occurs
  3. slice the content there.

How to debug in Django, the good way?

I find Visual Studio Code is awesome for debugging Django apps. The standard python launch.json parameters run python manage.py with the debugger attached, so you can set breakpoints and step through your code as you like.

error TS2339: Property 'x' does not exist on type 'Y'

If you want to be able to access images.main then you must define it explicitly:

interface Images {
    main: string;
    [key:string]: string;
}

function getMainImageUrl(images: Images): string {
    return images.main;
}

You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it's there (or not), whether it's optional or not and what's the type.


Edit

You can have a helper class for map instances, something like:

class Map<T> {
    private items: { [key: string]: T };

    public constructor() {
        this.items = Object.create(null);
    }

    public set(key: string, value: T): void {
        this.items[key] = value;
    }

    public get(key: string): T {
        return this.items[key];
    }

    public remove(key: string): T {
        let value = this.get(key);
        delete this.items[key];
        return value;
    }
}

function getMainImageUrl(images: Map<string>): string {
    return images.get("main");
}

I have something like that implemented, and I find it very useful.

AngularJS sorting rows by table header

I think this working CodePen example that I created will show you exactly how to do what you want.

The template:

<section ng-app="app" ng-controller="MainCtrl">
  <span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>
          <a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
          First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
            Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
          Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
        <td>{{emp.firstName}}</td>
        <td>{{emp.lastName}}</td>
        <td>{{emp.age}}</td>
      </tr>
    </tbody>
  </table>
</section>

The JavaScript code:

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

app.controller('MainCtrl', function($scope) {
  $scope.orderByField = 'firstName';
  $scope.reverseSort = false;

  $scope.data = {
    employees: [{
      firstName: 'John',
      lastName: 'Doe',
      age: 30
    },{
      firstName: 'Frank',
      lastName: 'Burns',
      age: 54
    },{
      firstName: 'Sue',
      lastName: 'Banter',
      age: 21
    }]
  };
});

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

jQuery find element by data attribute value

I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)

var numb = "3";
$(`#myid[data-tab-id=${numb}]`);

How do I redirect output to a variable in shell?

read hash < <(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)

This technique uses Bash's "process substitution" not to be confused with "command substitution".

Here are a few good references:

How can I generate an MD5 hash?

MD5 is perfectly fine if you don't need the best security, and if you're doing something like checking file integrity then security is not a consideration. In such as case you might want to consider something simpler and faster, such as Adler32, which is also supported by the Java libraries.

How to print_r $_POST array?

$_POST is an array in itsself you don't need to make an array out of it. What you did is nest the $_POST array inside a new array. This is why you print Array. Change it to:

foreach ($_POST as $key => $value) {

  echo "<p>".$key."</p>";
  echo "<p>".$value."</p>";
  echo "<hr />";

} 

Create XML file using java

package com.server;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


import org.w3c.dom.*;

import com.gwtext.client.data.XmlReader;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;  

public class XmlServlet extends HttpServlet
{ 

  NodeList list;
  Connection con=null;
  Statement st=null;
  ResultSet rs = null;
  String xmlString ;
  BufferedWriter bw;
  String displayTo;
  String displayFrom;
  String addressto;
  String addressFrom;
  Date send;
  String Subject;
  String body;
  String category;
  Document doc1;
  public void doGet(HttpServletRequest request,HttpServletResponse response)
   throws ServletException,IOException{

    System.out.print("on server");  

  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  System.out.print("on server");
  try
  {


    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
    //creating a new instance of a DOM to build a DOM tree.
    doc1 = docBuilder.newDocument();
    new XmlServlet().createXmlTree(doc1);

    System.out.print("on server");

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

   }

  public void createXmlTree(Document doc) throws Exception {
  //This method creates an element node

    System.out.println("ruchipaliwal111");

    try
    {

      System.out.println("ruchi111");
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1");
      st = con.createStatement();

      rs = st.executeQuery("select * from data");


      Element root = doc.createElement("message");
      doc.appendChild(root);

        while(rs.next())
        {



       displayTo=rs.getString(1).toString();
       System.out.println(displayTo+"getdataname");

       displayFrom=rs.getString(2).toString();
       System.out.println(displayFrom +"getdataname");

         addressto=rs.getString(3).toString();
         System.out.println(addressto +"getdataname");

       addressFrom=rs.getString(4).toString();
       System.out.println(addressFrom +"getdataname");

       send=rs.getDate(5);
       System.out.println(send +"getdataname");

       Subject=rs.getString(6).toString();
       System.out.println(Subject +"getdataname");

       body=rs.getString(7).toString();
       System.out.println(body+"getdataname");

      category=rs.getString(8).toString();
       System.out.println(category +"getdataname");


       //adding a node after the last child node of ssthe specified node.


        Element element1 = doc.createElement("Header");
        root.appendChild(element1);


        Element child1 = doc.createElement("To");
        element1.appendChild(child1);

        child1.setAttribute("displayNameTo",displayTo);
        child1.setAttribute("addressTo",addressto);

        Element child2 = doc.createElement("From");
        element1.appendChild(child2);

        child2.setAttribute("displayNameFrom",displayFrom);
        child2.setAttribute("addressFrom",addressFrom);

        Element child3 = doc.createElement("Send");
        element1.appendChild(child3);

        Text text2 = doc.createTextNode(send.toString());
        child3.appendChild(text2);

        Element child4 = doc.createElement("Subject");
        element1.appendChild(child4);

        Text text3 = doc.createTextNode(Subject);
        child4.appendChild(text3);

        Element child5 = doc.createElement("category");
        element1.appendChild(child5);

        Text text44 = doc.createTextNode(category);
        child5.appendChild(text44);


        Element element2 = doc.createElement("Body");
        root.appendChild(element2);

        Text text1 = doc.createTextNode(body);
        element2.appendChild(text1);

       /*
        Element child1 = doc.createElement("name");
        root.appendChild(child1);
        Text text = doc.createTextNode(getdataname);
        child1.appendChild(text);
        Element element = doc.createElement("address");
        root.appendChild(element);
        Text text1 = doc.createTextNode( getdataaddress);
        element.appendChild(text1); 
     */
      } 






//TransformerFactory instance is used to create Transformer objects. 
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer();

  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty(OutputKeys.METHOD,"xml");
  // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");


  // create string from xml tree
  StringWriter sw = new StringWriter();
  StreamResult result = new StreamResult(sw);
  DOMSource source = new DOMSource(doc);
  transformer.transform(source, result);

  xmlString = sw.toString();


  File file = new File("./war/ds/newxml.xml");
  bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
  bw.write(xmlString);
   }

    catch(Exception e)
    {
      System.out.print("after while loop exception"+e.toString());
    }

  bw.flush();
  bw.close();
  System.out.println("successfully done.....");
  }
}

Setting Authorization Header of HttpClient

I look for a good way to deal with this issue and I am looking at the same question. Hopefully, this answer will be helping everyone who has the same problem likes me.

using (var client = new HttpClient())
{
    var url = "https://www.theidentityhub.com/{tenant}/api/identity/v1";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    var response = await client.GetStringAsync(url);
    // Parse JSON response.
    ....
}

reference from https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi

How to style the UL list to a single line

ul li{
  display: inline;
}

For more see the basic list options and a basic horizontal list at listamatic. (thanks to Daniel Straight below for the links).

Also, as pointed out in the comments, you probably want styling on the ul and whatever elements go inside the li's and the li's themselves to get things to look nice.

How to disable horizontal scrolling of UIScrollView?

Swift solution

Create two outlets, one for your view and one for your scroll view:

@IBOutlet weak var myView: UIView!
@IBOutlet weak var scrollView: UIScrollView!

Then in your viewDidLayoutSubviews you can add the following code:

let scrollSize = CGSize(width: myView.frame.size.width, 
                        height: myView.frame.size.height)
scrollView.contentSize = scrollSize

What we've done is collected the height and width of the view and set the scrollViews content size to match it. This will stop your scrollview from scrolling horizontally.


More Thoughts:

CGSizeMake takes a width & height using CGFloats. You may need to use your UIScrollViews existing height for the second parameter. Which would look like this:

let scrollSize = CGSize(width: myView.frame.size.width, 
                        height: scrollView.contentSize.height)

user authentication libraries for node.js?

If you are looking for an authentication framework for Connect or Express, Passport is worth investigating: https://github.com/jaredhanson/passport

(Disclosure: I'm the developer of Passport)

I developed Passport after investigating both connect-auth and everyauth. While they are both great modules, they didn't suit my needs. I wanted something that was more light-weight and unobtrusive.

Passport is broken down into separate modules, so you can choose to use only what you need (OAuth, only if necessary). Passport also does not mount any routes in your application, giving you the flexibility to decide when and where you want authentication, and hooks to control what happens when authentication succeeds or fails.

For example, here is the two-step process to setup form-based (username and password) authentication:

passport.use(new LocalStrategy(
  function(username, password, done) {
    // Find the user from your DB (MongoDB, CouchDB, other...)
    User.findOne({ username: username, password: password }, function (err, user) {
      done(err, user);
    });
  }
));

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {
    // Authentication successful. Redirect home.
    res.redirect('/');
  });

Additional strategies are available for authentication via Facebook, Twitter, etc. Custom strategies can be plugged-in, if necessary.

How do I run a batch file from my Java Application?

Runtime runtime = Runtime.getRuntime();
try {
    Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
    InputStream is = p1.getInputStream();
    int i = 0;
    while( (i = is.read() ) != -1) {
        System.out.print((char)i);
    }
} catch(IOException ioException) {
    System.out.println(ioException.getMessage() );
}

Android disable screen timeout while app is running

Put this at onStart

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "no sleep");
    wakeLock.acquire();

And this at you manifest

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

Don't forget to

wakeLock.release();

at onStop

how to clear JTable

This is the fastest and easiest way that I have found;

while (tableModel.getRowCount()>0)
          {
             tableModel.removeRow(0);
          }

This clears the table lickety split and leaves it ready for new data.

C/C++ Struct vs Class

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.

However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)

While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.

IE 8: background-size fix

I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:

background: no-repeat center center fixed\0/; /* IE8 HACK */

This has solved the frozen links problem for me.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

I just looked at code that did this today. This is a variation on AviewAnew's answer.

collectionOfStrings = /* source string collection */;
String csList = StringUtils.join(collectionOfStrings.toArray(), ",");

The StringUtils ( <-- commons.lang 2.x, or commons.lang 3.x link) we used is from Apache Commons.

Is div inside list allowed?

I see you would want to do this if you wanted to make, say, the whole box of a menu item clickable. I used to insert an 'li' tag in 'a' tags to do this but this seems more valid.

Combine GET and POST request methods in Spring

@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

This will works for both GET and POST.

For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter

like below

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/books?parameter1=blah

Like this way u can use it for both GET and POST

Python Pandas Error tokenizing data

Your CSV file might have variable number of columns and read_csv inferred the number of columns from the first few rows. Two ways to solve it in this case:

1) Change the CSV file to have a dummy first line with max number of columns (and specify header=[0])

2) Or use names = list(range(0,N)) where N is the max number of columns.

Permission denied when launch python script via bash

Did you include

#!/usr/bin/python

as your first line?

How do I run Java .class files?

You need to set the classpath to find your compiled class:

java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2

Detect end of ScrollView

All of these answers are so complicated, but there is a simple built-in method that accomplishes this: canScrollVertically(int)

For example:

@Override
public void onScrollChanged() {
    if (!scrollView.canScrollVertically(1)) {
        // bottom of scroll view
    }
    if (!scrollView.canScrollVertically(-1)) {
        // top of scroll view
    }
}

This also works with RecyclerView, ListView, and actually any other view since the method is implemented on View.

If you have a horizontal ScrollView, the same can be achieved with canScrollHorizontally(int)

Text inset for UITextField?

To throw in another solution that has no need for subclassing:

UITextField *txtField = [UITextField new];
txtField.borderStyle = UITextBorderStyleRoundedRect;

// grab BG layer
CALayer *bgLayer = txtField.layer.sublayers.lastObject;
bgLayer.opacity = 0.f;

// add new bg view
UIView *bgView = [UIView new];
bgView.backgroundColor = [UIColor whiteColor];
bgView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
bgView.userInteractionEnabled = NO;

[txtField addSubview: bgView];
[txtField sendSubviewToBack: bgView];

Original UITextField Fixed UITextField

Tested with iOS 7 and iOS 8. Both working. Still there might be the chance of Apple modifying the UITextField's layer hierarchy screwing up things badly.

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

commons httpclient - Adding query string parameters to GET/POST request

This is how I implemented my URL builder. I have created one Service class to provide the params for the URL

public interface ParamsProvider {

    String queryProvider(List<BasicNameValuePair> params);

    String bodyProvider(List<BasicNameValuePair> params);
}

The Implementation of methods are below

@Component
public class ParamsProviderImp implements ParamsProvider {
    @Override
    public String queryProvider(List<BasicNameValuePair> params) {
        StringBuilder query = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                query.append("?");
                query.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                query.append("&");
                query.append(basicNameValuePair.toString());
            }
        });
        return query.toString();
    }

    @Override
    public String bodyProvider(List<BasicNameValuePair> params) {
        StringBuilder body = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                body.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                body.append("&");
                body.append(basicNameValuePair.toString());
            }
        });
        return body.toString();
    }
}

When we need the query params for our URL, I simply call the service and build it. Example for that is below.

Class Mock{
@Autowired
ParamsProvider paramsProvider;
 String url ="http://www.google.lk";
// For the query params price,type
 List<BasicNameValuePair> queryParameters = new ArrayList<>();
 queryParameters.add(new BasicNameValuePair("price", 100));
 queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider

}

Find a string within a cell using VBA

you never change the value of rng so it always points to the initial cell

copy the Set rng = rng.Offset(1, 0) to a new line before loop

also, your InStr test will always fail
True is -1, but the return from InStr will be greater than 0 when the string is found. change the test to remove = True

new code:

Sub IfTest()
 'This should split the information in a table up into cells
 Dim Splitter() As String
 Dim LenValue As Integer     'Gives the number of characters in date string
 Dim LeftValue As Integer    'One less than the LenValue to drop the ")"
 Dim rng As Range, cell As Range
 Set rng = ActiveCell

Do While ActiveCell.Value <> Empty
    If InStr(rng, "%") Then
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "% Change")
        ActiveCell.Offset(0, 10).Select
        ActiveCell.Value = Splitter(1)
        ActiveCell.Offset(0, -1).Select
        ActiveCell.Value = "% Change"
        ActiveCell.Offset(1, -9).Select
    Else
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "(")
        ActiveCell.Offset(0, 9).Select
        ActiveCell.Value = Splitter(0)
        ActiveCell.Offset(0, 1).Select
        LenValue = Len(Splitter(1))
        LeftValue = LenValue - 1
        ActiveCell.Value = Left(Splitter(1), LeftValue)
        ActiveCell.Offset(1, -10).Select
    End If
Set rng = rng.Offset(1, 0)
Loop

End Sub

Check if string is in a pandas dataframe

I bumped into the same problem, I used:

if "Mel" in a["Names"].values:
    print("Yep")

But this solution may be slower since internally pandas create a list from a Series.

Your content must have a ListView whose id attribute is 'android.R.id.list'

You should have one listview in your mainlist.xml file with id as @android:id/list

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_height="fill_parent"/>

How to use not contains() in xpath?

XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"

//production[not(contains(category,'Business'))]

I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.

Alternative to google finance api

I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

Solution can be the following:

DECLARE @UnixTimeStamp bigint = 1564646400000 /*2019-08-01 11:00 AM*/

DECLARE @LocalTimeOffset bigint = DATEDIFF(MILLISECOND, GETDATE(), GETUTCDATE());
DECLARE @AdjustedTimeStamp bigint = @UnixTimeStamp - @LocalTimeOffset;
SELECT [DateTime] = DATEADD(SECOND, @AdjustedTimeStamp % 1000, DATEADD(SECOND, @AdjustedTimeStamp / 1000, '19700101'));

Conversion of System.Array to List

I hope this is helpful.

enum TESTENUM
    {
        T1 = 0,
        T2 = 1,
        T3 = 2,
        T4 = 3
    }

get string value

string enumValueString = "T1";

        List<string> stringValueList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m => 
            Convert.ToString(m)
            ).ToList();

        if(!stringValueList.Exists(m => m == enumValueString))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertString;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);

get integer value

        int enumValueInt = 1;

        List<int> enumValueIntList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
            Convert.ToInt32(m)
            ).ToList();

        if(!enumValueIntList.Exists(m => m == enumValueInt))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertInt;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

HTML5 Video Autoplay not working correctly

Working solution October 2018, for videos including audio channel

 $(document).ready(function() {
     $('video').prop('muted',true).play()
 });

Have a look at another of mine, more in-depth answer: https://stackoverflow.com/a/57723549/3049675

How to use SSH to run a local shell script on a remote machine?

This is an old question, and Jason's answer works fine, but I would like to add this:

ssh user@host <<'ENDSSH'
#commands to run on remote host
ENDSSH

This can also be used with su and commands which require user input. (note the ' escaped heredoc)

Edit: Since this answer keeps getting bits of traffic, i would add even more info to this wonderful use of heredoc:

You can nest commands with this syntax, and thats the only way nesting seems to work (in a sane way)

ssh user@host <<'ENDSSH'
#commands to run on remote host
ssh user@host2 <<'END2'
# Another bunch of commands on another host
wall <<'ENDWALL'
Error: Out of cheese
ENDWALL
ftp ftp.secureftp-test.com <<'ENDFTP'
test
test
ls
ENDFTP
END2
ENDSSH

You can actually have a conversation with some services like telnet, ftp, etc. But remember that heredoc just sends the stdin as text, it doesn't wait for response between lines

Edit: I just found out that you can indent the insides with tabs if you use <<-END !

ssh user@host <<-'ENDSSH'
    #commands to run on remote host
    ssh user@host2 <<-'END2'
        # Another bunch of commands on another host
        wall <<-'ENDWALL'
            Error: Out of cheese
        ENDWALL
        ftp ftp.secureftp-test.com <<-'ENDFTP'
            test
            test
            ls
        ENDFTP
    END2
ENDSSH

(I think this should work)

Also see http://tldp.org/LDP/abs/html/here-docs.html

What are static factory methods?

If the constructor of a class is private then you cannot create an object for class from outside of it.

class Test{
 int x, y;
 private Test(){
  .......
  .......
  }
}

We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class

public static Test getObject(){
  return new Test();
}

So now you can create an object for this class from outside of it. Like the way...

Test t = Test.getObject();

Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method
.

Monitor network activity in Android Phones

TCPDUMP is one of my favourite tools for analyzing network, but if you find difficult to cross-compile tcpdump for android, I'd recomend you to use some applications from the market.

These are the applications I was talking about:

  • Shark: Is small version of wireshark for Android phones). This program will create a *.pcap and you can read the file on PC with wireshark.
  • Shark Reader : This program allows you to read the *.pcap directly in your Android phone.

Shark app works with rooted devices, so if you want to install it, be sure that you have your device already rooted.

Good luck ;)

How to compare arrays in JavaScript?

Another approach with very few code (using Array reduce and Array includes):

arr1.length == arr2.length && arr1.reduce((a, b) => a && arr2.includes(b), true)

If you want to compare also the equality of order:

arr1.length == arr2.length && arr1.reduce((a, b, i) => a && arr2[i], true)
  • The length check ensures that the set of elements in one array isn't just a subset of the other one.

  • The reducer is used to walk through one array and search for each item in other array. If one item isn't found the reduce function returns false.

    1. In the first example it's being tested that an element is included
    2. The second example check for the order too

Find PHP version on windows command line

  1. First open your cmd
  2. Then go to php folder directory, Suppose your php folder is in xampp folder on your c drive. Your command would then be:

    cd c:\xampp\php
    
  3. After that, check your version:

    php -v
    

This should give the following output:

PHP 7.2.0 (cli) (built: Nov 29 2017 00:17:00) ( ZTS MSVC15 (Visual C++ 2017) x86 ) Copyright (c) 1997-2017 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies

I have uploaded a youtube video myself about checking the version of PHP via command prompt in Bangla: https://www.youtube.com/watch?v=zVkhD_tv9ck

Are SSL certificates bound to the servers ip address?

SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.

In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.

Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.

BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.

JQuery .each() backwards

Needed to do a reverse on $.each so i used Vinay idea:

//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});

worked nicely, thanks

Java: How to access methods from another class

public class WeatherResponse {

private int cod;
private String base;
private Weather main;

public int getCod(){
    return this.cod;
}

public void setCod(int cod){
    this.cod = cod;
}

public String getBase(){
    return base;
}

public void setBase(String base){
    this.base = base;
}

public Weather getWeather() {
    return main;
}

// default constructor, getters and setters
}

another class

public class Weather {

private int id;
private String main;
private String description;

public String getMain(){
    return main;
}

public void setMain(String main){
    this.main = main;
}

public String getDescription(){
    return description;
}

public void setDescription(String description){
    this.description = description;
}

// default constructor, getters and setters
}

// accessing methods
// success!

    Log.i("App", weatherResponse.getBase());
    Log.i("App", weatherResponse.getWeather().getMain());
    Log.i("App", weatherResponse.getWeather().getDescription());

How to use Bootstrap in an Angular project?

An integration with Angular2 is also available through the ng2-bootstrap project : https://github.com/valor-software/ng2-bootstrap.

To install it simply put these files in your main HTML page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Then you can use it into your components this way:

import {Component} from 'angular2/core';
import {Alert} from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'my-app',
  directives: [Alert],
  template: `<alert type="info">ng2-bootstrap hello world!</alert>`
})
export class AppComponent {
}

jQuery ui datepicker with Angularjs

You main Index.html file for Angular can use the body tag as the ng-view. Then all you need to do is include a script tag at the bottom of whatever page is being pulled into Index.html by Angular like so:

<script type="text/javascript">
$( function() {
    $( "#mydatepickerid" ).datepicker({changeMonth: true, changeYear: true, 
        yearRange: '1930:'+new Date().getFullYear(), dateFormat: "yy-mm-dd"});
});
</script>

Why overcomplicate things??

Best way to compare dates in Android

You can use validDate.setTime(strDate) Have a look at the javadoc at http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

Bootstrap: adding gaps between divs

An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}} to override the previous margin)

is to nest your class in your preferred div and then add on your class the margin option you want

like the following example: HTML

<div class="container">
  <div class="col-md-3 col-xs-12">
   <div class="events">
     <img src="..."  class="img-responsive" alt="...."/>
     <div class="figcaption">
       <h2>Event Title</h2>
       <p>Event Description.</p>
     </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
</div>

And on your CSS you just add the margin option on your class which in this example is "events" like:

.events{
margin: 20px 10px;
}

By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.

Android Layout Weight

It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.

In Python, how do I convert all of the items in a list to floats?

map(float, mylist) should do it.

(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need list(map(float, mylist) - or use SilentGhost's answer which arguably is more pythonic.)

Rails: How can I set default values in ActiveRecord?

The after_initialize callback pattern can be improved by simply doing the following

after_initialize :some_method_goes_here, :if => :new_record?

This has a non-trivial benefit if your init code needs to deal with associations, as the following code triggers a subtle n+1 if you read the initial record without including the associated.

class Account

  has_one :config
  after_initialize :init_config

  def init_config
    self.config ||= build_config
  end

end

Ruby: How to get the first character of a string

Because of an annoying design choice in Ruby before 1.9 — some_string[0] returns the character code of the first character — the most portable way to write this is some_string[0,1], which tells it to get a substring at index 0 that's 1 character long.

C programming: Dereferencing pointer to incomplete type error

You are using the pointer newFile without allocating space for it.

struct stasher_file *newFile = malloc(sizeof(stasher_file));

Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.

struct stasher_file {
    char name[32];
    int  size;
    int  start;
    int  popularity;
};

Add timer to a Windows Forms application

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Hi you can try below methods with initialize of model.

Here you can initialize ng-model of textbox two way

- With use of ng-init

- With use of $scope in js

<!doctype html>
 <html >
 <head>
        <title>Angular js initalize with ng-init and scope</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="app" >
    <h3>Initialize value with ng-init</h3>
    <!-- Initlialize model values with ng-init -->
    <div ng-init="user={fullname:'Bhaskar Bhatt',email:'[email protected]',address:'Ahmedabad'};">
        Name : <input type="text" ng-model="user.fullname" /><br/>
        Email : <input type="text" ng-model="user.email" /><br/>
        Address:<input type="text" ng-model="user.address" /><br/>

    </div>  
    <!-- initialize with js controller scope -->
    <h3>Initialize with js controller</h3>

    <div  ng-controller="alpha">
        Age:<input type="text" name="age" ng-model="user.age" /><br/>
        Experience : <input type="text" name="experience" ng-model="user.exp" /><br/>
        Skills : <input type="text" name="skills" ng-model="user.skills" /><br/>
    </div>  

</body> 
<script type="text/javascript">
        angular.module("app",[])
        .controller("alpha",function($scope){
            $scope.user={};
            $scope.user.age=27;
            $scope.user.exp="4+ years";
            $scope.user.skills="Php,javascript,Jquery,Ajax,Mysql";
        });

     </script>
 </html>                

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

How to know if a DateTime is between a DateRange in C#

I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.

http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

C#: Looping through lines of multiline string

I know this has been answered, but I'd like to add my own answer:

using (var reader = new StringReader(multiLineString))
{
    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        // Do something with the line
    }
}

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

It's ctrl + . when, for example, you try to type List you need to type < at the end and press ctrl + . for it to work.

Finding the index of an item in a list

This solution is not as powerful as others, but if you're a beginner and only know about forloops it's still possible to find the first index of an item while avoiding the ValueError:

def find_element(p,t):
    i = 0
    for e in p:
        if e == t:
            return i
        else:
            i +=1
    return -1

Printing an array in C++?

Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.

Printing arrays and dumping many different kinds of objects is a feature of higher level languages.

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

Do you mean this?

var listOfList = new List<List<int>>() {
    new List<int>() { 1, 2 },
    new List<int>() { 3, 4 },
    new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));

foreach (var x in result) Console.WriteLine(x);

Results in: 9 9 9 1 2 3 4 5 6

How to force the input date format to dd/mm/yyyy?

To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow

<input id="txtDay" type="text" placeholder="DD" />

<input id="txtMonth" type="text" placeholder="MM" />

<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>


  function validateDate() {
    var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);

    if (date == "Invalid Date") {
        alert("jnvalid date");

    }
}

How do I add 1 day to an NSDate?

Since iOS 8 you can use NSCalendar.dateByAddingUnit

Example in Swift 1.x:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
    .dateByAddingUnit(
         .CalendarUnitDay, 
         value: 1, 
         toDate: today, 
         options: NSCalendarOptions(0)
    )

Swift 2.0:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
    .dateByAddingUnit(
        .Day, 
        value: 1, 
        toDate: today, 
        options: []
    )

Swift 3.0:

let today = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)

Adding css class through aspx code behind

If you're not using the id for anything other than code-behind reference (since .net mangles the ids), you could use a panel control and reference it in your codebehind:

<asp:panel runat="server" id="classMe"></asp:panel>

classMe.cssClass = "someClass"

Session variables in ASP.NET MVC

Although I don't know about asp.net mvc, but this is what we should do in a normal .net website. It should work for asp.net mvc also.

YourSessionClass obj=Session["key"] as YourSessionClass;
if(obj==null){
obj=new YourSessionClass();
Session["key"]=obj;
}

You would put this inside a method for easy access. HTH

Read a HTML file into a string variable in memory

This is mostly covered already, but one addition as I ran into an issue with the previous code samples.

Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))

React Router v4 - How to get current route?

Add

import {withRouter} from 'react-router-dom';

Then change your component export

export default withRouter(ComponentName)

Then you can access the route directly within the component itself (without touching anything else in your project) using:

window.location.pathname

Tested March 2020 with: "version": "5.1.2"

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

Date to milliseconds and back to date in Swift

Unless you absolutely have to convert the date to an integer, consider using a Double instead to represent the time interval. After all, this is the type that timeIntervalSince1970 returns. All of the answers that convert to integers loose sub-millisecond precision, but this solution is much more accurate (although you will still lose some precision due to floating-point imprecision).

public extension Date {
    
    /// The interval, in milliseconds, between the date value and
    /// 00:00:00 UTC on 1 January 1970.
    /// Equivalent to `self.timeIntervalSince1970 * 1000`.
    var millisecondsSince1970: Double {
        return self.timeIntervalSince1970 * 1000
    }

    /**
     Creates a date value initialized relative to 00:00:00 UTC
     on 1 January 1970 by a given number of **milliseconds**.
     
     equivalent to
     ```
     self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
     ```
     - Parameter millisecondsSince1970: A time interval in milliseconds.
     */
    init(millisecondsSince1970: Double) {
        self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }

}

Ruby objects and JSON serialization (without Rails)

For the JSON library to be available, you may have to install libjson-ruby from your package manager.

To use the 'json' library:

require 'json'

To convert an object to JSON (these 3 ways are equivalent):

JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string

To convert JSON text to an object (these 2 ways are equivalent):

JSON.load string #returns an object
JSON.parse string #returns an object

It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like "\"#<A:0xb76e5728>\"".

class A
    def initialize a=[1,2,3], b='hello'
        @a = a
        @b = b
    end
end

This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method. To go with this, a from_json class method would be useful. You could extend your class like so:

class A
    def to_json
        {'a' => @a, 'b' => @b}.to_json
    end
    def self.from_json string
        data = JSON.load string
        self.new data['a'], data['b']
    end
end

You could automate this by inheriting from a 'JSONable' class:

class JSONable
    def to_json
        hash = {}
        self.instance_variables.each do |var|
            hash[var] = self.instance_variable_get var
        end
        hash.to_json
    end
    def from_json! string
        JSON.load(string).each do |var, val|
            self.instance_variable_set var, val
        end
    end
end

Then you can use object.to_json to serialise to JSON and object.from_json! string to copy the saved state that was saved as the JSON string to the object.

Chrome, Javascript, window.open in new tab

At the moment (Chrome 39) I use this code to open a new tab:

_x000D_
_x000D_
window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
_x000D_
_x000D_
_x000D_

Of course this may change in future versions of Chrome.

It is a bad idea to use this if you can't control the browser your users are using. It may not work in future versions or with different settings.

Getting list of parameter names inside python function

If you also want the values you can use the inspect module

import inspect

def func(a, b, c):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    print 'function name "%s"' % inspect.getframeinfo(frame)[2]
    for i in args:
        print "    %s = %s" % (i, values[i])
    return [(i, values[i]) for i in args]

>>> func(1, 2, 3)
function name "func"
    a = 1
    b = 2
    c = 3
[('a', 1), ('b', 2), ('c', 3)]

Error Running React Native App From Terminal (iOS)

For those like me who come to this page with this problem after updating Xcode but don't have an issue with the location setting, restarting my computer did the trick.

When do I use the PHP constant "PHP_EOL"?

Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.

Check OS version in Swift?

Also if you want to check WatchOS.

Swift

let watchOSVersion = WKInterfaceDevice.currentDevice().systemVersion
print("WatchOS version: \(watchOSVersion)")

Objective-C

NSString *watchOSVersion = [[WKInterfaceDevice currentDevice] systemVersion];
NSLog(@"WatchOS version: %@", watchOSVersion);

MySQL Error #1133 - Can't find any matching row in the user table

I encountered this error using MySQL in a different context (not within phpMyAdmin). GRANT and SET PASSWORD commands failed on a particular existing user, who was listed in the mysql.user table. In my case, it was fixed by running

FLUSH PRIVILEGES;

The documentation for this command says

Reloads the privileges from the grant tables in the mysql database.

The server caches information in memory as a result of GRANT and CREATE USER statements. This memory is not released by the corresponding REVOKE and DROP USER statements, so for a server that executes many instances of the statements that cause caching, there will be an increase in memory use. This cached memory can be freed with FLUSH PRIVILEGES.

Apparently the user table cache had reached an inconsistent state, causing this weird error message. More information is available here.

PHP PDO returning single row

how about using limit 0,1 for mysql optimisation

and about your code:

$DBH = new PDO( "connection string goes here" );

$STH - $DBH -> prepare( "select figure from table1" );

$STH -> execute();

$result = $STH ->fetch(PDO::FETCH_ASSOC)

echo $result["figure"];

$DBH = null;

How to send POST request in JSON using HTTPClient in Android?

I recommend using this HttpURLConnectioninstead HttpGet. As HttpGet is already deprecated in Android API level 22.

HttpURLConnection httpcon;  
String url = null;
String data = null;
String result = null;
try {
  //Connect
  httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
  httpcon.setDoOutput(true);
  httpcon.setRequestProperty("Content-Type", "application/json");
  httpcon.setRequestProperty("Accept", "application/json");
  httpcon.setRequestMethod("POST");
  httpcon.connect();

  //Write       
  OutputStream os = httpcon.getOutputStream();
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
  writer.write(data);
  writer.close();
  os.close();

  //Read        
  BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));

  String line = null; 
  StringBuilder sb = new StringBuilder();         

  while ((line = br.readLine()) != null) {  
    sb.append(line); 
  }         

  br.close();  
  result = sb.toString();

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} 

How to clear the interpreter console?

I'm not sure if Windows' "shell" supports this, but on Linux:

print "\033[2J"

https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes

In my opinion calling cls with os is a bad idea generally. Imagine if I manage to change the cls or clear command on your system, and you run your script as admin or root.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

As has been discussed elsewhere, the .length property reference is failing because theHref is undefined. However, be aware of any solution which involves comparing theHref to undefined, which is not a keyword in JavaScript and can be redefined.

For a full discussion of checking for undefined variables, see Detecting an undefined object property and the first answer in particular.

Sql Server return the value of identity column after insert statement

You can explicitly get back Identity columns using SqlServer's OUTPUT clause: Assuming you have an identity/auto-increment column called ID:

$sql='INSERT INTO [xyz].[myTable] (Field1, Field2, Field3) OUTPUT Inserted.ID VALUES  (1, 2, '3')';

Note that in Perl DBI you would then execute the INSERT statement, just like it was a SELECT. And capture the output like it was a SELECT

$sth->execute($sql);
@row=$sth->fetchrow_array; #Only 1 val in 1 row returned
print "Inserted ID: ", $row[0], "\n";

Presumably this is preferable because it doesn't require another request.

How to get the file-path of the currently executing javascript code

I just made this little trick :

window.getRunningScript = () => {
    return () => {      
        return new Error().stack.match(/([^ \n])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0]
    }
}
console.log('%c Currently running script:', 'color: blue', getRunningScript()())

screenshot

? Works on: Chrome, Firefox, Edge, Opera

Enjoy !

Why is "npm install" really slow?

This link helped me boost npm installs. Force npm to use http over https and disable progress display.

Fixed header table with horizontal scrollbar and vertical scrollbar on

This is not an easy one. I've come up with a Script solution. (I don't think this can be done using pure CSS)

the HTML stays the same as you posted, the CSS changes a little bit, JQuery code added.

Working Fiddle Tested on: IE10, IE9, IE8, FF, Chrome

BTW: if you have unique elements, why don't you use id's instead of classes? I think it gives a better selector performance.

Explanation of how it works: inner-container will span the entire space of the outer-container (so basically, he's not needed) but I left him there, so you wont need to change you DOM.

the table-header is relatively positioned, without a scroll (overflow: hidden), we will handle his scroll later.

the table-body have to span the rest of the inner-container height, so I used a script to determine what height to fix him. (it changes dynamically when you re-size the window) without a fixed height, the scroll wont appear, because the div will just grow large instead.. notice that this part can be done without script, if you fix the header height and use CSS3 (as shown in the end of the answer)

now it's just a matter of moving the header along with the body each time we scroll. this is done by a function assigned to the scroll event.

CSS (some of it was copied from your style)

*
{
    padding: 0;
    margin: 0;
}

body
{
    height: 100%;
    width: 100%;
}
table
{
    border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
.outer-container
{
    background-color: #ccc;
    position: absolute;
    top:0;
    left: 0;
    right: 300px;
    bottom: 40px;
}

.inner-container
{
    height: 100%;
    overflow: hidden;
}

.table-header
{
    position: relative;
}
.table-body
{
    overflow: auto;
}

.header-cell
{
    background-color: yellow;
    text-align: left;
    height: 40px;
}
.body-cell 
{
    background-color: blue;
    text-align: left;
}
.col1, .col3, .col4, .col5
{
    width:120px;
    min-width: 120px;
}
.col2
{
    min-width: 300px;
}

JQuery

$(document).ready(function () {
    setTableBody();
    $(window).resize(setTableBody);
    $(".table-body").scroll(function ()
    {
        $(".table-header").offset({ left: -1*this.scrollLeft });
    });
});

function setTableBody()
{
    $(".table-body").height($(".inner-container").height() - $(".table-header").height());
}

If you don't care about fixing the header height (I saw that you fixed the cell's height in your CSS), some of the Script can be skiped if you use CSS3 :Shorter Fiddle (this will not work on IE8)

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

Make sure the target window that you (or Facebook) is posting a message to, has completed loading. Most of the times I've gotten this error were when an iframe I was sending messages to had failed to load.

Best way to change the background color for an NSView

In swift you can subclass NSView and do this

class MyView:NSView {
    required init?(coder: NSCoder) {
        super.init(coder: coder);

        self.wantsLayer = true;
        self.layer?.backgroundColor = NSColor.redColor().CGColor;
    }
}

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

Setting format and value in input type="date"

The format is YYYY-MM-DD. You cannot change it.

$('#myinput').val('2013-12-31'); sets value

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

Steps for MIUI 9 and Above:

Settings -> Additional Settings -> Developer options ->

  1. Turn off "MIUI optimization" and Restart

  2. Turn On "USB Debugging"

  3. Turn On "Install via USB"

  4. Set USB Configuration to Charging

  5. Turn On "install via USB

    MTP(Media Transfer Protocol) is the default mode.
    Works even in MTP in some cases

Java - How to find the redirected url of a url?

I'd actually suggest using a solid open-source library as an http client. If you take a look at http client by ASF you'll find life a lot easier. It is an easy-to-use,scalable and robust client for http.

Hive insert query like SQL

To insert entire data of table2 in table1. Below is a query:

INSERT INTO TABLE table1 SELECT * FROM table2; 

How to prevent scrollbar from repositioning web page?

I think not. But styling body with overflow: scroll should do. You seem to know that, though.

HTTP Range header

Contrary to Mark Novakowski answer, which for some reason has been upvoted by many, yes, it is a valid and satisfiable request.

In fact the standard, as Wrikken pointed out, makes just such an example. In practice, Apache responds to such requests as expected (with a 206 code), and this is exactly what I use to implement progressive download, that is, only get the tail of a long log file which grows in real time with polling.

Angular 2 router no base href set

Check your index.html. If you have accidentally removed the following part, include it and it will be fine

<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

Error 0x80005000 and DirectoryServices

The same error occurs if in DirectoryEntry.Patch is nothing after the symbols "LDAP//:". It is necessary to check the directoryEntry.Path before directorySearcher.FindOne(). Unless explicitly specified domain, and do not need to "LDAP://".

private void GetUser(string userName, string domainName)
{
     DirectoryEntry dirEntry = new DirectoryEntry();

     if (domainName.Length > 0)
     {
          dirEntry.Path = "LDAP://" + domainName;
     }

     DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
     dirSearcher.SearchScope = SearchScope.Subtree;
     dirSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(sn={0}*)(givenName={0})(sAMAccountName={0}*)))", userName);
     var searchResults = dirSearcher.FindAll();
     //var searchResults = dirSearcher.FindOne();

     if (searchResults.Count == 0)
     {
          MessageBox.Show("User not found");
     }
     else
     {
          foreach (SearchResult sr in searchResults)
          {
              var de = sr.GetDirectoryEntry();
              string user = de.Properties["SAMAccountName"][0].ToString();
              MessageBox.Show(user); 
          }        
     }
}

Is there a Newline constant defined in Java like Environment.Newline in C#?

As of Java 7 (and Android API level 19):

System.lineSeparator()

Documentation: Java Platform SE 7


For older versions of Java, use:

System.getProperty("line.separator");

See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.

C# static class why use?

Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.

Change the color of cells in one column when they don't match cells in another column

  1. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:

    enter image description here

  2. Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):

    =$A1<>$B1
    

    enter image description here

  3. Then press OK and that should do it.

    enter image description here

How to restore PostgreSQL dump file into Postgres databases?

The problem with your attempt at the psql command line is the direction of the slashes:

newTestDB-# /i E:\db-rbl-restore-20120511_Dump-20120514.sql   # incorrect
newTestDB-# \i E:/db-rbl-restore-20120511_Dump-20120514.sql   # correct

To be clear, psql commands start with a backslash, so you should have put \i instead. What happened as a result of your typo is that psql ignored everything until finding the first \, which happened to be followed by db, and \db happens to be the psql command for listing table spaces, hence why the output was a List of tablespaces. It was not a listing of "default tables of PostgreSQL" as you said.

Further, it seems that psql expects the filepath argument to delimit directories using the forward slash regardless of OS (thus on Windows this would be counter-intuitive).

It is worth noting that your attempt at "elevating permissions" had no relation to the outcome of the command you attempted to execute. Also, you did not say what caused the supposed "Permission Denied" error.

Finally, the extension on the dump file does not matter, in fact you don't even need an extension. Indeed, pgAdmin suggests a .backup extension when selecting a backup filename, but you can actually make it whatever you want, again, including having no extension at all. The problem is that pgAdmin seems to only allow a "Restore" of "Custom or tar" or "Directory" dumps (at least this is the case in the MAC OS X version of the app), so just use the psql \i command as shown above.

Change placeholder text

var input = document.getElementById ("IdofInput");
input.placeholder = "No need to fill this field";

You can find out more about placeholder here: http://help.dottoro.com/ljgugboo.php

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.

'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.

Validate IPv4 address in Java

my solution (supports leading 0s):

   String pattern="^[0-9](\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25?[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?$";

What is the easiest way to parse an INI File in C++?

If you need a cross-platform solution, try Boost's Program Options library.

Proper way to get page content

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages 
the_ID();
the_title();

//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}

endwhile;

//if you want specific page of content then write in loop

  if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
    {
    echo get_the_ID();
    the_title();
    the_content();
    }

How do I add an existing directory tree to a project in Visual Studio?

In Visual Studio 2017, you switch between Solution View and Folder View back and forth. I think this is a better option, because it will keep the solution cleaner. I use this to edit .gitignore, .md files, etc.

Solution View and Folder View

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

How do I install Python OpenCV through Conda?

To install OpenCV in Anaconda, start up the Anaconda command prompt and install OpenCV with

conda install -c https://conda.anaconda.org/menpo opencv3

Test that it works in your Anaconda Spyder or IPython console with

import cv2

You can also check the installed version using:

cv2.__version__

All shards failed

If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:

curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
    "index" : {
        "number_of_replicas" : 0
    }
}'

Doing this you'll force to use es without replicas

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I had the same problem when I upgraded jquery UI to 1.8.1 without upgrading the corresponding theme. Only is needed to upgrade the theme too and "auto" works again.

Is there a template engine for Node.js?

If you like haml, but want something even better check out http://jade-lang.com for node, I wrote haml.js as well :)

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I had the same problem. When i was trying and testing on a browser on my PC machine i didn't have the "not a function" error, but when i tried on a virtual machine the error was popping. I'd solved it by adding the slick files on my web server and adding the urls of the css and js files from my web server to my html. Before that i was pulling the css and js from CDN.

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

How can I hide an HTML table row <tr> so that it takes up no space?

Can you include some code? I add style="display:none;" to my table rows all the time and it effectively hides the entire row.

Where is nodejs log file?

If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name

That will show you STDOUT and STDERR.

How do I collapse a table row in Bootstrap?

You can do this without any JavaScript involved

(Using accepted answer)

HTML

<table class="table table-bordered table-striped">
    <tr>
        <td><button class="btn" data-target="#collapseme" data-toggle="collapse" type="button">Click to expand</button></td>
    </tr>
    <tr>
        <td class="nopadding">
            <div class="collapse" id="collapseme">
                <div class="content">
                    Show me collapsed
                </div>
            </div>
        </td>
    </tr>
</table>

CSS

.nopadding {
    padding: 0 !important;
}

.content {
    padding: 20px;
}

What are the advantages of NumPy over regular Python lists?

Here's a nice answer from the FAQ on the scipy.org website:

What advantages do NumPy arrays offer over (nested) Python lists?

Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.

How to trim white space from all elements in array?

String val = "hi hello prince";
String arr[] = val.split(" ");

for (int i = 0; i < arr.length; i++)
{   
     System.out.print(arr[i]);
}

Convert float to double without losing precision

Does this work?

float flt = 145.664454;

Double dbl = 0.0;
dbl += flt;

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

In my case I rename a component file, an VS Code add the below line of code for me:

import React, { Component } from "./node_modules/react";

So I fixed by removing the: ./node_modules/

import React, { Component } from "react";

Cheers!

How can I count the number of children?

You can do this using jQuery:

This method gets a list of its children then counts the length of that list, as simple as that.

$("ul").find("*").length;

The find() method traverses DOM downwards along descendants, all the way down to the last descendant.

Note: children() method traverses a single level down the DOM tree.

What techniques can be used to speed up C++ compilation times?

More RAM.

Someone talked about RAM drives in another answer. I did this with a 80286 and Turbo C++ (shows age) and the results were phenomenal. As was the loss of data when the machine crashed.

Better way to right align text in HTML Table

This doesn't work in IE6, which may be an issue, but it'll work in IE7+ and Firefox, Safari etc. It'll align the 3rd column right and all of the subsequent columns left.

td + td + td { text-align: right; }
td + td + td + td { text-align: left; }

Parsing Json rest api response in C#

  1. Create classes that match your data,
  2. then use JSON.NET to convert the JSON data to regular C# objects.

Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below

Step 2: JToken.Parse(...).ToObject<RootObject>().

public class Meta
{
    public int code { get; set; }
    public string status { get; set; }
    public string method_name { get; set; }
}

public class Photos
{
    public int total_count { get; set; }
}

public class Storage
{
    public int used { get; set; }
}

public class Stats
{
    public Photos photos { get; set; }
    public Storage storage { get; set; }
}

public class From
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ParticipateUser
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ChatGroup
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public List<ParticipateUser> participate_users { get; set; }
}

public class Chat
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public From from { get; set; }
    public ChatGroup chat_group { get; set; }
}

public class Response
{
    public List<Chat> chats { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Response response { get; set; }
}

Linq to Sql: Multiple left outer joins

In VB.NET using Function,

Dim query = From order In dc.Orders
            From vendor In 
            dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty()
            From status In 
            dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty()
            Select Order = order, Vendor = vendor, Status = status 

How to keep Docker container running after starting services?

Capture the PID of the ngnix process in a variable (for example $NGNIX_PID) and at the end of the entrypoint file do

wait $NGNIX_PID 

In that way, your container should run until ngnix is alive, when ngnix stops, the container stops as well

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

An HTML response from the web server normally indicates that an error page has been served instead of the response from the WCF service. My first suggestion would be to check that the user you're running the WCF client under has access to the resource.

How to use http.client in Node.js if there is basic authorization

An easier solution is to use the user:pass@host format directly in the URL.

Using the request library:

var request = require('request'),
    username = "john",
    password = "1234",
    url = "http://" + username + ":" + password + "@www.example.com";

request(
    {
        url : url
    },
    function (error, response, body) {
        // Do more stuff with 'body' here
    }
);

I've written a little blogpost about this as well.

How to split elements of a list?

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Android SDK Manager Not Installing Components

Solution for macOS

  1. click right on AndroidStudio.app -> show Package Contents -> MacOS
  2. now drag & dropping the studio-executable in a terminal
  3. sudo! (Ctrl+A places your cursor in front)
  4. start the SDK Manager inside AS to get your stuff (you will have root access)

https://www.youtube.com/watch?v=ZPnu3Nrd1u0&feature=youtu.be

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

How to match a substring in a string, ignoring case

You can use in operator in conjunction with lower method of strings.

if "mandy" in line.lower():

error: passing xxx as 'this' argument of xxx discards qualifiers

Member functions that do not modify the class instance should be declared as const:

int getId() const {
    return id;
}
string getName() const {
    return name;
}

Anytime you see "discards qualifiers", it's talking about const or volatile.

How to maintain state after a page refresh in React.js?

We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.

When the user selects an option, we can push the value of that onto the current route with:

history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});

pathname can be the current path. In your case params would look something like:

{
  selectedOption: 5
}

Then at the top level of the React tree, React Router will update the props of that component with a prop of location.search which is the encoded value we set earlier, so there will be something in componentWillReceiveProps like:

params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});

Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.

React Router: https://github.com/reactjs/react-router

History: https://github.com/ReactTraining/history

The query string library: https://github.com/ljharb/qs

What does "pending" mean for request in Chrome Developer Window?

The fix, for me, was to add the following to the top of the php file which was being requested.

header("Cache-Control: no-cache,no-store");

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Setting locales in terminal resolved the issue for me. Open the terminal and

  1. Check if locale settings are missing

    > locale
    LANG=
    LC_COLLATE="C"
    LC_CTYPE="UTF-8"
    LC_MESSAGES="C"
    LC_MONETARY="C"
    LC_NUMERIC="C"
    LC_TIME="C"
    LC_ALL=
    
  2. Edit ~/.profile or ~/.bashrc

    export LANG=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    
  3. Run . ~/.profile or . ~/.bashrc to read from the file.

  4. Open a new terminal window and check that the locales are properly set

    > locale
    LANG="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_CTYPE="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_ALL="en_US.UTF-8"
    

Get current batchfile directory

System read-only variable %CD% keeps the path of the caller of the batch, not the batch file location.

You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch.bat). Parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\) and %~f0 will return the full pathname (e.g. W:\scripts\mybatch.cmd).

You can refer to other files in the same folder as the batch script by using this syntax:

CALL %0\..\SecondBatch.cmd

This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will give you the filename of the batch script.

When the %0 variable is expanded, the result is enclosed in quotation marks.

More on batch parameters.

Random numbers with Math.random() in Java

Yours: Lowest possible is min, highest possible is max+min-1

Google: Lowest possible is min, highest possible is max-1

Fatal error: Maximum execution time of 30 seconds exceeded

I had the same problem and solved it by changing the value for the param max_execution_time in php.ini, like this:

max_execution_time = 360      ; Maximum execution time of each script, in seconds (I CHANGED THIS VALUE)
max_input_time = 120          ; Maximum amount of time each script may spend parsing request data
;max_input_nesting_level = 64 ; Maximum input variable nesting level
memory_limit = 128M           ; Maximum amount of memory a script may consume (128MB by default)

I hope this could help you.

Can I run a 64-bit VMware image on a 32-bit machine?

I honestly doubt it, for a number of reasons, but the most important one is that there are some instructions that are allowed in 32-bit mode, but not in 64-bit mode. Specifically, the REX prefix that is used to encode some instructions and registers in 64-bit mode is a byte of the form 0x4f:0x40, but in 32 bit mode the same byte is either INC or DEC with a fixed operand.
Because of this, any 64-bit instruction that is prefixed by REX will be interpreted as either INC or DEC, and won't give the VMM the chance to emulate the 64-bit instruction (for instance by signaling an undefined opcode exception).

The only way it might be done is to use a trap exception to return to the VMM after each and every instruction so that it can see if it needs special 64-bit handling. I simply can't see that happening.

Ubuntu, how do you remove all Python 3 but not 2

neither try any above ways nor sudo apt autoremove python3 because it will remove all gnome based applications from your system including gnome-terminal. In case if you have done that mistake and left with kernal only than trysudo apt install gnome on kernal.

try to change your default python version instead removing it. you can do this through bashrc file or export path command.

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

I routinely use INSERT IGNORE, and it sounds like exactly the kind of behavior you're looking for as well. As long as you know that rows which would cause index conflicts will not be inserted and you plan your program accordingly, it shouldn't cause any trouble.

Google Maps JavaScript API RefererNotAllowedMapError

According the google docs this happened because the url on which you are using the Google Maps API, it not registered in list of allowed referrers

EDIT :

From Google Docs

All subdomains of a specified domain are also authorized.

If http://example.com is authorized, then http://www.example.com is also authorized. The reverse is not true: if http://www.example.com is authorized, http://example.com is not necessarily authorized

So,Please configure http://testdomain.com domain, then your http://www.testdomain.com will start work.

Moving from position A to position B slowly with animation

You can animate it after the fadeIn completes using the callback as shown below:

$("#Friends").fadeIn('slow',function(){
  $(this).animate({'top': '-=30px'},'slow');
});

How do you detect where two line segments intersect?

I tried lot of ways and then I decided to write my own. So here it is:

bool IsBetween (float x, float b1, float b2)
{
   return ( ((x >= (b1 - 0.1f)) && 
        (x <= (b2 + 0.1f))) || 
        ((x >= (b2 - 0.1f)) &&
        (x <= (b1 + 0.1f))));
}

bool IsSegmentsColliding(   POINTFLOAT lineA,
                POINTFLOAT lineB,
                POINTFLOAT line2A,
                POINTFLOAT line2B)
{
    float deltaX1 = lineB.x - lineA.x;
    float deltaX2 = line2B.x - line2A.x;
    float deltaY1 = lineB.y - lineA.y;
    float deltaY2 = line2B.y - line2A.y;

    if (abs(deltaX1) < 0.01f && 
        abs(deltaX2) < 0.01f) // Both are vertical lines
        return false;
    if (abs((deltaY1 / deltaX1) -
        (deltaY2 / deltaX2)) < 0.001f) // Two parallel line
        return false;

    float xCol = (  (   (deltaX1 * deltaX2) * 
                        (line2A.y - lineA.y)) - 
                    (line2A.x * deltaY2 * deltaX1) + 
                    (lineA.x * deltaY1 * deltaX2)) / 
                 ((deltaY1 * deltaX2) - (deltaY2 * deltaX1));
    float yCol = 0;
    if (deltaX1 < 0.01f) // L1 is a vertical line
        yCol = ((xCol * deltaY2) + 
                (line2A.y * deltaX2) - 
                (line2A.x * deltaY2)) / deltaX2;
    else // L1 is acceptable
        yCol = ((xCol * deltaY1) +
                (lineA.y * deltaX1) -
                (lineA.x * deltaY1)) / deltaX1;

    bool isCol =    IsBetween(xCol, lineA.x, lineB.x) &&
            IsBetween(yCol, lineA.y, lineB.y) &&
            IsBetween(xCol, line2A.x, line2B.x) &&
            IsBetween(yCol, line2A.y, line2B.y);
    return isCol;
}

Based on these two formulas: (I simplified them from equation of lines and other formulas)

formula for x

formula for y

Call a child class method from a parent class object

I had the same situation and I found a way around with a bit of engineering as follows - -

  1. You have to have your method in parent class without any parameter and use - -

    Class<? extends Person> cl = this.getClass(); // inside parent class
    
  2. Now, with 'cl' you can access all child class fields with their name and initialized values by using - -

    cl.getDeclaredFields(); cl.getField("myfield"); // and many more
    
  3. In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.

  4. Another thing you might need to use is Object obj = cl.newInstance();

Let me know if still you got stucked somewhere.

Fetch: reject promise and catch the error if status is not OK?

For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable

Solution 1: Not throwing an error, handle the error ourselves

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response

    if (fetchResult.ok) {
      return result; // return success object
    }


    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    const error = new Error();
    error.info = responseError;

    return (error);
  }

Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error

    return;
  }
  debug.log('Success saving user', userSaved); // handle success

Solution 2: Throwing an error, using try/catch

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

Solution 3: Using customer error

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    throw new ClassError(result.message, result.data, result.code);
  }

And:

class ClassError extends Error {

  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }

}

Hope it helped.

How to add fonts to create-react-app based projects?

You can use the Web API FontFace constructor (also Typescript) without need of CSS:

export async function loadFont(fontFamily: string, url: string): Promise<void> {
    const font = new FontFace(fontFamily, `local(${fontFamily}), url(${url})`);
    // wait for font to be loaded
    await font.load();
    // add font to document
    document.fonts.add(font);
    // enable font with CSS class
    document.body.classList.add("fonts-loaded");
}
import ComicSans from "./assets/fonts/ComicSans.ttf";

loadFont("Comic Sans ", ComicSans).catch((e) => {
    console.log(e);
});

Declare a file font.ts with your modules (TS only):

declare module "*.ttf";
declare module "*.woff";
declare module "*.woff2";

If TS cannot find FontFace type as its still officially WIP, add this declaration to your project. It will work in your browser, except for IE.

How a thread should close itself in Java?

If you simply call interrupt(), the thread will not automatically be closed. Instead, the Thread might even continue living, if isInterrupted() is implemented accordingly. The only way to guaranteedly close a thread, as asked for by OP, is

Thread.currentThread().stop();

Method is deprecated, however.

Calling return only returns from the current method. This only terminates the thread if you're at its top level.

Nevertheless, you should work with interrupt() and build your code around it.

How do I get rid of the b-prefix in a string in python?

you need to decode the bytes of you want a string:

b = b'1234'
print(b.decode('utf-8'))  # '1234'

From inside of a Docker container, how do I connect to the localhost of the machine?

if you use docker-compose, maybe it can work:

iptables -I INPUT ! -i eth0 -p tcp --dport 8001 -j ACCEPT

the eth0 is your network interface that connect internet, and 8081 the host server port

the best way for iptables rule is iptables TRACE

Find the unique values in a column and then sort them

sort sorts inplace so returns nothing:

In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a

Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)

So you have to call print a again after the call to sort.

Eg.:

In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)

[1 2 3 6 8]

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

Alternative to sp_defaultdb (which will be removed in a future version of Microsoft SQL Server) could be ALTER LOGIN:

ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]

Note: unlike the sp_defaultdb solution user and database names are provided without quotes. Brackets are needed if name had special chars (most common example will be domain user which is domain\username and won't work without brackets).

Fatal error: Call to undefined function imap_open() in PHP

For Xampp 7.3.9

PHP.ini line 913:

;extension=imap

You should remove the semicolon.

File input 'accept' attribute - is it useful?

If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server...
Same for the <input type="hidden" name="MAX_FILE_SIZE" value="100000"> tag: if the browser uses it, it won't send the file but an error resulting in UPLOAD_ERR_FORM_SIZE (2) error in PHP (not sure how it is handled in other languages).
Note these are helps for the user. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.

How do I increase modal width in Angular UI Bootstrap?

Use max-width on modal-dialog for angular 5

.mod-class .modal-dialog {
    max-width: 1000px;
}

and use windowClass as others recommended, TS eg:

this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
        (result) => {
            // this.closeResult = `Closed with: ${result}`;
         }, (reason) => {
            // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});

Also, I had to put the css code in global styles > styles.css.

Connect with SSH through a proxy

In my case since I had a jump host or Bastion host on the way, and because the signatures on these bastion nodes had changed since they were imported into known_hosts file, I just needed to delete those entries/lines from the following file:

/Users/a.abdi-kelishami/.ssh/known_hosts

From above file, delete those lines referring to the bastion hosts.

Explain the concept of a stack frame in a nutshell

"A call stack is composed of stack frames..." — Wikipedia

A stack frame is a thing that you put on the stack. They are data structures that contain information about subroutines to call.

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

Node.js: socket.io close client connection

try this to close the connection:

socket.close();

and if you want to open it again:

socket.connect();

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

How to load a UIView using a nib file created with Interface Builder

You should not be setting the class of your view controller to be a subclass of UIView in Interface Builder. That is most definitely at least part of your problem. Leave that as either UIViewController, some subclass of it, or some other custom class you have.

As for loading only a view from a xib, I was under the assumption that you had to have some sort of view controller (even if it doesn't extend UIViewController, which may be too heavyweight for your needs) set as the File's Owner in Interface Builder if you want to use it to define your interface. I did a little research to confirm this as well. This is because otherwise there would be no way to access any of the interface elements in the UIView, nor would there be a way to have your own methods in code be triggered by events.

If you use a UIViewController as your File's Owner for your views, you can just use initWithNibName:bundle: to load it and get the view controller object back. In IB, make sure you set the view outlet to the view with your interface in the xib. If you use some other type of object as your File's Owner, you'll need to use NSBundle's loadNibNamed:owner:options: method to load the nib, passing an instance of File's Owner to the method. All its properties will be set properly according to the outlets you define in IB.

Eclipse interface icons very small on high resolution screen in Windows 8.1

Following solution worked for me

First you need to add this registry key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\PreferExternalManifest (DWORD) to 1

Next, a manifest file with the same name as the executable must be present in the same folder as the executable. The file is named eclipse.exe.manifest and consists of:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
    <description>eclipse</description>
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
            <requestedPrivileges>
                <requestedExecutionLevel xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3"
                               level="asInvoker"
                               ms_asmv3:uiAccess="false">
                </requestedExecutionLevel>
            </requestedPrivileges>
        </security>
    </trustInfo>
    <asmv3:application>
        <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
            <ms_windowsSettings:dpiAware xmlns:ms_windowsSettings="http://schemas.microsoft.com/SMI/2005/WindowsSettings">false</ms_windowsSettings:dpiAware>
        </asmv3:windowsSettings>
    </asmv3:application>
</assembly>

you can find more details here

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

Creating static library worked for me, compiling using g++ -static. It bundles the dependent libraries along with the build.

How to use data-binding with Fragment

One can simply retrieve view object as mentioned below

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

View view = DataBindingUtil.inflate(inflater, R.layout.layout_file, container, false).getRoot();

return view;

}

libz.so.1: cannot open shared object file

I've downloaded these packages:

  • libc6-i386
  • lib32stdc++6
  • lib32gcc1
  • lib32ncurses5
  • zlib1g

I then unpacked them and added the directories to LD_LIBRARY_PATH in my ~/.bashrc. Just make sure to add proper dirs to the path.

PHP get dropdown value and text

You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...

<option value="2|Dog">Dog</option>

Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.

The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.

Simple and fast method to compare images for similarity

Can the screenshot or icon be transformed (scaled, rotated, skewed ...)? There are quite a few methods on top of my head that could possibly help you:

  • Simple euclidean distance as mentioned by @carlosdc (doesn't work with transformed images and you need a threshold).
  • (Normalized) Cross Correlation - a simple metrics which you can use for comparison of image areas. It's more robust than the simple euclidean distance but doesn't work on transformed images and you will again need a threshold.
  • Histogram comparison - if you use normalized histograms, this method works well and is not affected by affine transforms. The problem is determining the correct threshold. It is also very sensitive to color changes (brightness, contrast etc.). You can combine it with the previous two.
  • Detectors of salient points/areas - such as MSER (Maximally Stable Extremal Regions), SURF or SIFT. These are very robust algorithms and they might be too complicated for your simple task. Good thing is that you do not have to have an exact area with only one icon, these detectors are powerful enough to find the right match. A nice evaluation of these methods is in this paper: Local invariant feature detectors: a survey.

Most of these are already implemented in OpenCV - see for example the cvMatchTemplate method (uses histogram matching): http://dasl.mem.drexel.edu/~noahKuntz/openCVTut6.html. The salient point/area detectors are also available - see OpenCV Feature Detection.

How to display line numbers in 'less' (GNU)

The command line flags -N or --LINE-NUMBERS causes a line number to be displayed at the beginning of each line in the display.

You can also toggle line numbers without quitting less by typing -N<return>. It it possible to toggle any of less's command line options in this way.

How prevent CPU usage 100% because of worker process in iis

If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.

This worked for me on my local machine

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

CardView background color always white

app:cardBackgroundColor="#488747"

use this in your card view and you can change a color of your card view

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

How can I remove punctuation from input text in Java?

You can use following regular expression construct

Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

inputString.replaceAll("\\p{Punct}", "");

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

Pass accepts header parameter to jquery ajax

Although some of them are correct, I've found quite confusing the previous responses. At the same time, the OP asked for a solution without setting a custom header or using beforeSend, so I've being looking for a clearer explanation. I hope my conclusions provide some light to others.

The code

jQuery.ajax({
    .... 
    accepts: "application/json; charset=utf-8",
    ....
});

doesn't work because accepts must be a PlainObject (not a String) according to the jQuery doc (http://api.jquery.com/jquery.ajax/). Specifically, jQuery expect zero or more key-value pairs relating each dataType with the accepted MIME type for them. So what I've finally using is:

jQuery.ajax({
    ....
    dataType: 'json',
    accepts: {
        json: 'application/json'
    },
    ....
});

Recommended SQL database design for tags or tagging

Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:

Use two tables:

Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID

Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title

This has some major advantages:

First it makes development much simpler: in the three-table solution for insert and update of item you have to lookup the Tag table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.

Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all Tags for one Item, draw a Tag-Cloud and select all items for one Tag Title.

All Tags for one Item:

3-Table:

SELECT Tag.Title 
  FROM Tag 
  JOIN ItemTag ON Tag.TagID = ItemTag.TagID
 WHERE ItemTag.ItemID = :id

2-Table:

SELECT Tag.Title
FROM Tag
WHERE Tag.ItemID = :id

Tag-Cloud:

3-Table:

SELECT Tag.Title, count(*)
  FROM Tag
  JOIN ItemTag ON Tag.TagID = ItemTag.TagID
 GROUP BY Tag.Title

2-Table:

SELECT Tag.Title, count(*)
  FROM Tag
 GROUP BY Tag.Title

Items for one Tag:

3-Table:

SELECT Item.*
  FROM Item
  JOIN ItemTag ON Item.ItemID = ItemTag.ItemID
  JOIN Tag ON ItemTag.TagID = Tag.TagID
 WHERE Tag.Title = :title

2-Table:

SELECT Item.*
  FROM Item
  JOIN Tag ON Item.ItemID = Tag.ItemID
 WHERE Tag.Title = :title

But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.

The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.

The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags "foo" to "bar"'.

So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)

Graphical HTTP client for windows

You could try Jsonium tool http://jsonium.org- nice free tool specialized on requests with JSON in bodies and responses