Programs & Examples On #Createtextnode

This method is used to create a new text node within the HTML/XML document.

adding text to an existing text element in javascript via DOM

   <!DOCTYPE html>
   <html>
   <head>
   <script   src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
   $("#btn1").click(function(){
    $("p").append(" <b>Appended text</b>.");
   });

  });
 </script>
  </head>
 <body>

 <p>This is a paragraph.</p>
  <p>This is another paragraph.</p>



 <button id="btn1">Append text</button>


</body>
</html>

Uncaught TypeError: Cannot read property 'appendChild' of null

If this is happening to you in an AJAX post, you'll want to compare the values that you're sending and the values that the Controller is expecting.

In my case, I had changed a parameter in a serializable class from State to StateID, and then in an AJAX call didn't change the receiving field out 'data'

success: function (data) { MakeAddressForm.formData.StateID = data.State;

Note that the class was changed - it doesn't matter what I call it in the formData.

This created a null reference in the formData which I was trying to post back to the Controller once I'd done the update. Obviously, if someone changed the state (which was the purpose of the form) then they didn't get the error, so it made for a hard one to find.

This also through a 500 error. I'm posting this here in hopes it saves someone else the time I've wasted

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

Javascript Uncaught Reference error Function is not defined

If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:

$('#exampleBtn').click(function() {
  function();
});

how to add new <li> to <ul> onclick with javascript

First you have to create a li(with id and value as you required) then add it to your ul.

Javascript ::

addAnother = function() {
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    var children = ul.children.length + 1
    li.setAttribute("id", "element"+children)
    li.appendChild(document.createTextNode("Element "+children));
    ul.appendChild(li)
}

Check this example that add li element to ul.

Creating SVG elements dynamically with javascript inside HTML

Add this to html:

<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>

Try this function and adapt for you program:

var svgNS = "http://www.w3.org/2000/svg";  

function createCircle()
{
    var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
    myCircle.setAttributeNS(null,"id","mycircle");
    myCircle.setAttributeNS(null,"cx",100);
    myCircle.setAttributeNS(null,"cy",100);
    myCircle.setAttributeNS(null,"r",50);
    myCircle.setAttributeNS(null,"fill","black");
    myCircle.setAttributeNS(null,"stroke","none");

    document.getElementById("mySVG").appendChild(myCircle);
}     

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

jQuery append() vs appendChild()

I know this is an old and answered question and I'm not looking for votes I just want to add an extra little thing that I think might help newcomers.

yes appendChild is a DOM method and append is JQuery method but practically the key difference is that appendChild takes a node as a parameter by that I mean if you want to add an empty paragraph to the DOM you need to create that p element first

var p = document.createElement('p')

then you can add it to the DOM whereas JQuery append creates that node for you and adds it to the DOM right away whether it's a text element or an html element or a combination!

$('p').append('<span> I have been appended </span>');

Create table using Javascript

Here is the latest method using the .map function in javascript.

Simple table code..

<table class="table table-hover">
    <thead class="thead-dark">
        <tr>
         <th scope="col">Tour</th>
         <th scope="col">Day</th>
         <th scope="col">Time</th>
         <th scope="col">Highlights</th>
         <th scope="col">Action</th>
       </tr>
    </thead>
  <tbody id="tableBody">
                            
  </tbody>

and here is javascript code to append something in the table body.

    const data = "some kind of json data or object of arrays";
                const tableData = data.map(function(value){
                    return (
                        `<tr>
                            <td>${value.Name}</td>
                            <td>${value.Day}</td>
                            <td>${value.Time}</td>
                            <td>${value.Highlights}</td>
                            <td class="text-center"><a class="btn btn-primary" href="route.html?id=${value.ID}" role="button">Details</a></td>
                        </tr>`
                    );
                }).join('');
            const tabelBody = document.querySelector("#tableBody");
                tableBody.innerHTML = tableData;

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

PHP XML how to output nice format

You can try to do this:

...
// get completed xml document
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$xml_string = $doc->saveXML();
echo $xml_string;

You can make set these parameter right after you've created the DOMDocument as well:

$doc = new DomDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

That's probably more concise. Output in both cases is (Demo):

<?xml version="1.0"?>
<root>
  <error>
    <a>eee</a>
    <b>sd</b>
    <c>df</c>
  </error>
  <error>
    <a>eee</a>
    <b>sd</b>
    <c>df</c>
  </error>
  <error>
    <a>eee</a>
    <b>sd</b>
    <c>df</c>
  </error>
</root>

I'm not aware how to change the indentation character(s) with DOMDocument. You could post-process the XML with a line-by-line regular-expression based replacing (e.g. with preg_replace):

$xml_string = preg_replace('/(?:^|\G)  /um', "\t", $xml_string);

Alternatively, there is the tidy extension with tidy_repair_string which can pretty print XML data as well. It's possible to specify indentation levels with it, however tidy will never output tabs.

tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);

Dynamic creation of table with DOM

You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:

var table = document.createElement('table');
for (var i = 1; i < 4; i++){
    var tr = document.createElement('tr');   

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode('Text1');
    var text2 = document.createTextNode('Text2');

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);

How do I append a node to an existing XML file in java

If you need to insert node/element in some specific place , you can to do next steps

  1. Divide original xml into two parts
  2. Append your new node/element as child to first first(the first part should ended with element after wich you wanna add your element )
  3. Append second part to the new document.

It is simple algorithm but should works...

Error on line 2 at column 1: Extra content at the end of the document

The problem is database connection string, one of your MySQL database connection function parameter is not correct ,so there is an error message in the browser output, Just right click output webpage and view html source code you will see error line followed by correct XML output data(file). I had same problem and the above solution worked perfectly.

Add CSS to <head> with JavaScript?

Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';

Older answer below.


You could use the jQuery library to select your head element and append HTML to it, in a manner like:

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

You can find a complete tutorial for this problem here

Get the last item in an array

Performance

Today 2020.05.16 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6

Conclusions

  • arr[arr.length-1] (D) is recommended as fastest cross-browser solution
  • mutable solution arr.pop() (A) and immutable _.last(arr) (L) are fast
  • solutions I, J are slow for long strings
  • solutions H, K (jQuery) are slowest on all browsers

enter image description here

Details

I test two cases for solutions:

  • mutable: A, B, C,

  • immutable: D, E, F, G, H, I, J (my),

  • immutable from external libraries: K, L, M,

for two cases

  • short string - 10 characters - you can run test HERE
  • long string - 1M characters - you can run test HERE

_x000D_
_x000D_
function A(arr) {
  return arr.pop();
}

function B(arr) {  
  return arr.splice(-1,1);
}

function C(arr) {  
  return arr.reverse()[0]
}

function D(arr) {
  return arr[arr.length - 1];
}

function E(arr) {
  return arr.slice(-1)[0] ;
}

function F(arr) {
  let [last] = arr.slice(-1);
  return last;
}

function G(arr) {
  return arr.slice(-1).pop();
}

function H(arr) {
  return [...arr].pop();
}

function I(arr) {  
  return arr.reduceRight(a => a);
}

function J(arr) {  
  return arr.find((e,i,a)=> a.length==i+1);
}

function K(arr) {  
  return $(arr).get(-1);
}

function L(arr) {  
  return _.last(arr);
}

function M(arr) {  
  return _.nth(arr, -1);
}






// ----------
// TEST
// ----------

let loc_array=["domain","a","b","c","d","e","f","g","h","file"];

log = (f)=> console.log(`${f.name}: ${f([...loc_array])}`);

[A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> log(f));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Example results for Chrome for short string

enter image description here

Executing <script> elements inserted with .innerHTML

Made this new helper function in TypeScript, maybe someone will appreciate it. If you remove type declaration from script parameter it will just be plain JS.

_x000D_
_x000D_
const evalPageScripts = () => {
  const scripts = document.querySelectorAll('script');

  scripts.forEach((script: HTMLScriptElement) => {
    const newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = script.src;

    if (script.parentNode) {
      script.parentNode.removeChild(script);
    }

    return document.body.appendChild(newScript);
  })
};

export default evalPageScripts;
_x000D_
_x000D_
_x000D_

Get the string representation of a DOM node

Under FF you can use the XMLSerializer object to serialize XML into a string. IE gives you an xml property of a node. So you can do the following:

function xml2string(node) {
   if (typeof(XMLSerializer) !== 'undefined') {
      var serializer = new XMLSerializer();
      return serializer.serializeToString(node);
   } else if (node.xml) {
      return node.xml;
   }
}

Creating the checkbox dynamically using JavaScript?

You're trying to put a text node inside an input element.

Input elements are empty and can't have children.

...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";

var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));

container.appendChild(checkbox);
container.appendChild(label);

Verify if file exists or not in C#

Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

How to sort 2 dimensional array by column value?

The best approach would be to use the following, as there may be repetitive values in the first column.

var arr = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];

arr.sort(function(a,b) {
    return a[0]-b[0]
});

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

How To Remove Outline Border From Input Button

This one worked for me

button:focus {
    border: none;
    outline: none;
}

HQL Hibernate INNER JOIN

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;

List<Address> addList=new ArrayList<Address>();


@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
    return addList;
}

public void setAddList(List<Address> addList) {
    this.addList = addList;
}
}

We have two entities Employee and Address with One to Many relationship.

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address implements Serializable{

private static final long serialVersionUID = 1L;

private int address_id;
private String address;
Employee employee;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
    return address_id;
}
public void setAddress_id(int address_id) {
    this.address_id = address_id;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
    return employee;
}
public void setEmployee(Employee employee) {
    this.employee = employee;
}
}

By this way we can implement inner join between two tables

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Main {

public static void main(String[] args) {
    saveEmployee();

    retrieveEmployee();

}

private static void saveEmployee() {
    Employee employee=new Employee();
    Employee employee1=new Employee();
    Employee employee2=new Employee();
    Employee employee3=new Employee();

    Address address=new Address();
    Address address1=new Address();
    Address address2=new Address();
    Address address3=new Address();

    address.setAddress("1485,Sector 42 b");
    address1.setAddress("1485,Sector 42 c");
    address2.setAddress("1485,Sector 42 d");
    address3.setAddress("1485,Sector 42 a");

    employee.setEmpName("Varun");
    employee1.setEmpName("Krishan");
    employee2.setEmpName("Aasif");
    employee3.setEmpName("Dut");

    address.setEmployee(employee);
    address1.setEmployee(employee1);
    address2.setEmployee(employee2);
    address3.setEmployee(employee3);

    employee.getAddList().add(address);
    employee1.getAddList().add(address1);
    employee2.getAddList().add(address2);
    employee3.getAddList().add(address3);

    Session session=HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();

    session.save(employee);
    session.save(employee1);
    session.save(employee2);
    session.save(employee3);
    session.getTransaction().commit();
    session.close();
}

private static void retrieveEmployee() {
    try{

    String sqlQuery="select e from Employee e inner join e.addList";

    Session session=HibernateUtil.getSessionFactory().openSession();

    Query query=session.createQuery(sqlQuery);

    List<Employee> list=query.list();

     list.stream().forEach((p)->{System.out.println(p.getEmpName());});     
    session.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.

 public class HibernateUtil {
 private static SessionFactory sessionFactory ;
 static {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(Employee.class);
    configuration.addAnnotatedClass(Address.class);
                  configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
    configuration.setProperty("hibernate.connection.username", "root");     
    configuration.setProperty("hibernate.connection.password", "root");
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");


   // configuration
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
} 

Creating a List of Lists in C#

public class ListOfLists<T> : List<List<T>>
{
}


var myList = new ListOfLists<string>();

Nested Recycler view height doesn't wrap its content

As @yigit mentioned, you need to override onMeasure(). Both @user2302510 and @DenisNek have good answers but if you want to support ItemDecoration you can use this custom layout manager.

And other answers cannot scroll when there are more items than can be displayed on the screen though. This one is using default implemantation of onMeasure() when there are more items than screen size.

public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {
        measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);

        if (getOrientation() == HORIZONTAL) {
            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }

    // If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
    if (height < heightSize && width < widthSize) {

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {

   View view = recycler.getViewForPosition(position);

   // For adding Item Decor Insets to view
   super.measureChildWithMargins(view, 0, 0);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom() + getPaddingBottom() + getDecoratedBottom(view) , p.height);
            view.measure(childWidthSpec, childHeightSpec);

            // Get decorated measurements
            measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
            measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

And if you want to use it with GridLayoutManager just extends it from GridLayoutManager and change

for (int i = 0; i < getItemCount(); i++)

to

for (int i = 0; i < getItemCount(); i = i + getSpanCount())

What do these three dots in React do?

This is a new feature in ES6/Harmony. It is called the Spread Operator. It lets you either separate the constituent parts of an array/object, or take multiple items/parameters and glue them together. Here is an example:

let array = [1,2,3]
let array2 = [...array]
// array2 is now filled with the items from array

And with an object/keys:

// lets pass an object as props to a react component
let myParameters = {myKey: 5, myOtherKey: 7}
let component = <MyComponent {...myParameters}/>
// this is equal to <MyComponent myKey=5 myOtherKey=7 />

What's really cool is you can use it to mean "the rest of the values".

const myFunc = (value1, value2, ...values) {
    // Some code
}

myFunc(1, 2, 3, 4, 5)
// when myFunc is called, the rest of the variables are placed into the "values" array

Difference between JSONObject and JSONArray

The usage of both can be depended on the structure of your data.

Simply, You can use the Nested Objects approach if you plan to give priority to a unique identifier such as a Primary Key.

eg:

  {
     "Employees" : {
           "001" : {
               "Name" : "Alan",
               "Children" : ["Walker", "Dua", "Lipa"]
                },
           "002" : {
               "Name" : "Ezio",
               "Children" : ["Kenvey", "Connor", "Edward"]
                }
      }

Or, Use the Array first approach if you intend to store a set of values with no need to identify uniquely.

eg:

 [
     {
        "Employees":[
               {
                   "Name" : "Alan",
                   "Children" : ["Walker", "Dua", "Lipa"]
               },
               {
                   "Name" : "Ezio",
                   "Children" : ["Kenvey", "Connor", "Edward"]
               }
          ]
       }
   ]

Although you could use the second method with an identifier, it can be harder or too complex to query and understand in some scenarios. Also depending on the database one may have to apply a suitable approach. Eg: MongoDB / Firebase

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I had same problem and despite having jstl

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

I had to add 'standard' as well:

<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

Also, as mentioned in previous post:

Conversion between UTF-8 ArrayBuffer and String

There's a polyfill for Encoding over on Github: text-encoding. It's easy for Node or the browser, and the Readme advises the following:

var uint8array = TextEncoder(encoding).encode(string);
var string = TextDecoder(encoding).decode(uint8array);

If I recall, 'utf-8' is the encoding you need, and of course you'll need to wrap your buffer:

var uint8array = new Uint8Array(utf8buffer);

Hope it works as well for you as it has for me.

c - warning: implicit declaration of function ‘printf’

You need to include the appropriate header

#include <stdio.h>

If you're not sure which header a standard function is defined in, the function's man page will state this.

Functions that return a function

Returning b is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing.

In your case, returning b returns the thing, the thing is a callable function. Returning b() returns the value returned by the callable function.

Consider this code:

function b() {
   return 42;
}

Using the above definition, return b(); returns the value 42. On the other hand return b; returns a function, that itself returns the value of 42. They are two different things.

How to get index using LINQ?

Simply do :

int index = List.FindIndex(your condition);

E.g.

int index = cars.FindIndex(c => c.ID == 150);

How Long Does it Take to Learn Java for a Complete Newbie?

You can definitely get a good understanding of Java in 10 weeks, but as mentioned before, practice makes perfect (or at least better...). A couple of starting places:

The Java API will be your friend: http://java.sun.com/j2se/1.5.0/docs/api/

Java has a lot of built-in functionality so try not to duplicate it (String functions and whatnot).

Also, an IDE might make some things a little more complicated, but it'll also help you find your way around the API. Eclipse is a good place to start (and it's free) http://www.eclipse.org/

Hope that helps a little..

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

I had the same issue. I used yarn instead of npm to install the dependencies and it worked.

yarn add *****

Microsoft Excel mangles Diacritics in .csv files?

The answer for all combinations of Excel versions (2003 + 2007) and file types

Most other answers here concern their Excel version only and will not necessarily help you, because their answer just might not be true for your version of Excel.

For example, adding the BOM character introduces problems with automatic column separator recognition, but not with every Excel version.

There are 3 variables that determines if it works in most Excel versions:

  • Encoding
  • BOM character presence
  • Cell separator

Somebody stoic at SAP tried every combination and reported the outcome. End result? Use UTF16le with BOM and tab character as separator to have it work in most Excel versions.

You don't believe me? I wouldn't either, but read here and weep: http://wiki.sdn.sap.com/wiki/display/ABAP/CSV+tests+of+encoding+and+column+separator

Bash loop ping successful

I use this Bash script to test the internet status every minute on OSX

#address=192.168.1.99  # forced bad address for testing/debugging
address=23.208.224.170 # www.cisco.com
internet=1             # default to internet is up

while true;
do
    # %a  Day of Week, textual
    # %b  Month, textual, abbreviated
    # %d  Day, numeric
    # %r  Timestamp AM/PM
    echo -n $(date +"%a, %b %d, %r") "-- " 
    ping -c 1 ${address} > /tmp/ping.$
    if [[ $? -ne 0 ]]; then
        if [[ ${internet} -eq 1 ]]; then   # edge trigger -- was up now down
            echo -n $(say "Internet down") # OSX Text-to-Speech
            echo -n "Internet DOWN"
        else
            echo -n "... still down"
        fi
        internet=0
    else
        if [[ ${internet} -eq 0 ]]; then     # edge trigger -- was down now up
            echo -n $(say "Internet back up") # OSX Text-To-Speech
        fi
        internet=1
    fi   
    cat /tmp/ping.$ | head -2 | tail -1
    sleep 60 ; # sleep 60 seconds =1 min
done

How do I lowercase a string in Python?

Don't try this, totally un-recommend, don't do this:

import string
s='ABCD'
print(''.join([string.ascii_lowercase[string.ascii_uppercase.index(i)] for i in s]))

Output:

abcd

Since no one wrote it yet you can use swapcase (so uppercase letters will become lowercase, and vice versa) (and this one you should use in cases where i just mentioned (convert upper to lower, lower to upper)):

s='ABCD'
print(s.swapcase())

Output:

abcd

Xcode 5 and iOS 7: Architecture and Valid architectures

My understanding from Apple Docs.

  • What is Architectures (ARCHS) into Xcode build-settings?
    • Specifies architecture/s to which the binary is TARGETED. When specified more that one architecture, the generated binary may contain object code for each of the specified architecture.
  • What is Valid Architectures (VALID_ARCHS) into Xcode build-settings?

    • Specifies architecture/s for which the binary may be BUILT.
    • During build process, this list is intersected with ARCHS and the resulting list specifies the architectures the binary can run on.
  • Example :- One iOS project has following build-settings into Xcode.

    • ARCHS = armv7 armv7s
    • VALID_ARCHS = armv7 armv7s arm64
    • In this case, binary will be built for armv7 armv7s arm64 architectures. But the same binary will run on ONLY ARCHS = armv7 armv7s.

Adding an onclick event to a div element

maybe your script tab has some problem.

if you set type, must type="application/javascript".

<!DOCTYPE html>
<html>
    <head>
        <title>
            Hello
        </title>
    </head>
    <body>
        <div onclick="showMsg('Hello')">
            Click me show message
        </div>
        <script type="application/javascript">
            function showMsg(item) {
            alert(item);
        }
        </script>
    </body>
</html>

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

The idea of retrying the query in case of Deadlock exception is good, but it can be terribly slow, since mysql query will keep waiting for locks to be released. And incase of deadlock mysql is trying to find if there is any deadlock, and even after finding out that there is a deadlock, it waits a while before kicking out a thread in order to get out from deadlock situation.

What I did when I faced this situation is to implement locking in your own code, since it is the locking mechanism of mysql is failing due to a bug. So I implemented my own row level locking in my java code:

private HashMap<String, Object> rowIdToRowLockMap = new HashMap<String, Object>();
private final Object hashmapLock = new Object();
public void handleShortCode(Integer rowId)
{
    Object lock = null;
    synchronized(hashmapLock)
    {
      lock = rowIdToRowLockMap.get(rowId);
      if (lock == null)
      {
          rowIdToRowLockMap.put(rowId, lock = new Object());
      }
    }
    synchronized (lock)
    {
        // Execute your queries on row by row id
    }
}

Loop through each row of a range in Excel

In Loops, I always prefer to use the Cells class, using the R1C1 reference method, like this:

Cells(rr, col).Formula = ...

This allows me to quickly and easily loop over a Range of cells easily:

Dim r As Long
Dim c As Long

c = GetTargetColumn() ' Or you could just set this manually, like: c = 1

With Sheet1 ' <-- You should always qualify a range with a sheet!

    For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)

        ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
        .Cells(r, c).Value = MyListOfStuff(r)

        '---- or ----

        '...to easily copy from one place to another (even with an offset of rows and columns)
        .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value


    Next r

End With

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

Bootstrap full responsive navbar with logo or brand name text

If you want to achieve this (you can resize the window to see how it will look for mobile version), all you have to do is to have 2 logo images (1 for desktop and one for mobile) and display them depending of the enviroment using visible-xs and hidden-xs classes.

So i used something like this:

<img class="hidden-xs" src="http://placehold.it/150x50&text=Logo" alt="">
<img class="visible-xs" src="http://placehold.it/120x40&text=Logo" alt=""> 

And ofcourse, i styled the mobile logo using:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand img {
        margin-top: 5px;
        margin-left: 5px;
    }
}

You can see all the code here. In case you need a text on mobile version insted of the logo, it's not a big deal. Just replace the logo with a <h1 class="visible-xs">AppName</h3> and change the style inside the media query like this:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand h1{
        //here add your style depending of the position you want the text to be placed
    }
} 

EDIT:

You need this conditions to make it work:

.navbar-toggle {
   margin: 23px 0; 
}

.navbar-nav, .navbar-nav li, .navbar-nav li a {
  height: 80px;
  line-height: 80px;
}

.navbar-nav li a {
  padding-top: 0;
  padding-bottom:0;
}

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Below is a workaround demo image of ; Uncheck Offline work option by going to:

File -> Settings -> Build, Execution, Deployment -> Gradle

enter image description here

If above workaround not works then try this:

  1. Open the build.gradle file for your application.

  2. Make sure that the repositories section includes a maven section with the "https://maven.google.com" endpoint. For example:

    allprojects {
         repositories {
             jcenter()
             maven {
                 url "https://maven.google.com"
             }
         }
    }
    
  3. Add the support library to the dependencies section. For example, to add the v4 core-utils library, add the following lines:

    dependencies {
        ...
        compile "com.android.support:support-core-utils:27.1.0"
    }
    

Caution: Using dynamic dependencies (for example, palette-v7:23.0.+) can cause unexpected version updates and regression incompatibilities. We recommend that you explicitly specify a library version (for example, palette-v7:27.1.0).

Manifest Declaration Changes

Specifically, you should update the android:minSdkVersion element of the <uses-sdk> tag in the manifest to the new, lower version number, as shown below:

<uses-sdk
  android:minSdkVersion="14"
  android:targetSdkVersion="23" />

If you are using Gradle build files, the minSdkVersion setting in the build file overrides the manifest settings.

apply plugin: 'com.android.application'

android {
   ...
      defaultConfig {
            minSdkVersion 16
            ...
        }
        ...
    }

Following Android Developer Library Support.

What is a reasonable code coverage % for unit tests (and why)?

If this were a perfect world, 100% of code would be covered by unit tests. However, since this is NOT a perfect world, it's a matter of what you have time for. As a result, I recommend focusing less on a specific percentage, and focusing more on the critical areas. If your code is well-written (or at least a reasonable facsimile thereof) there should be several key points where APIs are exposed to other code.

Focus your testing efforts on these APIs. Make sure that the APIs are 1) well documented and 2) have test cases written that match the documentation. If the expected results don't match up with the docs, then you have a bug in either your code, documentation, or test cases. All of which are good to vet out.

Good luck!

How to decompile to java files intellij idea

Some time ago I used JAD (JAva Decompiler) to achieve this - I do not think IntelliJ's decompiler was incorporated with exporting in mind. It is more of a tool to help look through classes where sources are not available.

JAD is still available for download, but I do not think anyone maintains it anymore: http://varaneckas.com/jad/

There were numerous plugins for it, namely Jadclipse (you guessed it, a way to use JAD in Eclipse - see decompiled classes where code is not available :)).

How to concatenate text from multiple rows into a single text string in SQL server?

To avoid null values you can use CONCAT()

DECLARE @names VARCHAR(500)
SELECT @names = CONCAT(@names, ' ', name) 
FROM Names
select @names

difference between width auto and width 100 percent

Width 100% : It will make content with 100%. margin, border, padding will be added to this width and element will overflow if any of these added.

Width auto : It will fit the element in available space including margin, border and padding. space remaining after adjusting margin + padding + border will be available width/ height.

Width 100% + box-sizing: border box : It will also fits the element in available space including border, padding (margin will make it overflow the container).

PHP: If internet explorer 6, 7, 8 , or 9

Here is a great resource for detecting browsers in php: http://php.net/manual/en/function.get-browser.php

Here is one of the examples that seems the simplest:

<?php
function get_user_browser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = '';
    if(preg_match('/MSIE/i',$u_agent))
    {
        $ub = "ie";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $ub = "firefox";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $ub = "safari";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $ub = "chrome";
    }
    elseif(preg_match('/Flock/i',$u_agent))
    {
        $ub = "flock";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $ub = "opera";
    }

    return $ub;
}
?>

Then later in your code you could say something like

$browser = get_user_browser();
if($browser == "ie"){
    //do stuff
}

DTO pattern: Best way to copy properties between two objects

I had an application that I needed to convert from a JPA entity to DTO, and I thought about it and finally came up using org.springframework.beans.BeanUtils.copyProperties for copying simple properties and also extending and using org.springframework.binding.convert.service.DefaultConversionService for converting complex properties.

In detail my service was something like this:

@Service("seedingConverterService")
public class SeedingConverterService extends DefaultConversionService implements ISeedingConverterService  {
    @PostConstruct
    public void init(){
        Converter<Feature,FeatureDTO> featureConverter = new Converter<Feature, FeatureDTO>() {

            @Override
            public FeatureDTO convert(Feature f) {
                FeatureDTO dto = new FeatureDTO();
                //BeanUtils.copyProperties(f, dto,"configurationModel");
                BeanUtils.copyProperties(f, dto);
                dto.setConfigurationModelId(f.getConfigurationModel()==null?null:f.getConfigurationModel().getId());
                return dto;
            }
        };

        Converter<ConfigurationModel,ConfigurationModelDTO> configurationModelConverter = new Converter<ConfigurationModel,ConfigurationModelDTO>() {
            @Override
            public ConfigurationModelDTO convert(ConfigurationModel c) {
                ConfigurationModelDTO dto = new ConfigurationModelDTO();
                //BeanUtils.copyProperties(c, dto, "features");
                BeanUtils.copyProperties(c, dto);
                dto.setAlgorithmId(c.getAlgorithm()==null?null:c.getAlgorithm().getId());
                List<FeatureDTO> l = c.getFeatures().stream().map(f->featureConverter.convert(f)).collect(Collectors.toList());
                dto.setFeatures(l);
                return dto;
            }
        };
        addConverter(featureConverter);
        addConverter(configurationModelConverter);
    }
}

Creating a new database and new connection in Oracle SQL Developer

This tutorial should help you:

Getting Started with Oracle SQL Developer

See the prerequisites:

  1. Install Oracle SQL Developer. You already have it.
  2. Install the Oracle Database. Download available here.
  3. Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:

    alter user hr identified by hr account unlock;

  4. Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.


Another version from May 2011: Getting Started with Oracle SQL Developer


For more info check this related question:

How to create a new database after initally installing oracle database 11g Express Edition?

How to use variables in SQL statement in Python?

Meanwhile there is another way of how to do it with f-strings:

cursor.execute(f"INSERT INTO table VALUES {var1}, {var2}, {var3},")

Google Chrome forcing download of "f.txt" file

I experienced the same issue, same version of Chrome though it's unrelated to the issue. With the developer console I captured an instance of the request that spawned this, and it is an API call served by ad.doubleclick.net. Specifically, this resource returns a response with Content-Disposition: attachment; filename="f.txt".

The URL I happened to capture was https://ad.doubleclick.net/adj/N7412.226578.VEVO/B8463950.115078190;sz=300x60...

Per curl:

$ curl -I 'https://ad.doubleclick.net/adj/N7412.226578.VEVO/B8463950.115078190;sz=300x60;click=https://2975c.v.fwmrm.net/ad/l/1?s=b035&n=10613%3B40185%3B375600%3B383270&t=1424475157058697012&f=&r=40185&adid=9201685&reid=3674011&arid=0&auid=&cn=defaultClick&et=c&_cc=&tpos=&sr=0&cr=;ord=435266097?'
HTTP/1.1 200 OK
P3P: policyref="https://googleads.g.doubleclick.net/pagead/gcn_p3p_.xml", CP="CURa ADMa DEVa TAIo PSAo PSDo OUR IND UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"
Date: Fri, 20 Feb 2015 23:35:38 GMT
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Cache-Control: no-cache, must-revalidate
Content-Type: text/javascript; charset=ISO-8859-1
X-Content-Type-Options: nosniff
Content-Disposition: attachment; filename="f.txt"
Server: cafe
X-XSS-Protection: 1; mode=block
Set-Cookie: test_cookie=CheckForPermission; expires=Fri, 20-Feb-2015 23:50:38 GMT; path=/; domain=.doubleclick.net
Alternate-Protocol: 443:quic,p=0.08
Transfer-Encoding: chunked
Accept-Ranges: none
Vary: Accept-Encoding

How to move the layout up when the soft keyboard is shown android

If you are working with xamarin, you can put this code WindowSoftInputMode =Android.Views.SoftInput.AdjustPan | Android.Views.SoftInput.AdjustResize in activity attribute of the MainActivity class. For example, now the activity attribute will look like below

    [Activity(WindowSoftInputMode =Android.Views.SoftInput.AdjustPan | Android.Views.SoftInput.AdjustResize)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        //some code here.
    }

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

this is what i used:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

ReferenceError: $ is not defined

Your widget has Underscore.js/LoDash.js as dependency.

You can get them here: underscore, lodash

Try prepending this to your code, so you can see if it works:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>

How can javascript upload a blob?

I could not get the above example to work with blobs and I wanted to know what exactly is in upload.php. So here you go:

(tested only in Chrome 28.0.1500.95)

// javascript function that uploads a blob to upload.php
function uploadBlob(){
    // create a blob here for testing
    var blob = new Blob(["i am a blob"]);
    //var blob = yourAudioBlobCapturedFromWebAudioAPI;// for example   
    var reader = new FileReader();
    // this function is triggered once a call to readAsDataURL returns
    reader.onload = function(event){
        var fd = new FormData();
        fd.append('fname', 'test.txt');
        fd.append('data', event.target.result);
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            // print the output from the upload.php script
            console.log(data);
        });
    };      
    // trigger the read from the reader...
    reader.readAsDataURL(blob);

}

The contents of upload.php:

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data, 
echo ($decodedData);
$filename = "test.txt";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

Increment a Integer's int value?

Integer objects are immutable. You can't change the value of the integer held by the object itself, but you can just create a new Integer object to hold the result:

Integer start = new Integer(5);
Integer end = start + 5; // end == 10;

How can I make a list of lists in R?

Using your example::

list1 <- list()
list1[1] = 1
list1[2] = 2
list2 <- list()
list2[1] = 'a'
list2[2] = 'b'
list_all <- list(list1, list2)

Use '[[' to retrieve an element of a list:

b = list_all[[1]]
 b
[[1]]
[1] 1

[[2]]
[1] 2

class(b)
[1] "list"

Explicitly select items from a list or tuple

Another possible solution:

sek=[]
L=[1,2,3,4,5,6,7,8,9,0]
for i in [2, 4, 7, 0, 3]:
   a=[L[i]]
   sek=sek+a
print (sek)

How to draw border on just one side of a linear layout?

There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi directory, it works px based, and in the drawable-mdpi works approximately as dp base (thanks to resample).

Example file for the original question (border-right:1px solid red;) is here:

http://ge.tt/517ZIFC2/v/3?c

Just place it to the drawable-nodpi directory.

Dynamically load JS inside JS

You can do it using JQuery:

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
  console.log(data); //data returned
  console.log(textStatus); //success
  console.log(jqxhr.status); //200
  console.log('Load was performed.');
});

this link should help: http://api.jquery.com/jQuery.getScript/

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

Bootstrap change carousel height

This worked for me.

.carousel-item {
  height: 500px;
}

.item, img{
    position: absolute;
    object-fit:cover;
    height: 100% !important;
    width:  100% !important;
    /*min-height: 500px;*/
}

How do you copy the contents of an array to a std::vector in C++ without looping?

There have been many answers here and just about all of them will get the job done.

However there is some misleading advice!

Here are the options:

vector<int> dataVec;

int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
unsigned dataArraySize = sizeof(dataArray) / sizeof(int);

// Method 1: Copy the array to the vector using back_inserter.
{
    copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));
}

// Method 2: Same as 1 but pre-extend the vector by the size of the array using reserve
{
    dataVec.reserve(dataVec.size() + dataArraySize);
    copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));
}

// Method 3: Memcpy
{
    dataVec.resize(dataVec.size() + dataArraySize);
    memcpy(&dataVec[dataVec.size() - dataArraySize], &dataArray[0], dataArraySize * sizeof(int));
}

// Method 4: vector::insert
{
    dataVec.insert(dataVec.end(), &dataArray[0], &dataArray[dataArraySize]);
}

// Method 5: vector + vector
{
    vector<int> dataVec2(&dataArray[0], &dataArray[dataArraySize]);
    dataVec.insert(dataVec.end(), dataVec2.begin(), dataVec2.end());
}

To cut a long story short Method 4, using vector::insert, is the best for bsruth's scenario.

Here are some gory details:

Method 1 is probably the easiest to understand. Just copy each element from the array and push it into the back of the vector. Alas, it's slow. Because there's a loop (implied with the copy function), each element must be treated individually; no performance improvements can be made based on the fact that we know the array and vectors are contiguous blocks.

Method 2 is a suggested performance improvement to Method 1; just pre-reserve the size of the array before adding it. For large arrays this might help. However the best advice here is never to use reserve unless profiling suggests you may be able to get an improvement (or you need to ensure your iterators are not going to be invalidated). Bjarne agrees. Incidentally, I found that this method performed the slowest most of the time though I'm struggling to comprehensively explain why it was regularly significantly slower than method 1...

Method 3 is the old school solution - throw some C at the problem! Works fine and fast for POD types. In this case resize is required to be called since memcpy works outside the bounds of vector and there is no way to tell a vector that its size has changed. Apart from being an ugly solution (byte copying!) remember that this can only be used for POD types. I would never use this solution.

Method 4 is the best way to go. It's meaning is clear, it's (usually) the fastest and it works for any objects. There is no downside to using this method for this application.

Method 5 is a tweak on Method 4 - copy the array into a vector and then append it. Good option - generally fast-ish and clear.

Finally, you are aware that you can use vectors in place of arrays, right? Even when a function expects c-style arrays you can use vectors:

vector<char> v(50); // Ensure there's enough space
strcpy(&v[0], "prefer vectors to c arrays");

Hope that helps someone out there!

What is the right way to treat argparse.Namespace() as a dictionary?

Is it proper to "reach into" an object and use its dict property?

In general, I would say "no". However Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

On the other hand, Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__, but the limits of my imagination are not the same as yours.

How do shift operators work in Java?

I think it would be the following, for example:

  • Signed left shift

[ 2 << 1 ] is => [10 (binary of 2) add 1 zero at the end of the binary string] Hence 10 will be 100 which becomes 4.

Signed left shift uses multiplication... So this could also be calculated as 2 * (2^1) = 4. Another example [2 << 11] = 2 *(2^11) = 4096

  • Signed right shift

[ 4 >> 1 ] is => [100 (binary of 4) remove 1 zero at the end of the binary string] Hence 100 will be 10 which becomes 2.

Signed right shift uses division... So this could also be calculated as 4 / (2^1) = 2 Another example [4096 >> 11] = 4096 / (2^11) = 2

What is the syntax meaning of RAISERROR()

according to MSDN

RAISERROR ( { msg_id | msg_str | @local_variable }
    { ,severity ,state }
    [ ,argument [ ,...n ] ] )
    [ WITH option [ ,...n ] ]

16 would be the severity.
1 would be the state.

The error you get is because you have not properly supplied the required parameters for the RAISEERROR function.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

In PostgreSQL there is no merge command, and actually writing it is not trivial - there are actually strange edge cases that make the task "interesting".

The best (as in: working in the most possible conditions) approach, is to use function - such as one shown in manual (merge_db).

If you don't want to use function, you can usually get away with:

updated = db.execute(UPDATE ... RETURNING 1)
if (!updated)
  db.execute(INSERT...)

Just remember that it is not fault proof and it will fail eventually.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

Django Admin - change header 'Django administration' text

You just override the admin/base_site.html template (copy the template from django.contrib.admin.templates and put in your own admin template dir) and replace the branding block.

Failed to execute 'atob' on 'Window'

here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.

http://jsfiddle.net/tZPg4/9397/

stack overflow requires I include some code with a jsFiddle link so please ignore snippet:

localStorage.setItem(...)

How to set maximum fullscreen in vmware?

From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.

Difference between git pull and git pull --rebase

For this is important to understand the difference between Merge and Rebase.

Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards.

For details refer - http://www.derekgourlay.com/archives/428

100% height minus header?

As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.

The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

reading HttpwebResponse json response, C#

If you're getting source in Content Use the following method

try
{
    var response = restClient.Execute<List<EmpModel>>(restRequest);

    var jsonContent = response.Content;

    var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);

    foreach (EmpModel item in data)
    {
        listPassingData?.Add(item);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Data get mathod problem {ex} ");
}

How to split a dos path into its components in Python

I use the following as since it uses the os.path.basename function it doesn't add any slashes to the returned list. It also works with any platform's slashes: i.e window's \\\\ or unix's /. And furthermore, it doesn't add the \\\\\\\\ that windows uses for server paths :)

def SplitPath( split_path ):
    pathSplit_lst   = []
    while os.path.basename(split_path):
        pathSplit_lst.append( os.path.basename(split_path) )
        split_path = os.path.dirname(split_path)
    pathSplit_lst.reverse()
    return pathSplit_lst

So for:

\\\\\\\server\\\\folder1\\\\folder2\\\\folder3\\\\folder4

You get:

['server','folder1','folder2','folder3','folder4']

How to change navigation bar color in iOS 7 or 6?

The complete code with version checking.

 if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {

    // do stuff for iOS 7 and newer
    [self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
}
else {

    // do stuff for older versions than iOS 7
    [self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
}

How to get the name of the current method from code

Well System.Reflection.MethodBase.GetCurrentMethod().Name is not a very good choice 'cause it will just display the method name without additional information.

Like for string MyMethod(string str) the above property will return just MyMethod which is hardly adequate.

It is better to use System.Reflection.MethodBase.GetCurrentMethod().ToString() which will return the entire method signature...

How to apply a patch generated with git format-patch?

First you should take a note about difference between git am and git apply

When you are using git am you usually wanna to apply many patches. Thus should use:

git am *.patch

or just:

git am

Git will find patches automatically and apply them in order ;-)

UPD
Here you can find how to generate such patches

Generate unique random numbers between 1 and 100

Using a Set is your fastest option. Here is a generic function for getting a unique random that uses a callback generator. Now it's fast and reusable.

_x000D_
_x000D_
// Get a unique 'anything'_x000D_
let unique = new Set()_x000D_
_x000D_
function getUnique(generator) {_x000D_
  let number = generator()_x000D_
  while (!unique.add(number)) {_x000D_
    number = generator()_x000D_
  }_x000D_
  return number;_x000D_
}_x000D_
_x000D_
// The generator.  Return anything, not just numbers._x000D_
const between_1_100 = () => 1 + Math.floor(Math.random() * 100)_x000D_
_x000D_
// Test it_x000D_
for (var i = 0; i < 8; i++) {_x000D_
  const aNumber = getUnique(between_1_100)_x000D_
}_x000D_
// Dump the 'stored numbers'_x000D_
console.log(Array.from(unique))
_x000D_
_x000D_
_x000D_

Unloading classes in java?

The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.

One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server.

This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it.

If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file.

And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own.

If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class.

I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well.

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I Cleared Temp, %Temp% and Prefetch. Then tried reopening VS and was able to find the test methods

Want to show/hide div based on dropdown box selection

You need to either put your code at the end of the page or wrap it in a document ready call, otherwise you're trying to execute code on elements that don't yet exist. Also, you can reduce your code to:

$('#purpose').on('change', function () {
    $("#business").css('display', (this.value == '1') ? 'block' : 'none');
});

jsFiddle example

Convert string to date in bash

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'

IF statement: how to leave cell blank if condition is false ("" does not work)

You could try this.

=IF(A1=1,B1,TRIM(" "))

If you put this formula in cell C1, then you could test if this cell is blank in another cells

=ISBLANK(C1)

You should see TRUE. I've tried on Microsoft Excel 2013. Hope this helps.

How to execute a shell script in PHP?

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:

disable_functions = exec

And remove the exec, shell_exec entries if there are there.

Good Luck!

setting request headers in selenium

With the solutions already discussed above the most reliable one is using Browsermob-Proxy

But while working with the remote grid machine, Browsermob-proxy isn't really helpful.

This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.

  1. Add the ModHeader extension to the chrome browser

How to download the Modheader? Link

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));

// Set the Desired capabilities 
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);

// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
  1. Go to the browser extensions and capture the Local Storage context ID of the ModHeader

Capture ID from ModHeader

  1. Navigate to the URL of the ModHeader to set the Local Storage Context

.

// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");

Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
  1. Now add the headers to the request using Javascript

.

   ((Javascript)driver).executeScript(
         "localStorage.setItem('profiles', JSON.stringify([{  title: 'Selenium', hideComment: true, appendMode: '', 
             headers: [                        
               {enabled: true, name: 'token-1', value: 'value-1', comment: ''},
               {enabled: true, name: 'token-2', value: 'value-2', comment: ''}
             ],                          
             respHeaders: [],
             filters: []
          }]));");

Where token-1, value-1, token-2, value-2 are the request headers and values that are to be added.

  1. Now navigate to the required web-application.

    driver.get("your-desired-website");

jQuery animated number counter from zero to value

This is working for me

$('.Count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

jQuery toggle CSS?

For jQuery versions lower than 1.9 (see https://api.jquery.com/toggle-event):

$('#user_button').toggle(function () {
    $("#user_button").css({borderBottomLeftRadius: "0px"});
}, function () {
    $("#user_button").css({borderBottomLeftRadius: "5px"});
});

Using classes in this case would be better than setting the css directly though, look at the addClass and removeClass methods alecwh mentioned.

$('#user_button').toggle(function () {
    $("#user_button").addClass("active");
}, function () {
    $("#user_button").removeClass("active");
});

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

Were those dev-masters added automatically? Avoid them as unnecessary version constraints, for 'any suitable version' use "*", or "@dev" if you don't mind dev packages. My guess is that Entrust is the potential troublemaker.

Also, "minimum-stability": "stable" imposes additional constraints, and

"minimum-stability": "dev",
"prefer-stable": true

is more conflict-free, consider it a rule of thumb.

How do I print the content of a .txt file in Python?

This will give you the contents of a file separated, line-by-line in a list:

with open('xyz.txt') as f_obj:
    f_obj.readlines()

How to shuffle an ArrayList

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

Git - deleted some files locally, how do I get them from a remote repository

Also, I add to do the following steps so that the git repo would be correctly linked with the IDE:

 $ git reset <commit #>

 $ git checkout <file/path>

I hope this was helpful!!

How to add a "sleep" or "wait" to my Lua Script?

This homebrew function have precision down to a 10th of a second or less.

function sleep (a) 
    local sec = tonumber(os.clock() + a); 
    while (os.clock() < sec) do 
    end 
end

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

Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10.

This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions

How to access random item in list?

Printing randomly country name from JSON file.
Model:

public class Country
    {
        public string Name { get; set; }
        public string Code { get; set; }
    }

Implementaton:

string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\")) + @"Data\Country.json";
            string _countryJson = File.ReadAllText(filePath);
            var _country = JsonConvert.DeserializeObject<List<Country>>(_countryJson);


            int index = random.Next(_country.Count);
            Console.WriteLine(_country[index].Name);

How do I wait for an asynchronously dispatched block to finish?

I have to wait until a UIWebView is loaded before running my method, I was able to get this working by performing UIWebView ready checks on main thread using GCD in combination with semaphore methods mentioned in this thread. Final code looks like this:

-(void)myMethod {

    if (![self isWebViewLoaded]) {

            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

            __block BOOL isWebViewLoaded = NO;

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                while (!isWebViewLoaded) {

                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        isWebViewLoaded = [self isWebViewLoaded];
                    });

                    [NSThread sleepForTimeInterval:0.1];//check again if it's loaded every 0.1s

                }

                dispatch_sync(dispatch_get_main_queue(), ^{
                    dispatch_semaphore_signal(semaphore);
                });

            });

            while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]];
            }

        }

    }

    //Run rest of method here after web view is loaded

}

How does the getView() method work when creating your own custom adapter?

You can also find useful information about getView at the Adapter interface in Adapter.java file. It says;

/**
 * Get a View that displays the data at the specified position in the data set. You can either
 * create a View manually or inflate it from an XML layout file. When the View is inflated, the
 * parent View (GridView, ListView...) will apply default layout parameters unless you use
 * {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
 * to specify a root view and to prevent attachment to the root.
 * 
 * @param position The position of the item within the adapter's data set of the item whose view
 *        we want.
 * @param convertView The old view to reuse, if possible. Note: You should check that this view
 *        is non-null and of an appropriate type before using. If it is not possible to convert
 *        this view to display the correct data, this method can create a new view.
 *        Heterogeneous lists can specify their number of view types, so that this View is
 *        always of the right type (see {@link #getViewTypeCount()} and
 *        {@link #getItemViewType(int)}).
 * @param parent The parent that this view will eventually be attached to
 * @return A View corresponding to the data at the specified position.
 */
View getView(int position, View convertView, ViewGroup parent);

Easiest way to toggle 2 classes in jQuery

Here's another 'non-conventional' way.

  • It implies the use of underscore or lodash.
  • It assumes a context where you:
    • the element doesn't have an init class (that means you cannot do toggleClass('a b'))
    • you have to get the class dynamically from somewhere

An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).

// 1: define the array of switching classes:
var types = ['web','email'];

// 2: get the active class:
var type = $(mybutton).prop('class');

// 3: switch the class with the other on (say..) the container. You can guess the other by using _.without() on the array:
$mycontainer.removeClass(_.without(types, type)[0]).addClass(type);

Excel - extracting data based on another list

Have you tried Advanced Filter? Using your short list as the 'Criteria' and long list as the 'List Range'. Use the options: 'Filter in Place' and 'Unique Values'.

You should be presented with the list of unique values that only appear in your short list.

Alternatively, you can paste your Unique list to another location (on the same sheet), if you prefer. Choose the option 'Copy to another Location' and in the 'Copy to' box enter the cell reference (say F1) where you want the Unique list.

Note: this will work with the two columns (name/ID) too, if you select the two columns as both 'Criteria' and 'List Range'.

How to connect to SQL Server from command prompt with Windows authentication

You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:

sqlcmd /S  /d  -E

If you want to use SQL Server authentication you could try this:

sqlcmd /S  /d -U -P 

Definitions:

/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234

Hope this helps!

Table scroll with HTML and CSS

Adds a fading gradient to an overflowing HTML table element to better indicate there is more content to be scrolled.

  • Table with fixed header
  • Overflow scroll gradient
  • Custom scrollbar

See the live example below:

_x000D_
_x000D_
$("#scrolltable").html("<table id='cell'><tbody></tbody></table>");_x000D_
$("#cell").append("<thead><tr><th><div>First col</div></th><th><div>Second col</div></th></tr></thead>");_x000D_
_x000D_
for (var i = 0; i < 40; i++) {_x000D_
  $("#scrolltable > table > tbody").append("<tr><td>" + "foo" + "</td><td>" + "bar" + "</td></tr>");_x000D_
}
_x000D_
/* Table with fixed header */_x000D_
_x000D_
table,_x000D_
thead {_x000D_
  width: 100%;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
#scrolltable {_x000D_
  margin-top: 50px;_x000D_
  height: 120px;_x000D_
  overflow: auto;_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
#scrolltable table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
#scrolltable tr:nth-child(even) {_x000D_
  background: #EEE;_x000D_
}_x000D_
_x000D_
#scrolltable th div {_x000D_
  position: absolute;_x000D_
  margin-top: -30px;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom scrollbar */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
  width: 8px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-track {_x000D_
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);_x000D_
  border-radius: 10px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
  border-radius: 10px;_x000D_
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
_x000D_
/* Overflow scroll gradient */_x000D_
_x000D_
.overflow-scroll-gradient {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.overflow-scroll-gradient::after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 240px;_x000D_
  height: 25px;_x000D_
  background: linear-gradient( rgba(255, 255, 255, 0.001), white);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="overflow-scroll-gradient">_x000D_
  <div id="scrolltable">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting an integer to binary in C

Result in string

The following function converts an integer to binary in a string (n is the number of bits):

// Convert an integer to binary (in a string)
void int2bin(unsigned integer, char* binary, int n=8)
{  
  for (int i=0;i<n;i++)   
    binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
  binary[n]='\0';
}

Test online on repl.it.

Source : AnsWiki.

Result in string with memory allocation

The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):

// Convert an integer to binary (in a string)
char* int2bin(unsigned integer, int n=8)
{
  char* binary = (char*)malloc(n+1);
  for (int i=0;i<n;i++)   
    binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
  binary[n]='\0';
  return binary;
}

This option allows you to write something like printf ("%s", int2bin(78)); but be careful, memory allocated for the string must be free later.

Test online on repl.it.

Source : AnsWiki.

Result in unsigned int

The following function converts an integer to binary in another integer (8 bits maximum):

// Convert an integer to binary (in an unsigned)
unsigned int int_to_int(unsigned int k) {
    return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}

Test online on repl.it

Display result

The following function displays the binary conversion

// Convert an integer to binary and display the result
void int2bin(unsigned integer, int n=8)
{  
  for (int i=0;i<n;i++)   
    putchar ( (integer & (int)1<<(n-i-1)) ? '1' : '0' );
}

Test online on repl.it.

Source : AnsWiki.

How to prevent Screen Capture in Android

According to this official guide, you can add WindowManager.LayoutParams.FLAG_SECURE to your window layout and it will disallow screenshots.

Validate email address textbox using JavaScript

Validating email is a very important point while validating an HTML form. In this page we have discussed how to validate an email using JavaScript :

An email is a string (a subset of ASCII characters) separated into two parts by @ symbol. a "personal_info" and a domain, that is personal_info@domain. The length of the personal_info part may be up to 64 characters long and domain name may be up to 253 characters. The personal_info part contains the following ASCII characters.

  1. Uppercase (A-Z) and lowercase (a-z) English letters.
  2. Digits (0-9).
  3. Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  4. Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.

The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.

Example of valid email id

[email protected]

[email protected]

[email protected]

Example of invalid email id

mysite.ourearth.com [@ is not present]

[email protected] [ tld (Top Level domain) can not start with dot "." ]

@you.me.net [ No character before @ ]

[email protected] [ ".b" is not a valid tld ]

[email protected] [ tld can not start with dot "." ]

[email protected] [ an email should not be start with "." ]

mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ]

[email protected] [double dots are not allowed]

JavaScript code to validate an email id

function ValidateEmail(mail) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w {2, 3})+$/.test(myForm.emailAddr.value)) {
            return (true)
        }
        alert("You have entered an invalid email address!")
        return (false)
    }

Android Activity as a dialog

Set the theme in your android manifest file.

<activity android:name=".LoginActivity"
            android:theme="@android:style/Theme.Dialog"/>

And set the dialog state on touch to finish.

this.setFinishOnTouchOutside(false);

@selector() in Swift?

Since Swift 3.0 is published, it is even a little bit more subtle to declare a targetAction appropriate

class MyCustomView : UIView {

    func addTapGestureRecognizer() {

        // the "_" is important
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyCustomView.handleTapGesture(_:)))
        tapGestureRecognizer.numberOfTapsRequired = 1
        addGestureRecognizer(tapGestureRecognizer)
    }

    // since Swift 3.0 this "_" in the method implementation is very important to 
    // let the selector understand the targetAction
    func handleTapGesture(_ tapGesture : UITapGestureRecognizer) {

        if tapGesture.state == .ended {
            print("TapGesture detected")
        }
    }
}

How to change the colors of a PNG image easily?

If you are like me and Photoshop is out of your price range or just overkill for what you need. Acorn 5 is a much cheaper version of Photoshop with a lot of the same features. One of those features being a color change option. You can import all of the basic image formats including SVG and PNG. The color editing software works great and allows for basic color selection, RBG selection, hex code, or even a color grabber if you do not know the color. These color features, plus a whole lot image editing features, is definitely worth the $30. The only downside is that is currently only available on Mac.

Link to "pin it" on pinterest without generating a button

For such cases, I found very useful the Share Link Generator, it helps creating Facebook, Google+, Twitter, Pinterest, LinkedIn share buttons.

CSS 100% height with padding/margin

This is the default behavior of display: block The fastest way that you can fix it in 2020 is to set display: 'flex' of parent element and padding e.g. 20px then all its children will have 100% height relative to its height.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

For those who have this problem with collection of enums here is how to solve it:

@Enumerated(EnumType.STRING)
@Column(name = "OPTION")
@CollectionTable(name = "MY_ENTITY_MY_OPTION")
@ElementCollection(targetClass = MyOptionEnum.class, fetch = EAGER)
Collection<MyOptionEnum> options;

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

Is embedding background image data into CSS as Base64 good or bad practice?

In my case it allows me to apply a CSS stylesheet without worrying about copying associated images, since they're already embedded inside.

jQuery - how can I find the element with a certain id?

This

var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);

will find you the td that needs to be blocked.

Actually this will also do:

var verificaHorario = $("#" + horaInicial);

Testing for the size() of the wrapped set will answer your question regarding the existence of the id.

How to add an empty column to a dataframe?

an even simpler solution is:

df = df.reindex(columns = header_list)                

where "header_list" is a list of the headers you want to appear.

any header included in the list that is not found already in the dataframe will be added with blank cells below.

so if

header_list = ['a','b','c', 'd']

then c and d will be added as columns with blank cells

Can an Option in a Select tag carry multiple values?

I was actually wondering this today, and I achieved it by using the php explode function, like this:

HTML Form (in a file I named 'doublevalue.php':

    <form name="car_form" method="post" action="doublevalue_action.php">
            <select name="car" id="car">
                    <option value="">Select Car</option>
                    <option value="BMW|Red">Red BMW</option>
                    <option value="Mercedes|Black">Black Mercedes</option>
            </select>
            <input type="submit" name="submit" id="submit" value="submit">
    </form>

PHP action (in a file I named doublevalue_action.php)

    <?php
            $result = $_POST['car'];
            $result_explode = explode('|', $result);
            echo "Model: ". $result_explode[0]."<br />";
            echo "Colour: ". $result_explode[1]."<br />";
    ?>

As you can see in the first piece of code, we're creating a standard HTML select box, with 2 options. Each option has 1 value, which has a separator (in this instance, '|') to split the values (in this case, model and colour).

On the action page, I'm exploding the results into an array, then calling each one. As you can see, I've separated and labelled them so you can see the effect this is causing.

I hope this helps someone :)

Drop all tables whose names begin with a certain string

Here is my solution:

SELECT CONCAT('DROP TABLE `', TABLE_NAME,'`;') 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE 'TABLE_PREFIX_GOES_HERE%';

And of course you need to replace TABLE_PREFIX_GOES_HERE with your prefix.

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

jQuery: Get the cursor position of text in input without browser specific code?

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

PHP cURL GET request and request's body

CURLOPT_POSTFIELDS as the name suggests, is for the body (payload) of a POST request. For GET requests, the payload is part of the URL in the form of a query string.

In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.

curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);

//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

scale fit mobile web content using viewport meta tag

For Android there is the addition of target-density tag.

target-densitydpi=device-dpi

So, the code would look like

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />

Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

It should be that the particular mvn command execs and does not return, thereby not executing the rest of the commands.

Android, How can I Convert String to Date?

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

you are confusing the concept of appending and prepending. the following code is prepending:

sys.path.insert(1,'/thePathToYourFolder/')

it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. sys.path.append() puts things at the very end of the search sequence.

it is advisable that you use something like virtualenv instead of manually coding your package directories into the PYTHONPATH everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:

  1. python ecosystems introduction

  2. bootstrapping python virtual environments

if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/

What is the meaning of prepended double colon "::"?

:: is the scope resolution operator. It's used to specify the scope of something.

For example, :: alone is the global scope, outside all other namespaces.

some::thing can be interpreted in any of the following ways:

  • some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
  • some is a class available in the current scope and thing is a member object, function or type of the some class;
  • in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.

You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.

So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.

The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.

I hope this answer is complete and correct enough to help you understand scope resolution.

Linux/Unix command to determine if process is running?

None of the answers worked for me, so heres mine:

process="$(pidof YOURPROCESSHERE|tr -d '\n')"
if [[ -z "${process// }" ]]; then
  echo "Process is not running."
else
  echo "Process is running."
fi

Explanation:

|tr -d '\n'

This removes the carriage return created by the terminal. The rest can be explained by this post.

How to go back (ctrl+z) in vi/vim

The answer, u, (and many others) is in $ vimtutor.

Use JSTL forEach loop's varStatus as an ID

Its really helped me to dynamically generate ids of showDetailItem for the below code.

<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" > 
<af:showDetailItem  id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>

if you execute this line <af:outputText value="#{ttfVs}"/> prints the below:

{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}

Getting the minimum of two values in SQL

Here is a trick if you want to calculate maximum(field, 0):

SELECT (ABS(field) + field)/2 FROM Table

returns 0 if field is negative, else, return field.

Iterate keys in a C++ map

You could

  • create a custom iterator class, aggregating the std::map<K,V>::iterator
  • use std::transform of your map.begin() to map.end() with a boost::bind( &pair::second, _1 ) functor
  • just ignore the ->second member while iterating with a for loop.

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

PHP: get the value of TEXTBOX then pass it to a VARIABLE

You are posting the data, so it should be $_POST. But 'name' is not the best name to use.

name = "name"

will only cause confusion IMO.

How can I copy the output of a command directly into my clipboard?

on Wayland xcopy doesn't seem to work, use wl-clipboard instead. e.g. on fedora

sudo dnf install wl-clipboard

tree | wl-copy

wl-paste > file

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

Don´t use USB3.0 ports ... try it on a usb 2.0 port

Also try to change transfer mode, like suggested here: https://android.stackexchange.com/a/49662

Convert ArrayList<String> to String[] array

An alternative in Java 8:

String[] strings = list.stream().toArray(String[]::new);

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

Gradle, Android and the ANDROID_HOME SDK location

Just delete the sdk.dir inside the local.preoperties file and set the ANDROID_HOME environment variable . It worked for me.

How to run batch file from network share without "UNC path are not supported" message?

My situation is just a little different. I'm running a batch file on startup to distribute the latest version of internal business applications.

In this situation I'm using the Windows Registry Run Key with the following string

cmd /c copy \\serverName\SharedFolder\startup7.bat %USERPROFILE% & %USERPROFILE%\startup7.bat

This runs two commands on startup in the correct sequence. First copying the batch file locally to a directory the user has permission to. Then executing the same batch file. I can create a local directory c:\InternalApps and copy all of the files from the network.

This is probably too late to solve the original poster's question but it may help someone else.

#pragma pack effect

#pragma is used to send non-portable (as in this compiler only) messages to the compiler. Things like disabling certain warnings and packing structs are common reasons. Disabling specific warnings is particularly useful if you compile with the warnings as errors flag turned on.

#pragma pack specifically is used to indicate that the struct being packed should not have its members aligned. It's useful when you have a memory mapped interface to a piece of hardware and need to be able to control exactly where the different struct members point. It is notably not a good speed optimization, since most machines are much faster at dealing with aligned data.

Best practices for styling HTML emails

The resource I always end up going back to about HTML emails is CampaignMonitor's CSS guide.

As their business is geared solely around email delivery, they know their stuff as well as anyone is going to

Correct way of looping through C++ arrays

string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
    cout << "value of a: " << texts[a] << endl;
}

Nope. Totally a wrong way of iterating through an array. sizeof(texts) is not equal to the number of elements in the array!

The modern, C++11 ways would be to:

  • use std::array if you want an array whose size is known at compile-time; or
  • use std::vector if its size depends on runtime

Then use range-for when iterating.

#include <iostream>
#include <array>


int main() {
    std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
    // ^ An array of 3 elements with the type std::string

    for(const auto& text : texts) {   // Range-for!
        std::cout << text << std::endl;
    }
}

Live example


You may ask, how is std::array better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end on it.

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I think JAVA_HOME is the best you can do. The command-line tools like java and javac will respect that environment variable, you can use /usr/libexec/java_home -v '1.7*' to give you a suitable value to put into JAVA_HOME in order to make command line tools use Java 7.

export JAVA_HOME="`/usr/libexec/java_home -v '1.7*'`"

But standard double-clickable application bundles don't use JDKs installed under /Library/Java at all. Old-style .app bundles using Apple's JavaApplicationStub will use Apple Java 6 from /System/Library/Frameworks, and new-style ones built with AppBundler without a bundled JRE will use the "public" JRE in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home - that's hard-coded in the stub code and can't be changed, and you can't have two different public JREs installed at the same time.


Edit: I've had a look at VisualVM specifically, assuming you're using the "application bundle" version from the download page, and this particular app is not an AppBundler application, instead its main executable is a shell script that calls a number of other shell scripts and reads various configuration files. It defaults to picking the newest JDK from /Library/Java as long as that is 7u10 or later, or uses Java 6 if your Java 7 installation is update 9 or earlier. But unravelling the logic in the shell scripts it looks to me like you can specify a particular JDK using a configuration file.

Create a text file ~/Library/Application Support/VisualVM/1.3.6/etc/visualvm.conf (replace 1.3.6 with whatever version of VisualVM you're using) containing the line

visualvm_jdkhome="`/usr/libexec/java_home -v '1.7*'`"

and this will force it to choose Java 7 instead of 8.

How to convert enum names to string in c

I usually do this:

#define COLOR_STR(color)                            \
    (RED       == color ? "red"    :                \
     (BLUE     == color ? "blue"   :                \
      (GREEN   == color ? "green"  :                \
       (YELLOW == color ? "yellow" : "unknown"))))   

How do I check that a Java String is not all whitespaces?

This answer focusses more on the sidenote "i.e. has at least one alphanumeric character". Besides that, it doesn't add too much to the other (earlier) solution, except that it doesn't hurt you with NPE in case the String is null.

We want false if (1) s is null or (2) s is empty or (3) s only contains whitechars.

public static boolean containsNonWhitespaceChar(String s) {
  return !((s == null) || "".equals(s.trim()));
}

How do I set multipart in axios with react?

Here's how I do file upload in react using axios

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload

Source

Command prompt won't change directory to another drive

The short answer

The correct way to go from C:\...\Adminto D:\Docs\Java drive, is the following command :

cd /d d:\Docs\Java

More details

If you're somewhere random on your D:\ drive, and you want to go to the root of your drive, you can use this command :

cd d:\

If you're somewhere random on your D:\ drive, and you want to go to a specific folder on your drive, you can use this command :

cd d:\Docs\Java

If you're on a different drive, and you want to go to the root of your D:\ drive, you can use this command :

cd /d d:\

If you're on a different drive, and you want to go to a specific folder on your D: drive, you can use this command :

cd /d d:\Docs\Java

If you're on a different drive, and you want to go to the last open folder of you D: drive, you can use this command :

cd /d d:

As a shorthand for cd /d d:, you can also use this command :

d:

Using HTML and Local Images Within UIWebView

These answers did help me -- specifically the file:\\xxxxxxx.xxx, but I had to do a workaround to display the image.

In my case, I have an HTML file on my server which I download to the documents directory. I want to it to display with a local graphic in a UIWebView which I could not get to work. Here's what I did:

  1. Copy the file from the NSBundle to the local documents directory
  2. Reference the file in my HTML document as "file:\\filename.png"

So in startup copy the file to documents directory:

-(BOOL)copyBundleFilesToDocumentsDirectoryForFileName:(NSString *)fileNameToCopy OverwriteExisting:(BOOL)overwrite {
        //GET DOCUMENTS DIR
        //Search for standard documents using NSSearchPathForDirectoriesInDomains
        //First Param = Searching the documents directory
        //Second Param = Searching the Users directory and not the System
        //Expand any tildes and identify home directories.
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [paths objectAtIndex:0];

        //COPY FILE FROM NSBUNDLE File to Local Documents Dir
        NSString *writableFilePath = [documentsDir  stringByAppendingPathComponent:fileNameToCopy];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *fileError;

        DDLogVerbose(@"File Copy From Bundle to Documents Dir would go to this path: %@", writableFilePath);

        if ([fileManager fileExistsAtPath:writableFilePath]) {
            DDLogVerbose(@"File %@ already exists in Documents Dir", fileNameToCopy);

            if (overwrite) {
                [fileManager removeItemAtPath:writableFilePath error:nil];
                DDLogVerbose(@"OLD File %@ was Deleted from  Documents Dir Successfully", fileNameToCopy);
            } else {
                return (NO);
            }
        }

        NSArray *fileNameParts = [fileNameToCopy componentsSeparatedByString:@"."];
        NSString *bundlePath = [[NSBundle mainBundle]pathForResource:[fileNameParts objectAtIndex:0] ofType:[fileNameParts objectAtIndex:1]];
        BOOL success = [fileManager copyItemAtPath:bundlePath toPath:writableFilePath error:&fileError];

        if (success) {
            DDLogVerbose(@"Copied %@ from Bundle to Documents Dir Successfully", fileNameToCopy);
        } else {
            DDLogError(@"File %@ could NOT be copied from bundle to Documents Dir due to error %@!!", fileNameToCopy, fileError);
        }

    return (success);
}

Find a string within a cell using VBA

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

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

Option Explicit

Const strText As String = "%"

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


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

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

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

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

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

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

End Sub

How to save a dictionary to a file?

For a dictionary of strings such as the one you're dealing with, it could be done using only Python's built-in text processing capabilities.

(Note this wouldn't work if the values are something else.)

with open('members.txt') as file:
    mdict={}
    for line in file:
        a, b, c, d = line.strip().split(':')
        mdict[a] = b + ':' + c + ':' + d

a = input('ID: ')
if a not in mdict:
    print('ID {} not found'.format(a))
else:
    b, c, d = mdict[a].split(':')
    d = input('phone: ')
    mdict[a] = b + ':' + c + ':' + d  # update entry
    with open('members.txt', 'w') as file:  # rewrite file
        for id, values in mdict.items():
            file.write(':'.join([id] + values.split(':')) + '\n')

Android global variable

import android.app.Application;

public class Globals extends Application
{
    private static Globals instance = null;
    private static int RecentCompaignID;
    private static int EmailClick;
    private static String LoginPassword;
    static String loginMemberID;
    private static String CompaignName = "";
    private static int listget=0;
    //MailingDetails
    private static String FromEmailadd="";
    private static String FromName="";
    private static String ReplyEmailAdd="";
    private static String CompaignSubject="";
    private static int TempId=0;
    private static int ListIds=0;

    private static String HTMLContent="";
    @Override
    public void onCreate() 
    {
        super.onCreate();
        instance = this;
    }

    public static Globals getInstance()
    {
        return instance;
    }

    public void setRecentCompaignID(int objRecentCompaignID)
    {
        RecentCompaignID = objRecentCompaignID;
    }

    public int getRecentCompaignID() 
    {
        return RecentCompaignID;
    }

    public void setLoginMemberID(String objloginMemberID) 
    {
        loginMemberID = objloginMemberID;
    }

    public String getLoginMemberID() 
    {
        return loginMemberID;
    }

    public void setLoginMemberPassword(String objLoginPassword)
    {
        LoginPassword = objLoginPassword;
    }

    public String getLoginMemberPassword()
    {
        return LoginPassword;
    }

    public void setEmailclick(int id)
    {
        EmailClick = id;
    }

    public int getEmailClick() 
    {
        return EmailClick;
    }
    public void setCompaignName(String objCompaignName)
    {
        CompaignName=objCompaignName;
    }
    public String getCompaignName()
    {
        return CompaignName;
    }
    public void setlistgetvalue(int objlistget)
    {
        listget=objlistget;
    }
    public int getlistvalue()
    {
        return listget;
    }
    public void setCompaignSubject(String objCompaignSubject)
    {
         CompaignSubject=objCompaignSubject;
    }
    public String getCompaignSubject()
    {
        return CompaignSubject;
    }
    public void setHTMLContent(String objHTMLContent)
    {
        HTMLContent=objHTMLContent;
    }
    public String getHTMLContent()
    {
        return HTMLContent;
    }
    public void setListIds(int objListIds)
    {
        ListIds=objListIds;
    }
    public int getListIds()
    {
        return ListIds;
    }
    public void setReplyEmailAdd(String objReplyEmailAdd)
    {
        ReplyEmailAdd=objReplyEmailAdd;
    }
    public String getReplyEmailAdd()
    {
        return ReplyEmailAdd;
    }
    public void setFromName(String objFromName)
    {
        FromName=objFromName;
    }
    public String getFromName()
    {
        return FromName;
    }
    public void setFromEmailadd(String objFromEmailadd)
    {
        FromEmailadd=objFromEmailadd;
    }
    public String getFromEmailadd()
    {
        return FromEmailadd;
    }
}

Equivalent of LIMIT for DB2

Developed this method:

You NEED a table that has an unique value that can be ordered.

If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:

int start = 40000 - 10000;

int total = 25000 - 10000;

And then pass these by code to the query:

SELECT * FROM 
(SELECT * FROM schema.mytable 
ORDER BY userId DESC fetch first {start} rows only ) AS mini 
ORDER BY mini.userId ASC fetch first {total} rows only

Lotus Notes email as an attachment to another email

  1. Open msg
  2. Save to desktop
  3. Open new mail
  4. Attached *.eml file on desktop

Sad to say, this is the only way I know which sux because in Outlook, you just need to copy and paste.

Plot a horizontal line using matplotlib

Use matplotlib.pyplot.hlines:

  • Plot multiple horizontal lines by passing a list to the y parameter.
  • y can be passed as a single location: y=40
  • y can be passed as multiple locations: y=[39, 40, 41]
  • If you're a plotting a figure with something like fig, ax = plt.subplots(), then replace plt.hlines or plt.axhline with ax.hlines or ax.axhline, respectively.
  • matplotlib.pyplot.axhline can only plot a single location (e.g. y=40)

plt.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(6, 3))
plt.hlines(y=39.5, xmin=100, xmax=175, colors='aqua', linestyles='-', lw=2, label='Single Short Line')
plt.hlines(y=[39, 40, 41], xmin=[0, 25, 50], xmax=[len(xs)], colors='purple', linestyles='--', lw=2, label='Multiple Lines')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

enter image description here

ax.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6))

ax1.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
ax1.set_title('One Line')

ax2.hlines(y=[39, 40, 41], xmin=0, xmax=len(xs), colors='purple', linestyles='--', lw=2)
ax2.set_title('Multiple Lines')

plt.tight_layout()
plt.show()

enter image description here

Time Series Axis

  • xmin and xmax will accept a date like '2020-09-10' or datetime(2020, 9, 10)
    • xmin=datetime(2020, 9, 10), xmax=datetime(2020, 9, 10) + timedelta(days=3)
    • Given date = df.index[9], xmin=date, xmax=date + pd.Timedelta(days=3), where the index is a DatetimeIndex.
import pandas_datareader as web  # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt

# get test data
df = web.DataReader('^gspc', data_source='yahoo', start='2020-09-01', end='2020-09-28').iloc[:, :2]

# plot dataframe
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')

# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')

ax.legend()
plt.show()

enter image description here

  • Sample time series data if web.DataReader doesn't work.
data = {pd.Timestamp('2020-09-01 00:00:00'): {'High': 3528.03, 'Low': 3494.6}, pd.Timestamp('2020-09-02 00:00:00'): {'High': 3588.11, 'Low': 3535.23}, pd.Timestamp('2020-09-03 00:00:00'): {'High': 3564.85, 'Low': 3427.41}, pd.Timestamp('2020-09-04 00:00:00'): {'High': 3479.15, 'Low': 3349.63}, pd.Timestamp('2020-09-08 00:00:00'): {'High': 3379.97, 'Low': 3329.27}, pd.Timestamp('2020-09-09 00:00:00'): {'High': 3424.77, 'Low': 3366.84}, pd.Timestamp('2020-09-10 00:00:00'): {'High': 3425.55, 'Low': 3329.25}, pd.Timestamp('2020-09-11 00:00:00'): {'High': 3368.95, 'Low': 3310.47}, pd.Timestamp('2020-09-14 00:00:00'): {'High': 3402.93, 'Low': 3363.56}, pd.Timestamp('2020-09-15 00:00:00'): {'High': 3419.48, 'Low': 3389.25}, pd.Timestamp('2020-09-16 00:00:00'): {'High': 3428.92, 'Low': 3384.45}, pd.Timestamp('2020-09-17 00:00:00'): {'High': 3375.17, 'Low': 3328.82}, pd.Timestamp('2020-09-18 00:00:00'): {'High': 3362.27, 'Low': 3292.4}, pd.Timestamp('2020-09-21 00:00:00'): {'High': 3285.57, 'Low': 3229.1}, pd.Timestamp('2020-09-22 00:00:00'): {'High': 3320.31, 'Low': 3270.95}, pd.Timestamp('2020-09-23 00:00:00'): {'High': 3323.35, 'Low': 3232.57}, pd.Timestamp('2020-09-24 00:00:00'): {'High': 3278.7, 'Low': 3209.45}, pd.Timestamp('2020-09-25 00:00:00'): {'High': 3306.88, 'Low': 3228.44}, pd.Timestamp('2020-09-28 00:00:00'): {'High': 3360.74, 'Low': 3332.91}}

df = pd.DataFrame.from_dict(data, 'index')

Find all controls in WPF Window by type

This should do the trick

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

then you enumerate over the controls like so

foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
    // do something with tb here
}

WAMP/XAMPP is responding very slow over localhost

Just try "Incognito" mode in Chrome.

Finally, this helped me to solve my issue.

Please keep your mind, this is not a permanent solution.

Validate that end date is greater than start date with jQuery

The date values from the text fields can be fetched by jquery's .val() Method like

var datestr1 = $('#datefield1-id').val();
var datestr2 = $('#datefield2-id').val();

I'd strongly recommend to parse the date strings before comparing them. Javascript's Date object has a parse()-Method, but it only supports US date formats (YYYY/MM/DD). It returns the milliseconds since the beginning of the unix epoch, so you can simply compare your values with > or <.

If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.

If you want to be super user-fiendly, you can use jquery ui datepickers instead of textfields. There is a datepicker variant that allows to enter date ranges:

http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/

What is the effect of encoding an image in base64?

The answer is: It depends.

Although base64-images are larger, there a few conditions where base64 is the better choice.

Size of base64-images

Base64 uses 64 different characters and this is 2^6. So base64 stores 6bit per 8bit character. So the proportion is 6/8 from unconverted data to base64 data. This is no exact calculation, but a rough estimate.

Example:

An 48kb image needs around 64kb as base64 converted image.

Calculation: (48 / 6) * 8 = 64

Simple CLI calculator on Linux systems:

$ cat /dev/urandom|head -c 48000|base64|wc -c
64843

Or using an image:

$ cat my.png|base64|wc -c

Base64-images and websites

This question is much more difficult to answer. Generally speaking, as larger the image as less sense using base64. But consider the following points:

  • A lot of embedded images in an HTML-File or CSS-File can have similar strings. For PNGs you often find repeated "A" chars. Using gzip (sometimes called "deflate"), there might be even a win on size. But it depends on image content.
  • Request overhead of HTTP1.1: Especially with a lot of cookies you can easily have a few kilobytes overhead per request. Embedding base64 images might save bandwith.
  • Do not base64 encode SVG images, because gzip is more effective on XML than on base64.
  • Programming: On dynamically generated images it is easier to deliver them in one request as to coordinate two dependent requests.
  • Deeplinks: If you want to prevent downloading the image, it is a little bit trickier to extract an image from an HTML page.

ng serve not detecting file changes automatically

In your project dist folder is own by root

Try to use sudo ng serve instead of ng serve.

Another solution

When there is having a large number of files watch not work in linux.There is a Limit at INotify Watches on Linux. So increasing the watches limit

//When live server not work in linux

sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system

ng serve //You can also do sudo **ng serve**

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files\PostgreSQL\8.4\data\postgresql.conf

How to clear textarea on click?

This is your javascript file:

function yourFunction(){
     document.getElementById('yourid').value = "";
};

This is the html file:

    <textarea id="yourid" >
    Your text inside the textarea
    </textarea>
    <button onClick="yourFunction();">
     Your button Name
     </button>

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

The package is not fully compatible with dotnetcore 2.0 for now.

eg, for 'Microsoft.AspNet.WebApi.Client' it maybe supported in version (5.2.4). See Consume new Microsoft.AspNet.WebApi.Client.5.2.4 package for details.

You could try the standard Client package as Federico mentioned.

If that still not work, then as a workaround you can only create a Console App (.Net Framework) instead of the .net core 2.0 console app.

Reference this thread: Microsoft.AspNet.WebApi.Client supported in .NET Core or not?

Failed to install *.apk on device 'emulator-5554': EOF

Solution:

  1. Start emulator (separately) and wait until it is fully loaded.
  2. Open keylock.
  3. Navigate to Eclipse and run your app.

Cause of the problem: Android emulator hasn't loaded all its libraries which handle the installing of a new application and due to that you run into java.io.IOException: EOF

That was causing me the problem.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

$(document).ready(function() {
    $("input:text").focus(function() { $(this).select(); } );
});

get parent's view from a layout

This also works:

this.getCurrentFocus()

It gets the view so I can use it.

How can I parse a YAML file in Python

I use ruamel.yaml. Details & debate here.

from ruamel import yaml

with open(filename, 'r') as fp:
    read_data = yaml.load(fp)

Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use

from ruamel import yaml

instead of

import yaml

and it will fix most of your problems.

EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.

Python - Create list with numbers between 2 values?

assuming you want to have a range between x to y

range(x,y+1)

>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>

use list for 3.x support

Oracle: how to INSERT if a row doesn't exist

INSERT INTO table
SELECT 'jonny', NULL
  FROM dual -- Not Oracle? No need for dual, drop that line
 WHERE NOT EXISTS (SELECT NULL -- canonical way, but you can select
                               -- anything as EXISTS only checks existence
                     FROM table
                    WHERE name = 'jonny'
                  )

Get current application physical path within Application_Start

There's, however, slight difference among all these options which

I found out that

If you do

    string URL = Server.MapPath("~");

or

    string URL = Server.MapPath("/");

or

    string URL = HttpRuntime.AppDomainAppPath;

your URL will display resources in your link like this:

    "file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"

But if you want your URL to show only virtual path not the resources location, you should do

    string URL = HttpRuntime.AppDomainAppVirtualPath; 

then, your URL is displaying a virtual path to your resources as below

    "http://HOME/Index/bin/Resources/HandlerDoc.htm"        

How can I get a channel ID from YouTube?

To obtain the channel id you can view the source code of the channel page and find either data-channel-external-id="UCjXfkj5iapKHJrhYfAF9ZGg" or "externalId":"UCjXfkj5iapKHJrhYfAF9ZGg".

UCjXfkj5iapKHJrhYfAF9ZGg will be the channel ID you are looking for.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

it worked for me adding type="module" to the script importing my mjs:

<script type="module">
import * as module from 'https://rawgit.com/abernier/7ce9df53ac9ec00419634ca3f9e3f772/raw/eec68248454e1343e111f464e666afd722a65fe2/mymod.mjs'

console.log(module.default()) // Prints: Hi from the default export!
</script>

See demo: https://codepen.io/abernier/pen/wExQaa

Place input box at the center of div

You can just use either of the following approaches:

_x000D_
_x000D_
.center-block {
  margin: auto;
  display: block;
}
_x000D_
<div>
  <input class="center-block">
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.parent {
  display: grid;
  place-items: center;
}
_x000D_
<div class="parent">
  <input>
</div>
_x000D_
_x000D_
_x000D_

Is it possible to use if...else... statement in React render function?

May be I'm too late here. But I hope this would help someone. First separate those two elements.

renderLogout(){
<div>
   <LogoutButton onClick={this.handleLogoutClick} />
<div>
}

renderLogin(){
<div>
   <LoginButton onClick={this.handleLoginClick} />
<div>
}

Then you can call these functions from render function using if else statement.

render(){
if(this.state.result){
  return this.renderResult();
}else{
  return this.renderQuiz();
}}

This works for me. :)

GIT commit as different user without email / or only email

The specific format is:

git commit --author="John Doe <[email protected]>" -m "Impersonation is evil." 

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

Reading a date using DataReader

Try as given below:

while (MyReader.Read())
{
    TextBox1.Text = Convert.ToDateTime(MyReader["DateField"]).ToString("dd/MM/yyyy");
}

in ToString() method you can change data format as per your requirement.

How to parse a CSV file using PHP

Just use the function for parsing a CSV file

http://php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
  }
  fclose($handle);
}

How to obtain Telegram chat_id for a specific user?

Straight out from the documentation:

Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.

  1. Create a bot with a suitable username, e.g. @ExampleComBot
  2. Set up a webhook for incoming messages
  3. Generate a random string of a sufficient length, e.g. $memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
  4. Put the value 123 with the key $memcache_key into Memcache for 3600 seconds (one hour)
  5. Show our user the button https://telegram.me/ExampleComBot?start=vCH1vGWJxfSeofSAs0K5PA
  6. Configure the webhook processor to query Memcached with the parameter that is passed in incoming messages beginning with /start. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.
  7. Now when we want to send a notification to the user 123, check if they have the field telegram_chat_id. If yes, use the sendMessage method in the Bot API to send them a message in Telegram.

Java: How to get input from System.console()

Using Console to read input (usable only outside of an IDE):

System.out.print("Enter something:");
String input = System.console().readLine();

Another way (works everywhere):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter String");
        String s = br.readLine();
        System.out.print("Enter Integer:");
        try {
            int i = Integer.parseInt(br.readLine());
        } catch(NumberFormatException nfe) {
            System.err.println("Invalid Format!");
        }
    }
}

System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

'npm' is not recognized as internal or external command, operable program or batch file

For windows8 right click my pc properties then click environment variables user variable or System variables >> new >> put variable name and path : like this C:\Program Files\nodejs Then ok now open cmd and type npm it will work

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

How to declare a static const char* in your header file?

With C++11 you can use the constexpr keyword and write in your header:

private:
    static constexpr const char* SOMETHING = "something";


Notes:

  • constexpr makes SOMETHING a constant pointer so you cannot write

    SOMETHING = "something different";
    

    later on.

  • Depending on your compiler, you might also need to write an explicit definition in the .cpp file:

    constexpr const char* MyClass::SOMETHING;
    

Web-scraping JavaScript page with Python

It sounds like the data you're really looking for can be accessed via secondary URL called by some javascript on the primary page.

While you could try running javascript on the server to handle this, a simpler approach to might be to load up the page using Firefox and use a tool like Charles or Firebug to identify exactly what that secondary URL is. Then you can just query that URL directly for the data you are interested in.

How to add image that is on my computer to a site in css or html?

No, Not if your website is on a remote server, i.e not on localhost.

How to get out of while loop in java with Scanner method "hasNext" as condition?

Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.

  while (sc.hasNext())
  {    
    s1 = sc.next();
    System.out.println(s1);
    System.out.print("Enter your sentence: ");
  }

How do I iterate over a range of numbers defined by variables in Bash?

The seq method is the simplest, but Bash has built-in arithmetic evaluation.

END=5
for ((i=1;i<=END;i++)); do
    echo $i
done
# ==> outputs 1 2 3 4 5 on separate lines

The for ((expr1;expr2;expr3)); construct works just like for (expr1;expr2;expr3) in C and similar languages, and like other ((expr)) cases, Bash treats them as arithmetic.

How to sort multidimensional array by column?

You can use list.sort with its optional key parameter and a lambda expression:

>>> lst = [
...     ['John',2],
...     ['Jim',9],
...     ['Jason',1]
... ]
>>> lst.sort(key=lambda x:x[1])
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>

This will sort the list in-place.


Note that for large lists, it will be faster to use operator.itemgetter instead of a lambda:

>>> from operator import itemgetter
>>> lst = [
...     ['John',2],
...     ['Jim',9],
...     ['Jason',1]
... ]
>>> lst.sort(key=itemgetter(1))
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>

Get first 100 characters from string, respecting full words

function truncate ($str, $length) {
    if (strlen($str) > $length) {
        $str = substr($str, 0, $length+1);
        $pos = strrpos($str, ' ');
        $str = substr($str, 0, ($pos > 0)? $pos : $length);
    }
    return $str;
}

Example:

print truncate('The first step to eternal life is you have to die.', 25);

string(25) "The first step to eternal"

print truncate('The first step to eternal life is you have to die.', 12);

string(9) "The first"

print truncate('FirstStepToEternalLife', 5);

string(5) "First"

How to remove list elements in a for loop in Python?

As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).

If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.

This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.

TL;DR:

>>> a = list(range(5))
>>> for b in reversed(a):
    if b == 3:
        a.remove(b)
>>> a
[0, 1, 2, 4]

However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

If you want to filter rows by a certain number of columns with null values, you may use this:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

So, here is the example:

Your dataframe:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

If you want to select the rows that have two or more columns with null value, you run the following:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

How to load local html file into UIWebView

by this you can load html file which is in your project Assets(bundle) to webView.

 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

may be this is useful to you.

Duplicating a MySQL table, indices, and data

To create table structure only use this below code :

CREATE TABLE new_table LIKE current_table; 

To copy data from table to another use this below code :

INSERT INTO new_table SELECT * FROM current_table;

javascript cell number validation

Verify this code : It works on change of phone number field in ms crm 2016 form .

function validatePhoneNumber() {

    var mob = Xrm.Page.getAttribute("gen_phone").getValue();
    var length = mob.length;
    if (length < 10 || length > 10) {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
    if (mob > 31 && (mob < 48 || mob > 57)) {} else {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
}

Why did I get the compile error "Use of unassigned local variable"?

Local variables aren't initialized. You have to manually initialize them.

Members are initialized, for example:

public class X
{
    private int _tmpCnt; // This WILL initialize to zero
    ...
}

But local variables are not:

public static void SomeMethod()
{
    int tmpCnt;  // This is not initialized and must be assigned before used.

    ...
}

So your code must be:

int tmpCnt = 0;  
if (name == "Dude")  
   tmpCnt++;  

So the long and the short of it is, members are initialized, locals are not. That is why you get the compiler error.

Adding event listeners to dynamically added elements using jQuery

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});

Need to get current timestamp in Java

java.time

As of Java 8+ you can use the java.time package. Specifically, use DateTimeFormatterBuilder and DateTimeFormatter to format the patterns and literals.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("MM").appendLiteral("/")
        .appendPattern("dd").appendLiteral("/")
        .appendPattern("yyyy").appendLiteral(" ")
        .appendPattern("hh").appendLiteral(":")
        .appendPattern("mm").appendLiteral(":")
        .appendPattern("ss").appendLiteral(" ")
        .appendPattern("a")
        .toFormatter();
System.out.println(LocalDateTime.now().format(formatter));

The output ...

06/22/2015 11:59:14 AM

Or if you want different time zone

// system default
System.out.println(formatter.withZone(ZoneId.systemDefault()).format(Instant.now()));
// Chicago
System.out.println(formatter.withZone(ZoneId.of("America/Chicago")).format(Instant.now()));
// Kathmandu
System.out.println(formatter.withZone(ZoneId.of("Asia/Kathmandu")).format(Instant.now()));

The output ...

06/22/2015 12:38:42 PM
06/22/2015 02:08:42 AM
06/22/2015 12:53:42 PM

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).

Class weights

The weights from the class_weight parameter are used to train the classifier. They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.

Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.

The metrics

Once you have a classifier, you want to know how well it is performing. Here you can use the metrics you mentioned: accuracy, recall_score, f1_score...

Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.

I will not detail all these metrics but note that, with the exception of accuracy, they are naturally applied at the class level: as you can see in this print of a classification report they are defined for each class. They rely on concepts such as true positives or false negative that require defining which class is the positive one.

             precision    recall  f1-score   support

          0       0.65      1.00      0.79        17
          1       0.57      0.75      0.65        16
          2       0.33      0.06      0.10        17
avg / total       0.52      0.60      0.51        50

The warning

F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The 
default `weighted` averaging is deprecated, and from version 0.18, 
use of precision, recall or F-score with multiclass or multilabel data  
or pos_label=None will result in an exception. Please set an explicit 
value for `average`, one of (None, 'micro', 'macro', 'weighted', 
'samples'). In cross validation use, for instance, 
scoring="f1_weighted" instead of scoring="f1".

You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:

  1. Take the average of the f1-score for each class: that's the avg / total result above. It's also called macro averaging.
  2. Compute the f1-score using the global count of true positives / false negatives, etc. (you sum the number of true positives / false negatives for each class). Aka micro averaging.
  3. Compute a weighted average of the f1-score. Using 'weighted' in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.

These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average argument for the score method.

Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.

The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.

Computing scores

Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.

Here's a way to do it using StratifiedShuffleSplit, which gives you a random splits of your data (after shuffling) that preserve the label distribution.

from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
    X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
    svc.fit(X_train, y_train)
    y_pred = svc.predict(X_test)
    print(f1_score(y_test, y_pred, average="macro"))
    print(precision_score(y_test, y_pred, average="macro"))
    print(recall_score(y_test, y_pred, average="macro"))    

Hope this helps.

How can I convert this foreach code to Parallel.ForEach?

For big file use the following code (you are less memory hungry)

Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
    //Your stuff
});

How to sort a file, based on its numerical values for a field?

    echo " Enter any values to sorting: "
read n
i=0;
t=0;
echo " Enter the n value: "
for(( i=0;i<n;i++ ))
do
read s[$i]
done
for(( i=0;i<n;i++ ))
do
for(( j=i+1;j<n;j++ ))
do
if [ ${s[$i]} -gt ${s[$j]} ]
then
t=${s[$i]}
s[$i]=${s[$j]}
s[$j]=$t
fi
done
done
for(( i=0;i<n;i++ ))
do
echo " ${s[$i]}  "
done

Close all infowindows in Google Maps API v3

Declare global variables:

var mapOptions;
var map;
var infowindow;
var marker;
var contentString;
var image;

In intialize use the map's addEvent method:

google.maps.event.addListener(map, 'click', function() {
    if (infowindow) {
        infowindow.close();
    }
});

Wireshark vs Firebug vs Fiddler - pros and cons?

Wireshark, Firebug, Fiddler all do similar things - capture network traffic.

  • Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.

  • Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).

  • Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.

Open Sublime Text from Terminal in macOS

In OS X Mavericks running Sublime Text 2 the following worked for me.

sudo ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/bin/subl

Its handy to locate the file in the finder and drag and drop that into the terminal window so you can be sure the path is the correct one, I'm not a huge terminal user so this was more comfortable for me. then you can go to the start of the path and start adding in the other parts like the shorthand UNIX commands. Hope this helps

How do I find the duplicates in a list and create another list with them?

raw_list = [1,2,3,3,4,5,6,6,7,2,3,4,2,3,4,1,3,4,]

clean_list = list(set(raw_list))
duplicated_items = []

for item in raw_list:
    try:
        clean_list.remove(item)
    except ValueError:
        duplicated_items.append(item)


print(duplicated_items)
# [3, 6, 2, 3, 4, 2, 3, 4, 1, 3, 4]

You basically remove duplicates by converting to set (clean_list), then iterate the raw_list, while removing each item in the clean list for occurrence in raw_list. If item is not found, the raised ValueError Exception is caught and the item is added to duplicated_items list.

If the index of duplicated items is needed, just enumerate the list and play around with the index. (for index, item in enumerate(raw_list):) which is faster and optimised for large lists (like thousands+ of elements)

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

How do I make an http request using cookies on Android?

A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion.

You can read this article for more information.

I can share my peace of code to demonstrate how easy you can make it.

public static String getServerResponseByHttpGet(String url, String token) {

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            get.setHeader("Cookie", "PHPSESSID=" + token + ";");
            Log.d(TAG, "Try to open => " + url);

            HttpResponse httpResponse = client.execute(get);
            int connectionStatusCode = httpResponse.getStatusLine().getStatusCode();
            Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url);

            HttpEntity entity = httpResponse.getEntity();
            String serverResponse = EntityUtils.toString(entity);
            Log.d(TAG, "Server response for request " + url + " => " + serverResponse);

            if(!isStatusOk(connectionStatusCode))
                return null;

            return serverResponse;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }