Programs & Examples On #Row

A horizontal line of cells in a spreadsheet, SQL table, HTML table, or similar structure.

Python Pandas Replacing Header with Top Row

If you want a one-liner, you can do:

df.rename(columns=df.iloc[0]).drop(df.index[0])

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

Fast way to discover the row count of a table in PostgreSQL

You can get the count by the below query (without * or any column names).

select from table_name;

Referencing Row Number in R

Simply:

data$rownumber = 1:nrow(Data)

Programmatically select a row in JTable

It is an old post, but I came across this recently

Selecting a specific interval

As @aleroot already mentioned, by using

table.setRowSelectionInterval(index0, index1);

You can specify an interval, which should be selected.

Adding an interval to the existing selection

You can also keep the current selection, and simply add additional rows by using this here

table.getSelectionModel().addSelectionInterval(index0, index1);

This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.

How do I count the number of rows and columns in a file using bash?

If counting number of columns in the first is enough, try the following:

awk -F'\t' '{print NF; exit}' myBigFile.tsv

where \t is column delimiter.

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

In MySQL, can I copy one row to insert into the same table?

This can be achieved with some creativity:

SET @sql = CONCAT('INSERT INTO <table> SELECT null, 
    ', (SELECT GROUP_CONCAT(COLUMN_NAME) 
    FROM information_schema.columns 
    WHERE table_schema = '<database>' 
    AND table_name = '<table>' 
    AND column_name NOT IN ('id')), ' 
from <table> WHERE id = <id>');  

PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

This will result in the new row getting an auto incremented id instead of the id from the selected row.

CSS: Fix row height

You can also try this, if this is what you need:

<style type="text/css">
   ....
   table td div {height:20px;overflow-y:hidden;}
   table td.col1 div {width:100px;}
   table td.col2 div {width:300px;}
</style>


<table>
<tbody>
    <tr><td class="col1"><div>test</div></td></tr>
    <tr><td class="col2"><div>test</div></td></tr>
</tbody>
</table>

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

android listview item height

The trick for me was not setting the height -- but instead setting the minHeight. This must be applied to the root view of whatever layout your custom adapter is using to render each row.

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

jQuery: count number of rows in a table

Use a selector that will select all the rows and take the length.

var rowCount = $('#myTable tr').length;

Note: this approach also counts all trs of every nested table!

How to fix height of TR?

Your table width is 90% which is relative to it's container.

If you squeeze the page, you are probably squeezing the table width as well. The width of the cells reduce too and the browser compensate by increasing the height.

To have the height untouched, you have to make sure the widths of the cells can hold the intented content. Fixing the table width is probably something you want to try. Or perhaps play around with the min-width of the table.

MS SQL 2008 - get all table names and their row counts in a DB

Posted for completeness.

If you are looking for row count of all tables in all databases (which was what I was looking for) then I found this combination of this and this to work. No idea whether it is optimal or not:

SET NOCOUNT ON
DECLARE @AllTables table (DbName sysname,SchemaName sysname, TableName sysname, RowsCount int )
DECLARE
     @SQL nvarchar(4000)
SET @SQL='SELECT ''?'' AS DbName, s.name AS SchemaName, t.name AS TableName, p.rows AS RowsCount FROM [?].sys.tables t INNER JOIN sys.schemas s ON t.schema_id=s.schema_id INNER JOIN [?].sys.partitions p ON p.OBJECT_ID = t.OBJECT_ID'

INSERT INTO @AllTables (DbName, SchemaName, TableName, RowsCount)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT DbName, SchemaName, TableName, SUM(RowsCount), MIN(RowsCount), SUM(1)
FROM @AllTables
WHERE RowsCount > 0
GROUP BY DbName, SchemaName, TableName
ORDER BY DbName, SchemaName, TableName

Remove table row after clicking table row delete button

Using pure Javascript:

Don't need to pass this to the SomeDeleteRowFunction():

<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction()"></td>

The onclick function:

function SomeDeleteRowFunction() {
      // event.target will be the input element.
      var td = event.target.parentNode; 
      var tr = td.parentNode; // the row to be removed
      tr.parentNode.removeChild(tr);
}

How do I delete rows in a data frame?

The key idea is you form a set of the rows you want to remove, and keep the complement of that set.

In R, the complement of a set is given by the '-' operator.

So, assuming the data.frame is called myData:

myData[-c(2, 4, 6), ]   # notice the -

Of course, don't forget to "reassign" myData if you wanted to drop those rows entirely---otherwise, R just prints the results.

myData <- myData[-c(2, 4, 6), ]

How to insert a row in an HTML table body in JavaScript

I have tried this, and this is working for me:

var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);

How do I add indices to MySQL tables?

You say you have an index, the explain says otherwise. However, if you really do, this is how to continue:

If you have an index on the column, and MySQL decides not to use it, it may by because:

  1. There's another index in the query MySQL deems more appropriate to use, and it can use only one. The solution is usually an index spanning multiple columns if their normal method of retrieval is by value of more then one column.
  2. MySQL decides there are to many matching rows, and thinks a tablescan is probably faster. If that isn't the case, sometimes an ANALYZE TABLE helps.
  3. In more complex queries, it decides not to use it based on extremely intelligent thought-out voodoo in the query-plan that for some reason just not fits your current requirements.

In the case of (2) or (3), you could coax MySQL into using the index by index hint sytax, but if you do, be sure run some tests to determine whether it actually improves performance to use the index as you hint it.

How to add a new row to datagridview programmatically

yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value

you can also create a new row and then add it to the DataGridView like this:

DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);

Padding a table row

The trick is to give padding on the td elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):

td {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;   
}

td:first-child {
  padding-left:20px;
  padding-right:0;
}

First-child is relatively well supported: https://developer.mozilla.org/en-US/docs/CSS/:first-child

You can use the same reasoning for the horizontal padding by using tr:first-child td.

Alternatively, exclude the first column by using the not operator. Support for this is not as good right now, though.

td:not(:first-child) {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;       
}

Copy data from one existing row to another existing row in SQL?

This works well for coping entire records.

UPDATE your_table
SET new_field = sourse_field

Delete a row from a table by id

to Vilx-:

var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
    table = table.parentNode;

and what if row.parentNode is TBODY?

You should check it out first, and after that do while by .tBodies, probably

jQuery: click function exclude children.

Or you can do also:

$('.example').on('click', function(e) { 
   if( e.target != this ) 
       return false;

   // ... //
});

How to get the URL without any parameters in JavaScript?

This is possible, but you'll have to build it manually from the location object:

location.protocol + '//' + location.host + location.pathname

How can I disable selected attribute from select2() dropdown Jquery?

if you want to disable the values of the dropdown

$('select option:not(selected)').prop('disabled', true);

$('select').prop('disabled', true);

MySQL joins and COUNT(*) from another table

Maybe I am off the mark here and not understanding the OP but why are you joining tables?

If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.

SELECT group_id, COUNT(*) as membercount 
FROM members 
GROUP BY group_id 
HAVING membercount > 4

This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.

If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.

*ngIf else if in template

You can also use this old trick for converting complex if/then/else blocks into a slightly cleaner switch statement:

<div [ngSwitch]="true">
    <button (click)="foo=(++foo%3)+1">Switch!</button>

    <div *ngSwitchCase="foo === 1">one</div>
    <div *ngSwitchCase="foo === 2">two</div>
    <div *ngSwitchCase="foo === 3">three</div>
</div>

javascript multiple OR conditions in IF statement

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

What are best practices for REST nested resources?

I've moved what I've done from the question to an answer where more people are likely to see it.

What I've done is to have the creation endpoints at the nested endpoint, The canonical endpoint for modifying or querying an item is not at the nested resource.

So in this example (just listing the endpoints that change a resource)

  • POST /companies/ creates a new company returns a link to the created company.
  • POST /companies/{companyId}/departments when a department is put creates the new department returns a link to /departments/{departmentId}
  • PUT /departments/{departmentId} modifies a department
  • POST /departments/{deparmentId}/employees creates a new employee returns a link to /employees/{employeeId}

So there are root level resources for each of the collections. However the create is in the owning object.

SQL query to find third highest salary in company

SELECT id FROM tablename ORDER BY id DESC LIMIT 2 , 1

This is only for get 3rd highest value .

setState() inside of componentDidUpdate()

I had a similar problem where i have to center the toolTip. React setState in componentDidUpdate did put me in infinite loop, i tried condition it worked. But i found using in ref callback gave me simpler and clean solution, if you use inline function for ref callback you will face the null problem for every component update. So use function reference in ref callback and set the state there, which will initiate the re-render

How to check if a double value has no decimal part

You probably want to round the double to 5 decimals or so before comparing since a double can contain very small decimal parts if you have done some calculations with it.

double d = 10.0;
d /= 3.0; // d should be something like 3.3333333333333333333333...
d *= 3.0; // d is probably something like 9.9999999999999999999999...

// d should be 10.0 again but it is not, so you have to use rounding before comparing

d = myRound(d, 5); // d is something like 10.00000
if (fmod(d, 1.0) == 0)
  // No decimals
else
  // Decimals

If you are using C++ i don't think there is a round-function, so you have to implement it yourself like in: http://www.cplusplus.com/forum/general/4011/

Allowing Untrusted SSL Certificates with HttpClient

Or you can use for the HttpClient in the Windows.Web.Http namespace:

var filter = new HttpBaseProtocolFilter();
#if DEBUG
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
#endif
using (var httpClient = new HttpClient(filter)) {
    ...
}

Vbscript list all PDF files in folder and subfolders

The file extension may be case sentive...but the code works.

Set objFSO = CreateObject("Scripting.FileSystemObject")
  objStartFolder = "C:\Dev\"

  Set objFolder = objFSO.GetFolder(objStartFolder)
  Wscript.Echo objFolder.Path

  Set colFiles = objFolder.Files

  For Each objFile in colFiles
  strFileName = objFile.Name

  If objFSO.GetExtensionName(strFileName) = "pdf" Then
      Wscript.Echo objFile.Name
  End If

  Next
  Wscript.Echo

  ShowSubfolders objFSO.GetFolder(objStartFolder)

  Sub ShowSubFolders(Folder)
     For Each Subfolder in Folder.SubFolders
          Wscript.Echo Subfolder.Path
          Set objFolder = objFSO.GetFolder(Subfolder.Path)
          Set colFiles = objFolder.Files
          For Each objFile in colFiles
              Wscript.Echo objFile.Name
          Next
          Wscript.Echo
          ShowSubFolders Subfolder
      Next
  End Sub

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Messages Using Command prompt in Windows 7

You can use the net send command to send a message over a network.

example:

net send * How Are You

you can use the above statement to send a message to all members of your domain.But if you want to send a message to a single user named Mike, you can use

 net send mike hello!

this will send hello! to the user named Mike.

How do I prevent DIV tag starting a new line?

You can simply use:

#contentInfo_new br {display:none;}

Deserialize json object into dynamic object using Json.net

Note: At the time I answered this question in 2010, there was no way to deserialize without some sort of type, this allowed you to deserialize without having go define the actual class and allowed an anonymous class to be used to do the deserialization.


You need to have some sort of type to deserialize to. You could do something along the lines of:

var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());

My answer is based on a solution for .NET 4.0's build in JSON serializer. Link to deserialize to anonymous types is here:

http://blogs.msdn.com/b/alexghi/archive/2008/12/22/using-anonymous-types-to-deserialize-json-data.aspx

SSL "Peer Not Authenticated" error with HttpClient 4.1

Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.

  • CA.crt
  • UTNAddTrustServer_CA.crt
  • AddTrustExternalCARoot.crt

HTTP error 403 in Python 3 Web Scraping

Based on previous answers this has worked for me with Python 3.7

from urllib.request import Request, urlopen

req = Request('Url_Link', headers={'User-Agent': 'XYZ/3.0'})
webpage = urlopen(req, timeout=10).read()

print(webpage)

SQL using sp_HelpText to view a stored procedure on a linked server

Little addition in answer if you have different user rather then dbo then do like this.

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'

Is JavaScript a pass-by-reference or pass-by-value language?

In JavaScript, the type of the value solely controls whether that value will be assigned by value-copy or by reference-copy.

Primitive values are always assigned/passed by value-copy:

  • null
  • undefined
  • string
  • number
  • boolean
  • symbol in ES6

Compound values are always assigned/passed by reference-copy

  • objects
  • arrays
  • function

For example

var a = 2;
var b = a; // `b` is always a copy of the value in `a`
b++;
a; // 2
b; // 3

var c = [1,2,3];
var d = c; // `d` is a reference to the shared `[1,2,3]` value
d.push( 4 );
c; // [1,2,3,4]
d; // [1,2,3,4]

In the above snippet, because 2 is a scalar primitive, a holds one initial copy of that value, and b is assigned another copy of the value. When changing b, you are in no way changing the value in a.

But both c and d are separate references to the same shared value [1,2,3], which is a compound value. It's important to note that neither c nor d more "owns" the [1,2,3] value -- both are just equal peer references to the value. So, when using either reference to modify (.push(4)) the actual shared array value itself, it's affecting just the one shared value, and both references will reference the newly modified value [1,2,3,4].

var a = [1,2,3];
var b = a;
a; // [1,2,3]
b; // [1,2,3]

// later
b = [4,5,6];
a; // [1,2,3]
b; // [4,5,6]

When we make the assignment b = [4,5,6], we are doing absolutely nothing to affect where a is still referencing ([1,2,3]). To do that, b would have to be a pointer to a rather than a reference to the array -- but no such capability exists in JS!

function foo(x) {
    x.push( 4 );
    x; // [1,2,3,4]

    // later
    x = [4,5,6];
    x.push( 7 );
    x; // [4,5,6,7]
}

var a = [1,2,3];

foo( a );

a; // [1,2,3,4]  not  [4,5,6,7]

When we pass in the argument a, it assigns a copy of the a reference to x. x and a are separate references pointing at the same [1,2,3] value. Now, inside the function, we can use that reference to mutate the value itself (push(4)). But when we make the assignment x = [4,5,6], this is in no way affecting where the initial reference a is pointing -- still points at the (now modified) [1,2,3,4] value.

To effectively pass a compound value (like an array) by value-copy, you need to manually make a copy of it, so that the reference passed doesn't still point to the original. For example:

foo( a.slice() );

Compound value (object, array, etc) that can be passed by reference-copy

function foo(wrapper) {
    wrapper.a = 42;
}

var obj = {
    a: 2
};

foo( obj );

obj.a; // 42

Here, obj acts as a wrapper for the scalar primitive property a. When passed to foo(..), a copy of the obj reference is passed in and set to the wrapperparameter. We now can use the wrapper reference to access the shared object, and update its property. After the function finishes, obj.a will see the updated value 42.

Source

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.

Installation of SQL Server Business Intelligence Development Studio

http://msdn.microsoft.com/en-us/library/ms173767.aspx

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

Visual Studio 2017 - Git failed with a fatal error

I also had this issue after I got wget from the GNU tools, and copied it right into c:\windows. The libeay.dll and libssl.dll files were also in the archive. When those were in c:\windows, I had this issue. Removing them immediately fixed it. So, check if you have these .DLLs somewhere in your path, VS may be picking up some other software's version of these instead of using the ones it expects.

How to get multiple selected values from select box in JSP?

Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.

Update: save the file as test.jsp and run it on any web/app server

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>

Put request with simple string as request body

This works for me (code called from node js repl):

const axios = require("axios");

axios
    .put(
        "http://localhost:4000/api/token", 
        "mytoken", 
        {headers: {"Content-Type": "text/plain"}}
    )
    .then(r => console.log(r.status))
    .catch(e => console.log(e));

Logs: 200

And this is my request handler (I am using restify):

function handleToken(req, res) {
    if(typeof req.body === "string" && req.body.length > 3) {
        res.send(200);
    } else {
        res.send(400);
    }
}

Content-Type header is important here.

CSS @font-face not working in ie

If you're still having troubles with this, here's your solution:

http://www.fontsquirrel.com/fontface/generator

It works far better/faster than any other font-generator and also gives an example for you to use.

How to run a program in Atom Editor?

You can go settings, select packages and type atom-runner there if your browser can't open this link.

To run your code do Alt+R if you're using Windows in Atom.

How to get the unique ID of an object which overrides hashCode()?

There is a difference between hashCode() and identityHashCode() returns. It is possible that for two unequal (tested with ==) objects o1, o2 hashCode() can be the same. See the example below how this is true.

class SeeDifferences
{
    public static void main(String[] args)
    {
        String s1 = "stackoverflow";
        String s2 = new String("stackoverflow");
        String s3 = "stackoverflow";
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println(s3.hashCode());
        System.out.println(System.identityHashCode(s1));
        System.out.println(System.identityHashCode(s2));
        System.out.println(System.identityHashCode(s3));
        if (s1 == s2)
        {
            System.out.println("s1 and s2 equal");
        } 
        else
        {
            System.out.println("s1 and s2 not equal");
        }
        if (s1 == s3)
        {
            System.out.println("s1 and s3 equal");
        }
        else
        {
            System.out.println("s1 and s3 not equal");
        }
    }
}

PHP: Call to undefined function: simplexml_load_string()

For PHP 7 and Ubuntu 14.04 the procedure is follows. Since PHP 7 is not in the official Ubuntu PPAs you likely installed it through Ondrej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). Go to /etc/php/7.0/fpm and edit php.ini, uncomment to following line:

extension=php_xmlrpc.dll

Then simply install php7.0-xml:

sudo apt-get install php7.0-xml

And restart PHP:

sudo service php7.0-fpm restart

And restart Apache:

sudo service apache2 restart

If you are on a later Ubuntu version where PHP 7 is included, the procedure is most likely the same as well (except adding any 3rd party repository).

Alter MySQL table to add comments on columns

As per the documentation you can add comments only at the time of creating table. So it is must to have table definition. One way to automate it using the script to read the definition and update your comments.

Reference:

http://cornempire.net/2010/04/15/add-comments-to-column-mysql/

http://bugs.mysql.com/bug.php?id=64439

How to group by week in MySQL?

You can use both YEAR(timestamp) and WEEK(timestamp), and use both of the these expressions in the SELECT and the GROUP BY clause.

Not overly elegant, but functional...

And of course you can combine these two date parts in a single expression as well, i.e. something like

SELECT CONCAT(YEAR(timestamp), '/', WEEK(timestamp)), etc...
FROM ...
WHERE ..
GROUP BY CONCAT(YEAR(timestamp), '/', WEEK(timestamp))

Edit: As Martin points out you can also use the YEARWEEK(mysqldatefield) function, although its output is not as eye friendly as the longer formula above.


Edit 2 [3 1/2 years later!]:
YEARWEEK(mysqldatefield) with the optional second argument (mode) set to either 0 or 2 is probably the best way to aggregate by complete weeks (i.e. including for weeks which straddle over January 1st), if that is what is desired. The YEAR() / WEEK() approach initially proposed in this answer has the effect of splitting the aggregated data for such "straddling" weeks in two: one with the former year, one with the new year.
A clean-cut every year, at the cost of having up to two partial weeks, one at either end, is often desired in accounting etc. and for that the YEAR() / WEEK() approach is better.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

Universal way of loading view from xib:

Example:

let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)

Implementation:

extension Bundle {

    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }

        fatalError("Could not load view with type " + String(describing: type))
    }
}

Prevent RequireJS from Caching Required Scripts

I took this snippet from AskApache and put it into a seperate .conf file of my local Apache webserver (in my case /etc/apache2/others/preventcaching.conf):

<FilesMatch "\.(html|htm|js|css)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</FilesMatch>

For development this works fine with no need to change the code. As for the production, I might use @dvtoever's approach.

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

As of SQL Server 2016 you have

DROP TABLE IF EXISTS [foo];

MSDN source

Update Git submodule to latest commit on origin

the simplest way to handle git projects containing submodules is to always add

--recurse-submodules 

at the end of each git command example:

git fetch --recurse-submodules

another

git pull --update --recurse-submodules

etc...

Inner join with count() on three tables

select pe_name,count( distinct b.ord_id),count(c.item_id) 
 from people  a, order1 as b ,item as c
 where a.pe_id=b.pe_id and
b.ord_id=c.order_id   group by a.pe_id,pe_name

How can I make XSLT work in chrome?

As close as I can tell, Chrome is looking for the header

Content-Type: text/xml

Then it works --- other iterations have failed.

Make sure your web server is providing this. It also explains why it fails for file://URI xml files.

java.lang.NoClassDefFoundError: org/json/JSONObject

The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject

You have not added the necessary jar file which will be having org.json.JSONObject class to your classpath.

You can Download it From Here

PHP: How do you determine every Nth iteration of a loop?

every 3 posts?

if($counter % 3 == 0){
    echo IMAGE;
}

How can I generate a list or array of sequential integers in Java?

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());

How to change Status Bar text color in iOS

In iOS 8: add NavigationController.NavigationBar.BarStyle = UIBarStyle.Black; to viewDidLoad

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

I had this issue with an MVC project and here is how I fixed it.

  1. Open BundleConfig.cs
  2. Find :

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));

    Change to:

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.bundle.min.js"));
    

This will set the bundle file to load. It is already in the correct order. You just have to make sure that you are rendering this bundle in your view.

Bootstrap datetimepicker is not a function

I changed the import sequence without fixing the problem, until finally I installed moments and tempus dominius (Core and bootrap), using npm and include them in boostrap.js

try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('moment'); /*added*/
require('bootstrap');
require('tempusdominus-bootstrap-4');/*added*/} catch (e) {}

What are Makefile.am and Makefile.in?

reference :

Makefile.am -- a user input file to automake

configure.in -- a user input file to autoconf


autoconf generates configure from configure.in

automake gererates Makefile.in from Makefile.am

configure generates Makefile from Makefile.in

For ex:

$]
configure.in Makefile.in
$] sudo autoconf
configure configure.in Makefile.in ... 
$] sudo ./configure
Makefile Makefile.in

Mongoose and multiple database in single node.js project

As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.

var Mongoose = require('mongoose').Mongoose;

var instance1 = new Mongoose();
instance1.connect('foo');

var instance2 = new Mongoose();
instance2.connect('bar');

This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.

How to exit an Android app programmatically?

put this one into your onClic:

moveTaskToBack(true);
    finish()

C# Listbox Item Double Click Event

It depends whether you ListBox object of the System.Windows.Forms.ListBox class, which does have the ListBox.IndexFromPoint() method. But if the ListBox object is from the System.Windows.Control.Listbox class, the answer from @dark-knight (marked as correct answer) does not work.

Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI. See also: WPF vs Windows Form

How to delete files/subfolders in a specific directory at the command prompt in Windows

I tried several of these approaches, but none worked properly.

I found this two-step approach on the site Windows Command Line:

forfiles /P %pathtofolder% /M * /C "cmd /c if @isdir==FALSE del @file"

forfiles /P %pathtofolder%  /M * /C "cmd /c if @isdir==TRUE rmdir /S /Q @file"

It worked exactly as I needed and as specified by the OP.

Visual Studio : short cut Key : Duplicate Line

For Visual Studio Code 2019:

Edit menu keyboard shortcuts with: ctrl+k and ctrl+s

Edit "Copy Line Down" (Shift + Alt + DownArrow) to your your own shortcut.

You can find it, with the command ID: editor.action.copyLinesDownAction

For me, It's ctrl+d

Google Chrome default opening position and size

Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.

MySQL: Curdate() vs Now()

Just for the fun of it:

CURDATE() = DATE(NOW())

Or

NOW() = CONCAT(CURDATE(), ' ', CURTIME())

How can I get nth element from a list?

You can use !!, but if you want to do it recursively then below is one way to do it:

dataAt :: Int -> [a] -> a
dataAt _ [] = error "Empty List!"
dataAt y (x:xs)  | y <= 0 = x
                 | otherwise = dataAt (y-1) xs

is python capable of running on multiple cores?

The answer is "Yes, But..."

But cPython cannot when you are using regular threads for concurrency.

You can either use something like multiprocessing, celery or mpi4py to split the parallel work into another process;

Or you can use something like Jython or IronPython to use an alternative interpreter that doesn't have a GIL.

A softer solution is to use libraries that don't run afoul of the GIL for heavy CPU tasks, for instance numpy can do the heavy lifting while not retaining the GIL, so other python threads can proceed. You can also use the ctypes library in this way.

If you are not doing CPU bound work, you can ignore the GIL issue entirely (kind of) since python won't aquire the GIL while it's waiting for IO.

What values for checked and selected are false?

The empty string is false as a rule.

Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.

How to set bot's status

Use this:

client.user.setActivity("with depression", {
  type: "STREAMING",
  url: "https://www.twitch.tv/monstercat"
});

How can I turn a DataTable to a CSV?

4 lines of code:

public static string ToCSV(DataTable tbl)
{
    StringBuilder strb = new StringBuilder();

    //column headers
    strb.AppendLine(string.Join(",", tbl.Columns.Cast<DataColumn>()
        .Select(s => "\"" + s.ColumnName + "\"")));

    //rows
    tbl.AsEnumerable().Select(s => strb.AppendLine(
        string.Join(",", s.ItemArray.Select(
            i => "\"" + i.ToString() + "\"")))).ToList();

    return strb.ToString();
}

Note that the ToList() at the end is important; I need something to force an expression evaluation. If I was code golfing, I could use Min() instead.

Also note that the result will have a newline at the end because of the last call to AppendLine(). You may not want this. You can simply call TrimEnd() to remove it.

How can I reset or revert a file to a specific revision?

I think I've found it....from http://www-cs-students.stanford.edu/~blynn/gitmagic/ch02.html

Sometimes you just want to go back and forget about every change past a certain point because they're all wrong.

Start with:

$ git log

which shows you a list of recent commits, and their SHA1 hashes.

Next, type:

$ git reset --hard SHA1_HASH

to restore the state to a given commit and erase all newer commits from the record permanently.

Configuring Log4j Loggers Programmatically

In the case that you have defined an appender in log4j properties and would like to update it programmatically, set the name in the log4j properties and get it by name.

Here's an example log4j.properties entry:

log4j.appender.stdout.Name=console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold=INFO

To update it, do the following:

((ConsoleAppender) Logger.getRootLogger().getAppender("console")).setThreshold(Level.DEBUG);

Use of "instanceof" in Java

instanceof can be used to determine the actual type of an object:

class A { }  
class C extends A { } 
class D extends A { } 

public static void testInstance(){
    A c = new C();
    A d = new D();
    Assert.assertTrue(c instanceof A && d instanceof A);
    Assert.assertTrue(c instanceof C && d instanceof D);
    Assert.assertFalse(c instanceof D);
    Assert.assertFalse(d instanceof C);
}

How can I programmatically get the MAC address of an iphone


NOTE As of iOS7, you can no longer retrieve device MAC addresses. A fixed value will be returned rather than the actual MAC


Somthing I stumbled across a while ago. Originally from here I modified it a bit and cleaned things up.

IPAddress.h
IPAddress.c

And to use it

InitAddresses();
GetIPAddresses();
GetHWAddresses();

int i;
NSString *deviceIP = nil;
for (i=0; i<MAXADDRS; ++i)
{
    static unsigned long localHost = 0x7F000001;        // 127.0.0.1
    unsigned long theAddr;

    theAddr = ip_addrs[i];

    if (theAddr == 0) break;
    if (theAddr == localHost) continue;

    NSLog(@"Name: %s MAC: %s IP: %s\n", if_names[i], hw_addrs[i], ip_names[i]);

        //decided what adapter you want details for
    if (strncmp(if_names[i], "en", 2) == 0)
    {
        NSLog(@"Adapter en has a IP of %s", ip_names[i]);
    }
}

Adapter names vary depending on the simulator/device as well as wifi or cell on the device.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had tried uninstalling and then installing "Microsoft Access Database Engine 2010 (English) several times and finally the comment - "Changed option from ANY CPU to x86" and it worked.

Thanks for that comment - I am now back in business after 2 weeks of frustration.

Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.

Update

PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

Removing multiple files from a Git repo that have already been deleted from disk

something like

git status | sed -s "s/^.*deleted: //" | xargs git rm 

may do it.

How to present UIActionSheet iOS Swift?

swift4 (tested)

let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .actionSheet)
    let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
        print("Default is pressed.....")
    }
    let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel is pressed......")
    }
    let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
        print("Destructive is pressed....")

    }
    alertController.addAction(action1)
    alertController.addAction(action2)
    alertController.addAction(action3)
    self.present(alertController, animated: true, completion: nil)

}

Using a SELECT statement within a WHERE clause

The principle of subqueries is not at all bad, but I don't think that you should use it in your example. If I understand correctly you want to get the maximum score for each date. In this case you should use a GROUP BY.

How to filter by IP address in Wireshark?

Try

ip.dst == 172.16.3.255

Count elements with jQuery

var count_elements = $('.class').length;

From: http://api.jquery.com/size/

The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

Please see:

http://api.jquery.com/size/

http://api.jquery.com/length/

Error handling in C code

I ran into this Q&A a number of times, and wanted to contribute a more comprehensive answer. I think the best way to think about this is how to return errors to caller, and what you return.

How

There are 3 ways to return information from a function:

  1. Return Value
  2. Out Argument(s)
  3. Out of Band, that includes non-local goto (setjmp/longjmp), file or global scoped variables, file system etc.

Return Value

You can only return value is a single object, however, it can be an arbitrary complex. Here is an example of an error returning function:

  enum error hold_my_beer();

One benefit of return values is that it allows chaining of calls for less intrusive error handling:

  !hold_my_beer() &&
  !hold_my_cigarette() &&
  !hold_my_pants() ||
  abort();

This not just about readability, but may also allow processing an array of such function pointers in a uniform way.

Out Argument(s)

You can return more via more than one object via arguments, but best practice does suggest to keep the total number of arguments low (say, <=4):

void look_ma(enum error *e, char *what_broke);

enum error e;
look_ma(e);
if(e == FURNITURE) {
  reorder(what_broke);
} else if(e == SELF) {
  tell_doctor(what_broke);
}

Out of Band

With setjmp() you define a place and how you want to handle an int value, and you transfer control to that location via a longjmp(). See Practical usage of setjmp and longjmp in C.

What

  1. Indicator
  2. Code
  3. Object
  4. Callback

Indicator

An error indicator only tells you that there is a problem but nothing about the nature of said problem:

struct foo *f = foo_init();
if(!f) {
  /// handle the absence of foo
}

This is the least powerful way for a function to communicate error state, however, perfect if caller cannot respond to the error in a graduated manner anyways.

Code

An error code tells the caller about the nature of the problem, and may allow for a suitable response (from the above). It can be return value, or like the look_ma() example above an error argument.

Object

With an error object, the caller can be informed about arbitrary complicated issues. For example, an error code and a suitable human readable message. It can also inform the caller that multiple things went wrong, or an error per item when processing a collection:

struct collection friends;
enum error *e = malloc(c.size * sizeof(enum error));
...
ask_for_favor(friends, reason);
for(int i = 0; i < c.size; i++) {
   if(reason[i] == NOT_FOUND) find(friends[i]);
}

Instead of pre-allocating the error array, you can also (re)allocate it dynamically as needed of course.

Callback

Callback is the most powerful way to handle errors, as you can tell the function what behavior you would like to see happen when something goes wrong. A callback argument can be added to each function, or if customization uis only required per instance of a struct like this:

 struct foo {
    ...
    void (error_handler)(char *);
 };

 void default_error_handler(char *message) { 
    assert(f);
    printf("%s", message);
 }

 void foo_set_error_handler(struct foo *f, void (*eh)(char *)) {
    assert(f);
    f->error_handler = eh;
 }

 struct foo *foo_init() {
    struct foo *f = malloc(sizeof(struct foo));
    foo_set_error_handler(f, default_error_handler);
    return f;
 }


 struct foo *f = foo_init();
 foo_something();

One interesting benefit of a callback is that it can be invoked multiple times, or none at all in the absence of errors in which there is no overhead on the happy path.

There is, however, an inversion of control. The calling code does not know if the callback was invoked. As such, it may make sense to also use an indicator.

Want to download a Git repository, what do I need (windows machine)?

I don't want to start a "What's the best unix command line under Windows" war, but have you thought of Cygwin? Git is in the Cygwin package repository.

And you get a lot of beneficial side-effects! (:-)

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

How to find server name of SQL Server Management Studio

Open up SQL Server Configuration Manager (search for it in the Start menu). Click on SQL Server Services. The instance name of SQL Server is in parenthesis inline with SQL Server service. If it says MSSQLSERVER, then it's the default instance. To connect to it in Management Studio, just type . (dot) OR (local) and click Connect. If the instance name is different, then use .\[instance name] to connect to it (for example if the instance name is SQL2008, connect to .\SQL2008).

Also make sure SQL Server and SQL Server Browser services are running, otherwise you won't be able to connect.

Edit:

Here's a screenshot of how it looks like on my machine. In this case, I have two instances installed: SQLExpress and SQL2008.

enter image description here

Pandas read_csv low_memory and dtype options

As the error says, you should specify the datatypes when using the read_csv() method. So, you should write

file = pd.read_csv('example.csv', dtype='unicode')

Laravel: Auth::user()->id trying to get a property of a non-object

Never forget to include and try to use middleware auth:

use Illuminate\Http\Request;   

Then find the id using request method:

$id= $request->user()->id;

How to start http-server locally

To start server locally paste the below code in package.json and run npm start in command line.

"scripts": { "start": "http-server -c-1 -p 8081" },

How to Serialize a list in java?

As pointed out already, most standard implementations of List are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

Setting up a JavaScript variable from Spring model by using Thymeleaf

I've seen this kind of thing work in the wild:

<input type="button"  th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />

Select from one table where not in another

Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT) pattern.

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)

Note that you only need to use ` backticks on reserved words, names with spaces and such, not with normal column names.

On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.

Make sure you have indexes on the fields in question
You need to have an index on pm.id, pd.part_num.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

How do I tell Gradle to use specific JDK version?

There is one more option to follow. In your gradle tasks available in Eclipse, you can set your desired jdk path. (I know this is a while since the question was posted. This answer can help someone.)

Right click on the deploy or any other task and select "Open Gradle Run Configuration..."

enter image description here

Then navigate to "Java Home" and paste your desired java path.

enter image description here

Please note that, bin will be added by the gradle task itself. So don't add the "bin" to the path.

What is the difference between MVC and MVVM?

The Controller is not replaced by a ViewModel in MVVM, because the ViewModel has a totally different functionality then a Controller. You still need a Controller, because without a Controller your Model, ViewModel and View will not do much... In MVVM you have a Controller too, the name MVVM is just missleading.

MVVMC is the correct name in my humble opinion.

As you can see the ViewModel is just an addition to the MVC pattern. It moves conversion-logic (for example convert object to a string) from the Controller to the ViewModel.

sending mail from Batch file

We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file

blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt

Or you can put that file in as the body

blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"

How can I make setInterval also work when a tab is inactive in Chrome?

Here's my rough solution

(function(){
var index = 1;
var intervals = {},
    timeouts = {};

function postMessageHandler(e) {
    window.postMessage('', "*");

    var now = new Date().getTime();

    sysFunc._each.call(timeouts, function(ind, obj) {
        var targetTime = obj[1];

        if (now >= targetTime) {
            obj[0]();
            delete timeouts[ind];
        }
    });
    sysFunc._each.call(intervals, function(ind, obj) {
        var startTime = obj[1];
        var func = obj[0];
        var ms = obj[2];

        if (now >= startTime + ms) {
            func();
            obj[1] = new Date().getTime();
        }
    });
}
window.addEventListener("message", postMessageHandler, true);
window.postMessage('', "*");

function _setTimeout(func, ms) {
    timeouts[index] = [func, new Date().getTime() + ms];
    return index++;
}

function _setInterval(func, ms) {
    intervals[index] = [func, new Date().getTime(), ms];
    return index++;
}

function _clearInterval(ind) {
    if (intervals[ind]) {
        delete intervals[ind]
    }
}
function _clearTimeout(ind) {
    if (timeouts[ind]) {
        delete timeouts[ind]
    }
}

var intervalIndex = _setInterval(function() {
    console.log('every 100ms');
}, 100);
_setTimeout(function() {
    console.log('run after 200ms');
}, 200);
_setTimeout(function() {
    console.log('closing the one that\'s 100ms');
    _clearInterval(intervalIndex)
}, 2000);

window._setTimeout = _setTimeout;
window._setInterval = _setInterval;
window._clearTimeout = _clearTimeout;
window._clearInterval = _clearInterval;
})();

downcast and upcast

  • Upcasting is an operation that creates a base class reference from a subclass reference. (subclass -> superclass) (i.e. Manager -> Employee)
  • Downcasting is an operation that creates a subclass reference from a base class reference. (superclass -> subclass) (i.e. Employee -> Manager)

In your case

Employee emp = (Employee)mgr; //mgr is Manager

you are doing an upcasting.

An upcast always succeeds unlike a downcast that requires an explicit cast because it can potentially fail at runtime.(InvalidCastException).

C# offers two operators to avoid this exception to be thrown:

Starting from:

Employee e = new Employee();

First:

Manager m = e as Manager; // if downcast fails m is null; no exception thrown

Second:

if (e is Manager){...} // the predicate is false if the downcast is not possible 

Warning: When you do an upcast you can only access to the superclass' methods, properties etc...

Inserting an item in a Tuple

one way is to convert it to list

>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)

Configure hibernate to connect to database via JNDI Datasource

Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">



  <jee:jndi-lookup id="dataSource"
                 jndi-name="Give_DataSource_Path_From_Your_Server"
                 expected-type="javax.sql.DataSource" />


Hope It will help someone.Thanks!

What is a NullPointerException, and how do I fix it?

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labeled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.)

Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.

So let's look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • "at Test.main" says that we were in the main method of the Test class.
  • "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.

In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

See also: What is a stack trace, and how can I use it to debug my application errors?

1 - Not quite true. There are things called nested exceptions...

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.

Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and... BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second "at" line.

So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let's try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two "at" lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);
    

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

How to solve Permission denied (publickey) error when using Git?

I hit this error because I needed to give my present working directory permissions 700:

chmod -R 700 /home/ec2-user/

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

I got the same issue and It got solved by installing Oracle 11g client in my machine..

I have not installed any excclusive drivers for it. I am using windows7 with 64 bit. Interestignly, when I navigate into the path Start > Settings > Control Panel > Administrative Tools > DataSources(ODBC) > Drivers. I found only SQL server in it

Please Finc the attachment below for the same

How to search for a part of a word with ElasticSearch

Try the solution with is described here: Exact Substring Searches in ElasticSearch

{
    "mappings": {
        "my_type": {
            "index_analyzer":"index_ngram",
            "search_analyzer":"search_ngram"
        }
    },
    "settings": {
        "analysis": {
            "filter": {
                "ngram_filter": {
                    "type": "ngram",
                    "min_gram": 3,
                    "max_gram": 8
                }
            },
            "analyzer": {
                "index_ngram": {
                    "type": "custom",
                    "tokenizer": "keyword",
                    "filter": [ "ngram_filter", "lowercase" ]
                },
                "search_ngram": {
                    "type": "custom",
                    "tokenizer": "keyword",
                    "filter": "lowercase"
                }
            }
        }
    }
}

To solve the disk usage problem and the too-long search term problem short 8 characters long ngrams are used (configured with: "max_gram": 8). To search for terms with more than 8 characters, turn your search into a boolean AND query looking for every distinct 8-character substring in that string. For example, if a user searched for large yard (a 10-character string), the search would be:

"arge ya AND arge yar AND rge yard.

Is there a way to detect if a browser window is not currently active?

A slightly more complicated way would be to use setInterval() to check mouse position and compare to last check. If the mouse hasn't moved in a set amount of time, the user is probably idle.

This has the added advantage of telling if the user is idle, instead of just checking if the window is not active.

As many people have pointed out, this is not always a good way to check whether the user or browser window is idle, as the user might not even be using the mouse or is watching a video, or similar. I am just suggesting one possible way to check for idle-ness.

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Self-Signed Certificate Authorities pip / conda

After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:

NEVER disable all SSL verification!

This creates a bad security culture. Don't be that person.

tl;dr

pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify

# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt

But where do we get ca-bundle.crt?


Get an up to date CA Bundle

cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox

https://curl.haxx.se/docs/caextract.html

I recommend you open up this cacert.pem file in a text editor as we will need to add our self-signed CA to this file.

Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:

----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----

https://support.ssl.com/Knowledgebase/Article/View/19/0/der-vs-crt-vs-cer-vs-pem-certificates-and-how-to-convert-them


Getting our Self Signed Certificate

Below are a few options on how to get our self signed certificate:

  • Via OpenSSL CLI
  • Via Browser
  • Via Python Scripting

Get our Self-Signed Certificate by OpenSSL CLI

https://unix.stackexchange.com/questions/451207/how-to-trust-self-signed-certificate-in-curl-command-line/468360#468360

echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem

Get our Self-Signed Certificate Authority via Browser

Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.

Copy the contents of this exported file and paste it at the end of your cacerts.pem file.

For consistency rename this file cacerts.pem --> ca-bundle.crt and place it somewhere easy like:

# Windows
%USERPROFILE%\certs\ca-bundle.crt

# or *nix
$HOME/certs/cabundle.crt

Get our Self-Signed Certificate Authority via Python

Thanks to all the brilliant answers in:

How to get response SSL certificate from requests in python?

I have put together the following to attempt to take it a step further.

https://github.com/neozenith/get-ca-py


Finally

Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.

pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt

OR

pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt

THEN

pip config list
conda config --show ssl_verify

# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'

References

SELECT data from another schema in oracle

Does the user that you are using to connect to the database (user A in this example) have SELECT access on the objects in the PCT schema? Assuming that A does not have this access, you would get the "table or view does not exist" error.

Most likely, you need your DBA to grant user A access to whatever tables in the PCT schema that you need. Something like

GRANT SELECT ON pct.pi_int
   TO a;

Once that is done, you should be able to refer to the objects in the PCT schema using the syntax pct.pi_int as you demonstrated initially in your question. The bracket syntax approach will not work.

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Many people will feel surprised maybe, but this question is incorrect. If you hear this question during an interview, you need to help the interviewer understand where the confusion is.

Let's start from the fact that there is no concrete pattern that is called just "Factory". There is pattern that is called "Abstract Factory", and there is pattern that is called "Factory Method".

So, what does "Factory" mean then? one of the following (all can be considered correct, depending on the scope of the reference):

  • Some people use it as an alias (shortcut) for "Abstract Factory".
  • Some people use it as an alias (shortcut) for "Factory Method".
  • Some people use it as a more general name for all factory/creational patterns. E.g. both "Abstract Factory" and "Factory Method" are Factories.

And, unfortunately, many people use "Factory" to denote another kind of factory, that creates factory or factories (or their interfaces). Based on their theory:

Product implements IProduct, which is created by Factory, which implements IFactory, which is created by AbstractFactory.

To understand how silly this is, let's continue our equation:

AbstractFactory implements IAbstractFactory, which is created by... AbstractAbstractFactory???

I hope you see the point. Don't get confused, and please don't invent things that don't exist for reason.

-

P.S.: Factory for Products is AbstractFactory, and Factory for Abstract Factories would be just another example of AbstractFactory as well.

How to list only top level directories in Python?

[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]

psql: FATAL: Ident authentication failed for user "postgres"

You can set the environment variable PGHOST=localhost:

$ psql -U db_user db_name
psql: FATAL:  Peer authentication failed for user "db_user"

$ export PGHOST=localhost
$ psql -U db_user db_name

Password for user mfonline:

Git - Undo pushed commits

Here is my way:

Let's say the branch name is develop.

# Create a new temp branch based on one history commit
git checkout <last_known_good_commit_hash>
git checkout -b develop-temp

# Delete the original develop branch and 
# create a new branch with the same name based on the develop-temp branch
git branch -D develop
git checkout -b develop

# Force update this new branch
git push -f origin develop

# Remove the temp branch
git branch -D develop-temp

Changing :hover to touch/click for mobile devices

Well I agree with above answers but still there can be an another way to do this and it is by using media queries.

Suppose this is what you want to do :

body.nontouch nav a:hover {
    background: yellow;
}

then you can do this by media query as :

@media(hover: hover) and (pointer: fine) {
    nav a:hover {
        background: yellow;
    }
}

And for more details you can visit this page.

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

They are the same when used for output, e.g. with printf.

However, these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal (if preceded by 0).

So 033 would be 27 with %i but 33 with %d.

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Echo equivalent in PowerShell for script testing

There are several ways:

Write-Host: Write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to be set.

Write-Debug: Write directly to the console, if $DebugPreference set to Continue or Stop.

Write-Verbose: Write directly to the console, if $VerbosePreference set to Continue or Stop.

The latter is intended for extra optional information, Write-Debug for debugging (so would seem to fit in this case).

Additional: In PSH2 (at least) scripts using cmdlet binding will automatically get the -Verbose and -Debug switch parameters, locally enabling Write-Verbose and Write-Debug (i.e. overriding the preference variables) as compiled cmdlets and providers do.

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Print range of numbers on same line

This is an old question, xrange is not supported in Python3.

You can try -

print(*range(1,11)) 

OR

for i in range(10):
    print(i, end = ' ')

Copy folder recursively in Node.js

ncp locks the file descriptor and fires a callback when it hasn't been unlocked yet.

I recommend to use the recursive-copy module instead. It supports events and you can be sure in the copy ending.

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

You can do like

HTML in PHP :

<?php
     echo "<table>";
     echo "<tr>";
     echo "<td>Name</td>";
     echo "<td>".$name."</td>";
     echo "</tr>";
     echo "</table>";
?>

Or You can write like.

PHP in HTML :

<?php /*Do some PHP calculation or something*/ ?>
     <table>
         <tr>
             <td>Name</td>
             <td><?php echo $name;?></td>
         </tr>
     </table>


<?php /*Do some PHP calculation or something*/ ?> Means:
You can open a PHP tag with <?php, now add your PHP code, then close the tag with ?> and then write your html code. When needed to add more PHP, just open another PHP tag with <?php.

Finding the max/min value in an array of primitives using Java

Here's a utility class providing min/max methods for primitive types: Primitives.java

int [] numbers= {10,1,8,7,6,5,2};
    int a=Integer.MAX_VALUE;
    for(int c:numbers) {
        a=c<a?c:a;
        }
        
    System.out.println("Lowest value is"+a);

How to deal with ModalDialog using selenium webdriver?

Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.

WebElement link = // element that will showModalDialog()

// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
    "var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
  link);

// wait for there to be two windows and choose the one that is 
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
    .until(new Function<WebDriver, Boolean>() {
    @Override
    public Boolean apply(final WebDriver driver) {
        final String[] windowHandles =
            driver.getWindowHandles().toArray(new String[0]);
        if (windowHandles.length != 2) {
            return false;
        }
        if (windowHandles[0].equals(parentWindowHandle)) {
            driver.switchTo().window(windowHandles[1]);
        } else {
            driver.switchTo().window(windowHandles[0]);
        }
        return true;
    }
});

Nginx reverse proxy causing 504 Gateway Timeout

In my case i restart php for and it become ok.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Find the process id of your webapp/java process from top. Use jmap heap to get the heap allocation. I tested this on AWS-Ec2 for elastic beanstalk

You can see in image below 3GB max heap for the application

enter image description here

How to change the style of the title attribute inside an anchor tag?

You cannot style the default browser tooltip. But you can use javascript to create your own custom HTML tooltips.

Is there a way to add a gif to a Markdown file?

If you can provide your image in SVG format and if it is an icon and not a photo so it can be animated with SMIL animations, then it would be definitely the superior alternative to gif images (or even other formats).

SVG images, like other image files, could be used with either standard markup or HTML <img> element:

![image description](the_path_to/image.svg)
<img src="the_path_to/image.svg" width="128"/>

How can I switch word wrap on and off in Visual Studio Code?

If you want a permanent solution for wordwrapping lines, go to menu FilePreferenceSettings and change editor.wordWrap: "on". This will apply always.

However, we usually keep changing our preference to check code. So, I use the Alt + Z key to wrap written code of a file or you can go to menu ViewToggle Word Wrap. This applies whenever you want not always. And again Alt + Z to undo wordwrap (will show the full line in one line).

Grouping switch statement cases together?

You can use like this:

case 4: case 2:
 {
   //code ...
 }

For use 4 or 2 switch case.

How to get substring of NSString?

Use this also

NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];

Note - Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

Disable browser 'Save Password' functionality

This is my html code for solution. It works for Chrome-Safari-Internet Explorer. I created new font which all characters seem as "?". Then I use this font for my password text. Note: My font name is "passwordsecretregular".

<style type="text/css">
         #login_parola {
             font-family: 'passwordsecretregular' !important;
            -webkit-text-security: disc !important;
            font-size: 22px !important;
         }
    </style>


<input type="text" class="w205 has-keyboard-alpha"  name="login_parola" id="login_parola" onkeyup="checkCapsWarning(event)"  
   onfocus="checkCapsWarning(event)" onblur="removeCapsWarning()" onpaste="return false;" maxlength="32"/>

Variable's memory size in Python

Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get

>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160

There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.

If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).

How to implement a property in an interface

In the interface, you specify the property:

public interface IResourcePolicy
{
   string Version { get; set; }
}

In the implementing class, you need to implement it:

public class ResourcePolicy : IResourcePolicy
{
   public string Version { get; set; }
}

This looks similar, but it is something completely different. In the interface, there is no code. You just specify that there is a property with a getter and a setter, whatever they will do.

In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.

What is the memory consumption of an object in Java?

The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example).

For the detailed rules for the SUN JVM check my old blog

Regards, Markus

CSV file written with Python has blank lines between each row

Use the method defined below to write data to the CSV file.

open('outputFile.csv', 'a',newline='')

Just add an additional newline='' parameter inside the open method :

def writePhoneSpecsToCSV():
    rowData=["field1", "field2"]
    with open('outputFile.csv', 'a',newline='') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(rowData)

This will write CSV rows without creating additional rows!

How do I get IntelliJ to recognize common Python modules?

Here's what I had to do. (And I probably forgot an important aspect of my problem, which is that this wasn't set up as a Python project originally, but a Java project, with some python files in them.)

Project Settings -> Modules -> Plus button (add a module) -> Python

Then, click the "..." button next to Python Interpreter.

In the "Configure SDK" dialog that pops up, click the "+" button. Select "Python SDK", then select the default "Python" shortcut that appears in my finder dialog

Wait about 5 minutes. Read some productivity tips. :)

Click Ok

Wait for the system to rebuild some indexes.

Hooray! Code hinting is back for my modules!

jQuery AJAX file upload PHP

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}

Getting a machine's external IP address with Python

Use this script :

import urllib, json

data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]

Without json :

import urllib, re

data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data

How to get URL of current page in PHP

The other answers are correct. However, a quick note: if you're looking to grab the stuff after the ? in a URI, you should use the $_GET[] array.

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

Why do Sublime Text 3 Themes not affect the sidebar?

In Material theme 3.1.4 you can change theme like this: Tools->Metherial Theme->Material Theme Config. Its very easy.

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

$html = file_get_contents("http://www.somesite.com/");

$dom = new DOMDocument();
$dom->loadHTML(htmlspecialchars($html));

echo $dom;

try this

how to change text box value with jQuery?

<style>
    .form-cus {
        width: 200px;
        margin: auto;
        position: relative;
    }
        .form-cus .putval, .form-cus .getval {
            width: 100%;
        }
        .form-cus .putval {
            position: absolute;
            left: 0px;
            top: 0;
            color: transparent !important;
            box-shadow: 0 0 0 0 !important;
            background-color: transparent !important;
            border: 0px;
            outline: 0 none;
        }
            .form-cus .putval::selection {
                color: transparent;
                background: lightblue;
            }
</style>

<link href="css/bootstrap.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<div class="form-group form-cus">
    <input class="putval form-control" type="text" id="input" maxlength="16" oninput="xText();">
    <input class="getval form-control" type="text" id="output" maxlength="16">
</div>

<script type="text/javascript">
    function xText() {
        var x = $("#input").val();
        var x_length = x.length;
        var a = '';
        for (var i = 0; i < x_length; i++) {
            a += "x";
        }
        $("#output").val(a);
     }
    $("#input").click(function(){
     $("#output").trigger("click");
    })

</script>

What is the correct way to declare a boolean variable in Java?

In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.

This is helpful when your equals method call throws some exception e.g. NullPointerException;

     boolean isMatch = false;

     try{
         isMatch = email1.equals (email2);
      }catch(NullPointerException npe){
         .....
      }
      System.out.print("Match=="+isMatch);
      if(isMatch){
        ......
      }

Installing jQuery?

Install JQuery with only JavaScript. This is not a very good solution if you are developing a website but it's great if you want JQuery in the JavaScript console of a random website that does not use JQuery already.

function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}
loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js")

loadScript function thanks to e-satis's answer to Include JavaScript file inside JavaScript file?

Conversion hex string into ascii in bash command line

Make a script like this:

#!/bin/bash

echo $((0x$1)).$((0x$2)).$((0x$3)).$((0x$4))

Example:

sh converthextoip.sh c0 a8 00 0b

Result:

192.168.0.11

How to import load a .sql or .csv file into SQLite?

If you are happy to use a (python) script then there is a python script that automates this at: https://github.com/rgrp/csv2sqlite

This will auto-create the table for you as well as do some basic type-guessing and data casting for you (so e.g. it will work out something is a number and set the column type to "real").

How do I make Git use the editor of my choice for commits?

For Mac OS X, using TextEdit or the natural environmental editor for text:

git config --global core.editor "open -W -n"

How to prevent caching of my Javascript file?

Add a random query string to the src

You could either do this manually by incrementing the querystring each time you make a change:

<script src="test.js?version=1"></script>

Or if you are using a server side language, you could automatically generate this:

ASP.NET:

<script src="test.js?rndstr=<%= getRandomStr() %>"></script>

More info on cache-busting can be found here:

https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/

Using Python, how can I access a shared folder on windows network?

How did you try it? Maybe you are working with \ and omit proper escaping.

Instead of

open('\\HOST\share\path\to\file')

use either Johnsyweb's solution with the /s, or try one of

open(r'\\HOST\share\path\to\file')

or

open('\\\\HOST\\share\\path\\to\\file')

.

Connecting to remote URL which requires authentication using Java

Be really careful with the "Base64().encode()"approach, my team and I got 400 Apache bad request issues because it adds a \r\n at the end of the string generated.

We found it sniffing packets thanks to Wireshark.

Here is our solution :

import org.apache.commons.codec.binary.Base64;

HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());

private String getBasicAuthenticationEncoding() {

        String userPassword = username + ":" + password;
        return new String(Base64.encodeBase64(userPassword.getBytes()));
    }

Hope it helps!

Using underscores in Java variables and method names

sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs();

as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable();

Copy file or directories recursively in Python

The python shutil.copytree method its a mess. I've done one that works correctly:

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)
    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

How to force page refreshes or reloads in jQuery?

Replace with:

$('#something').click(function() {
    location.reload();
});

Server Discovery And Monitoring engine is deprecated

It is important to run your mongod command and keep the server running. If not, you will still be seeing this error.

I attach you my code:

_x000D_
_x000D_
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient

const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'

MongoClient.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
    if(error) {
        return console.log('Error connecting to the server.')
    }

    console.log('Succesfully connected.')
})
_x000D_
_x000D_
_x000D_

Response Buffer Limit Exceeded

I faced the same kind of issue, my IIS version is 8.5. Increased the Response Buffering Limit under the ASP -> Limit Properties solved the issue.

  1. In IIS 8.5, select your project, you can see the options in the right hand side. In that under the IIS, you can see the ASP option.

ASP option

  1. In the option window increase the Response Buffering Limit to 40194304 (approximately 40 MB) .

Increase buffer limit

  1. Navigate away from the option, in the right hand side top you can see the Actions menu, Select Apply. It solved my problem.

Apply settings

How do I tell if a variable has a numeric value in Perl?

I found this interesting though

if ( $value + 0 eq $value) {
    # A number
    push @args, $value;
} else {
    # A string
    push @args, "'$value'";
}

Read specific columns from a csv file with csv module?

With pandas you can use read_csv with usecols parameter:

df = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

Example:

import pandas as pd
import io

s = '''
total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
'''

df = pd.read_csv(io.StringIO(s), usecols=['total_bill', 'day', 'size'])
print(df)

   total_bill  day  size
0       16.99  Sun     2
1       10.34  Sun     3
2       21.01  Sun     3

How to import other Python files?

I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:

/main.py
/mymodule
    /__init__.py
    /somefile.py
    /otherstuff.py

When loading somefile.py/otherstuff.py from __init__.py the contents should look like:

from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc

How can I set the opacity or transparency of a Panel in WinForms?

some comments says that it works and some say it doesn't It works only for your form background not any other controls behind

Stop a youtube video with jquery?

This works for me on both YouTube and Vimeo players. I'm basically just resetting the src attribute, so be aware that the video will go back to the beginning.

var $theSource = $theArticleDiv.find('.views-field-field-video-1 iframe').attr('src');

$theArticleDiv.find('.views-field-field-video-1 iframe').attr('src', $theSource); //reset the video so it stops playing

$theArticleDiv is my current video's container - since I have multiple videos on the page, and they're being exposed via a Drupal view at runtime, I have no idea what their ids are going to be. So I've bound muy click event to a currently visible element, found its parent, and decided that's $theArticleDiv.

('.views-field-field-video-1 iframe') finds the current video's iframe for me - in particular the one that's visible right now. That iframe has a src attribute. I just pick that up and reset it right back to what it already was, and automagically the video stops and goes back to the start. If my users want to pause and resume, they can do it without closing the video, of course - but frankly if they do close the video, I feel they can live with the fact that it's reset to the start.

HTH

fetch in git doesn't get all branches

The problem can be seen when checking the remote.origin.fetch setting
(The lines starting with $ are bash prompts with the commands I typed. The other lines are the resulting output)

$ git config --get remote.origin.fetch
+refs/heads/master:refs/remotes/origin/master

As you can see, in my case, the remote was set to fetch the master branch specifically and only. I fixed it as per below, including the second command to check the results.

$ git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
$ git config --get remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

The wildcard * of course means everything under that path.

Unfortunately I saw this comment after I had already dug through and found the answer by trial and error.

Adding a 'share by email' link to website

Something like this might be the easiest way.

<a href="mailto:?subject=I wanted you to see this site&amp;body=Check out this site http://www.website.com."
   title="Share by Email">
  <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>

You could find another email image and add that if you wanted.

Prevent screen rotation on Android

Rather than going into the AndroidManifest, you could just do this:

screenOrientation = getResources().getConfiguration().orientation;
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
... AsyncTask

screenOrientation = getResources().getConfiguration().orientation;


@Override
protected void onPostExecute(String things) {
    context.setRequestedOrientation(PlayListFragment.screenOrientation);
    or 
    context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}

The only drawback here is that it requires API level 18 or higher. So basically this is the tip of the spear.

How to compile C programming in Windows 7?

If you are familiar with gcc, as you indicated in the question, you can install MinGW, which will set a linux-like compile environment in Win7. Otherwise, Visual Studio 2010 Express is the best choice.

html cellpadding the left side of a cell

This is what css is for... HTML doesn't allow for unequal padding. When you say that you don't want to use style sheets, does this mean you're OK with inline css?

<table>
    <tr>
        <td style="padding: 5px 10px 5px 5px;">Content</td>
        <td style="padding: 5px 10px 5px 5px;">Content</td>
    </tr>
</table>

You could also use JS to do this if you're desperate not to use stylesheets for some reason.

Error importing SQL dump into MySQL: Unknown database / Can't create database

It sounds like your database dump includes the information for creating the database. So don't give the MySQL command line a database name. It will create the new database and switch to it to do the import.

Fastest way to set all values of an array?

See Arrays.fill method:

char f = '+';
char [] c = new char [50];
Arrays.fill(c, f);

Laravel use same form for create and edit

Pretty easy in your controller you do:

public function create()
{
    $user = new User;

    $action = URL::route('user.store');

    return View::('viewname')->with(compact('user', 'action'));
}

public function edit($id)
{
    $user = User::find($id);

    $action = URL::route('user.update', ['id' => $id]);

    return View::('viewname')->with(compact('user', 'action'));
}

And you just have to use this way:

{{ Form::model($user, ['action' => $action]) }}

   {{ Form::input('email') }}
   {{ Form::input('first_name') }}

{{ Form::close() }}

Preloading images with JavaScript

I recommend you use a try/catch to prevent some possible issues:

OOP:

    var preloadImage = function (url) {
        try {
            var _img = new Image();
            _img.src = url;
        } catch (e) { }
    }

Standard:

    function preloadImage (url) {
        try {
            var _img = new Image();
            _img.src = url;
        } catch (e) { }
    }

Also, while I love DOM, old stupid browsers may have problems with you using DOM, so avoid it altogether IMHO contrary to freedev's contribution. Image() has better support in old trash browsers.

How can I list all tags for a Docker image on a remote registry?

I have done this thing when I have to implement a task in which if user somehow type the wrong tag then we have to give the list of all the tag present in the repo(Docker repo) present in the register. So I have code in batch Script.

<html>
<pre style="background-color:#bcbbbb;">
@echo off

docker login --username=xxxx --password=xxxx
docker pull %1:%2

IF NOT %ERRORLEVEL%==0 (
echo "Specified Version is Not Found "
echo "Available Version for this image is :"
for /f %%i in (' curl -s -H "Content-Type:application/json" -X POST -d "{\"username\":\"user\",\"password\":\"password\"}" https://hub.docker.com/v2/users/login ^|jq -r .token ') do set TOKEN=%%i
curl -sH "Authorization: JWT %TOKEN%" "https://hub.docker.com/v2/repositories/%1/tags/" | jq .results[].name
)
</pre>
</html>

So in this we can give arguments to out batch file like:

Dockerfile java version7 

How to get thread id of a pthread in linux c program?

As noted in other answers, pthreads does not define a platform-independent way to retrieve an integral thread ID.

On Linux systems, you can get thread ID thus:

#include <sys/types.h>
pid_t tid = gettid();

On many BSD-based platforms, this answer https://stackoverflow.com/a/21206357/316487 gives a non-portable way.

However, if the reason you think you need a thread ID is to know whether you're running on the same or different thread to another thread you control, you might find some utility in this approach

static pthread_t threadA;

// On thread A...
threadA = pthread_self();

// On thread B...
pthread_t threadB = pthread_self();
if (pthread_equal(threadA, threadB)) printf("Thread B is same as thread A.\n");
else printf("Thread B is NOT same as thread A.\n");

If you just need to know if you're on the main thread, there are additional ways, documented in answers to this question how can I tell if pthread_self is the main (first) thread in the process?.

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine
End Sub
Sub OtherSubRoutine()
    MsgBox wbA.Name, vbInformation
End Sub

Alternately, you can pass variables between subroutines:

Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
    MsgBox wb1.Name, vbInformation
    MsgBox wb2.Name, vbInformation
End Sub

Or use Functions to return values:

Sub MySubroutine()
    Dim i as Long
    i = MyFunction()
    MsgBox i
End Sub
Function MyFunction()
    'Lots of code that does something
    Dim x As Integer, y as Double
    For x = 1 to 1000
        'Lots of code that does something
    Next
    MyFunction = y
End Function

In the second method, within the scope of OtherSubRoutine you refer to them by their parameter names wb1 and wb2. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.

A Note About User Forms

Personally I would recommend keeping Option Explicit in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn when you meant lCount etc., among other reasons).

If you're using Option Explicit (which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public scoped variables, as these are not "public" in the same sense. For instance, i is undefined, though it's Public in the scope of UserForm1:

enter image description here

You can refer to it as UserForm1.i to avoid the compile error, or since forms are New-able, you can create a variable object to contain reference to your form, and refer to it that way:

enter image description here

NB: In the above screenshots x is declared Public x as Long in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x to avoid ambiguity and possible shadowing in case you re-use variable names...

Fling gesture detection on grid layout

Gestures are those subtle motions to trigger interactions between the touch screen and the user. It lasts for the time between the first touch on the screen to the point when the last finger leaves the surface.

Android provides us with a class called GestureDetector using which we can detect common gestures like tapping down and up, swiping vertically and horizontally (fling), long and short press, double taps, etc. and attach listeners to them.

Make our Activity class implement GestureDetector.OnDoubleTapListener (for double tap gesture detection) and GestureDetector.OnGestureListener interfaces and implement all the abstract methods.For more info. you may visit https://developer.android.com/training/gestures/detector.html . Courtesy

For Demo Test.GestureDetectorDemo

How do I find my host and username on mysql?

Default user for MySQL is "root", and server "localhost".

Dynamically add child components in React

You need to pass your components as children, like this:

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);

And then append them in the component's body:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});

You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:

var App = React.createClass({

    getInitialState: function(){
        return [
            {id:1,name:"Some Name"}
        ]
    },

    addChild: function() {
        // State change will cause component re-render
        this.setState(this.state.concat([
            {id:2,name:"Another Name"}
        ]))
    }

    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <button onClick={this.addChild}>Add component</button>
                {
                    this.state.map((item) => (
                        <SampleComponent key={item.id} name={item.name}/>
                    ))
                }
            </div>
        );
    }

});

What is the difference between utf8mb4 and utf8 charsets in MySQL?

UTF-8 is a variable-length encoding. In the case of UTF-8, this means that storing one code point requires one to four bytes. However, MySQL's encoding called "utf8" (alias of "utf8mb3") only stores a maximum of three bytes per code point.

So the character set "utf8"/"utf8mb3" cannot store all Unicode code points: it only supports the range 0x000 to 0xFFFF, which is called the "Basic Multilingual Plane". See also Comparison of Unicode encodings.

This is what (a previous version of the same page at) the MySQL documentation has to say about it:

The character set named utf8[/utf8mb3] uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:

  • For a BMP character, utf8[/utf8mb3] and utf8mb4 have identical storage characteristics: same code values, same encoding, same length.

  • For a supplementary character, utf8[/utf8mb3] cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8[/utf8mb3] cannot store the character at all, you do not have any supplementary characters in utf8[/utf8mb3] columns and you need not worry about converting characters or losing data when upgrading utf8[/utf8mb3] data from older versions of MySQL.

So if you want your column to support storing characters lying outside the BMP (and you usually want to), such as emoji, use "utf8mb4". See also What are the most common non-BMP Unicode characters in actual use?.

How do I hide the bullets on my list for the sidebar?

You have a selector ul on line 252 which is setting list-style: square outside none (a square bullet). You'll have to change it to list-style: none or just remove the line.

If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:

ul#groups-list.items-list { list-style: none }

Using CSS :before and :after pseudo-elements with inline CSS?

as mentioned above: its not possible to call a css pseudo-class / -element inline. what i now did, is: give your element a unique identifier, f.ex. an id or a unique class. and write a fitting <style> element

<style>#id29:before { content: "*";}</style>
<article id="id29">
  <!-- something -->
</article>

fugly, but what inline css isnt..?

What charset does Microsoft Excel use when saving files?

Excel 2010 saves an UTF-16/UCS-2 TSV file, if you select File > Save As > Unicode Text (.txt). It's (force) suffixed ".txt", which you can change to ".tsv".

If you need CSV, you can then convert the TSV file in a text editor like Notepad++, Ultra Edit, Crimson Editor etc, replacing tabs by semi-colons, commas or the like. Note that e.g. for reading into a DB table, often TSV works fine already (and it is often easier to read manually).

If you need a different code page like UTF-8, use one of the above mentioned editors for converting.

Equivalent of typedef in C#

I think there is no typedef. You could only define a specific delegate type instead of the generic one in the GenericClass, i.e.

public delegate GenericHandler EventHandler<EventData>

This would make it shorter. But what about the following suggestion:

Use Visual Studio. This way, when you typed

gcInt.MyEvent += 

it already provides the complete event handler signature from Intellisense. Press TAB and it's there. Accept the generated handler name or change it, and then press TAB again to auto-generate the handler stub.

Split a string into an array of strings based on a delimiter

Using the SysUtils.TStringHelper.Split function, introduced in Delphi XE3:

var
  MyString: String;
  Splitted: TArray<String>;
begin
  MyString := 'word:doc,txt,docx';
  Splitted := MyString.Split([':']);
end.

This will split a string with a given delimiter into an array of strings.

Why should I use a pointer rather than the object itself?

This is has been discussed at length, but in Java everything is a pointer. It makes no distinction between stack and heap allocations (all objects are allocated on the heap), so you don't realize you're using pointers. In C++, you can mix the two, depending on your memory requirements. Performance and memory usage is more deterministic in C++ (duh).

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

How to quietly remove a directory with content in PowerShell

Below is a copy-pasteable implementation of Michael Freidgeim's answer

function Delete-FolderAndContents {
    # http://stackoverflow.com/a/9012108

    param(
        [Parameter(Mandatory=$true, Position=1)] [string] $folder_path
    )

    process {
        $child_items = ([array] (Get-ChildItem -Path $folder_path -Recurse -Force))
        if ($child_items) {
            $null = $child_items | Remove-Item -Force -Recurse
        }
        $null = Remove-Item $folder_path -Force
    }
}

Why don’t my SVG images scale using the CSS "width" property?

You have to modify the viewBox property to change the height and the width correctly with a svg. It is in the <svg> tag of the svg.

https://developer.mozilla.org/en/docs/Web/SVG/Attribute/viewBox

.NET Global exception handler in console application

I just inherited an old VB.NET console application and needed to set up a Global Exception Handler. Since this question mentions VB.NET a few times and is tagged with VB.NET, but all the other answers here are in C#, I thought I would add the exact syntax for a VB.NET application as well.

Public Sub Main()
    REM Set up Global Unhandled Exception Handler.
    AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionEvent

    REM Do other stuff
End Sub

Public Sub MyUnhandledExceptionEvent(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    REM Log Exception here and do whatever else is needed
End Sub

I used the REM comment marker instead of the single quote here because Stack Overflow seemed to handle the syntax highlighting a bit better with REM.

Protect .NET code from reverse engineering?

It's impossible to fully secure an application, sorry.

Hide text using css

h1 {
    text-indent: -3000px; 
    line-height: 3000px;
    background-image: url(/LOGO.png);
    height: 100px; width:  600px;  /* height and width are a must */

}

Refresh Page and Keep Scroll Position

This might be useful for refreshing also. But if you want to keep track of position on the page before you click on a same position.. The following code will help.

Also added a data-confirm for prompting the user if they really want to do that..

Note: I'm using jQuery and js-cookie.js to store cookie info.

$(document).ready(function() {
    // make all links with data-confirm prompt the user first.
    $('[data-confirm]').on("click", function (e) {
        e.preventDefault();
        var msg = $(this).data("confirm");
        if(confirm(msg)==true) {
            var url = this.href;
            if(url.length>0) window.location = url;
            return true;
        }
        return false;
    });

    // on certain links save the scroll postion.
    $('.saveScrollPostion').on("click", function (e) {
        e.preventDefault();
        var currentYOffset = window.pageYOffset;  // save current page postion.
        Cookies.set('jumpToScrollPostion', currentYOffset);
        if(!$(this).attr("data-confirm")) {  // if there is no data-confirm on this link then trigger the click. else we have issues.
            var url = this.href;
            window.location = url;
            //$(this).trigger('click');  // continue with click event.
        }
    });

    // check if we should jump to postion.
    if(Cookies.get('jumpToScrollPostion') !== "undefined") {
        var jumpTo = Cookies.get('jumpToScrollPostion');
        window.scrollTo(0, jumpTo);
        Cookies.remove('jumpToScrollPostion');  // and delete cookie so we don't jump again.
    }
});

A example of using it like this.

<a href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

react-router - pass props to handler component

Using ES6 you can just make component wrappers inline:

<Route path="/" component={() => <App myProp={someValue}/>} >

If you need to pass children:

<Route path="/" component={(props) => <App myProp={someValue}>{props.children}</App>} >

File URL "Not allowed to load local resource" in the Internet Browser

You just need to replace all image network paths to byte strings in HTML string. For this first you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

        // Decode the encoded string.
        StringWriter myWriter = new StringWriter();
        HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
        string DecodedHtmlString = myWriter.ToString();

        //find and replace each img src with byte string
         HtmlDocument document = new HtmlDocument();
         document.LoadHtml(DecodedHtmlString);
         document.DocumentNode.Descendants("img")
          .Where(e =>
        {
            string src = e.GetAttributeValue("src", null) ?? "";
            return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
        })
        .ToList()
                    .ForEach(x =>
                    {
                        string currentSrcValue = x.GetAttributeValue("src", null);                                
                        string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
                        string filename = Path.GetFileName(currentSrcValue);
                        string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
                        FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fs);
                        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                        br.Close();
                        fs.Close();
                        x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
                    });

        string result = document.DocumentNode.OuterHtml;
        //Encode HTML string
        string myEncodedString = HttpUtility.HtmlEncode(result);

        Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

Don't use:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

because works bad. Instead of that, use:

fun setFullScreen(fullScreen: Boolean) {
        val decorView = getWindow().getDecorView()
        val uiOptions : Int
        if(fullScreen){
            uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN // this hide statusBar
            toolbar.visibility = View.GONE // if you use toolbar
            tabs.visibility = View.GONE // if you use tabLayout
        } else {
            uiOptions = View.SYSTEM_UI_FLAG_VISIBLE // this show statusBar
            toolbar.visibility = View.VISIBLE
            tabs.visibility = View.VISIBLE
        }
        decorView.setSystemUiVisibility(uiOptions)
    }

How to add default signature in Outlook

The existing answers had a few problems for me:

  1. I needed to insert text (e.g. 'Good Day John Doe') with html formatting where you would normally type your message.
  2. At least on my machine, Outlook adds 2 blank lines above the signature where you should start typing. These should obviously be removed (replaced with custom HTML).

The code below does the job. Please note the following:

  1. The 'From' parameter allows you to choose the account (since there could be different default signatures for different email accounts)
  2. The 'Recipients' parameter expects an array of emails, and it will 'Resolve' the added email (i.e. find it in contacts, as if you had typed it in the 'To' box)
  3. Late binding is used, so no references are required
'Opens an outlook email with the provided email body and default signature
'Parameters:
'  from: Email address of Account to send from.  Wildcards are supported e.g. *@example.com
'  recipients: Array of recipients.  Recipient can be a Contact name or email address
'  subject: Email subject
'  htmlBody: Html formatted body to insert before signature (just body markup, should not contain html, head or body tags)
Public Sub CreateMail(from As String, recipients, subject As String, htmlBody As String)
    Dim oApp, oAcc As Object
    
    Set oApp = CreateObject("Outlook.application")
    
    With oApp.CreateItem(0) 'olMailItem = 0
        'Ensure we are sending with the correct account (to insert the correct signature)
        'oAcc is of type Outlook.Account, which has other properties that could be filtered with if required
        'SmtpAddress is usually equal to the raw email address
        .SendUsingAccount = Nothing
        For Each oAcc In oApp.Session.Accounts
            If CStr(oAcc.SmtpAddress) = from Or CStr(oAcc.SmtpAddress) Like from Then
                Set .SendUsingAccount = oAcc
            End If
        Next oAcc
        If .SendUsingAccount Is Nothing Then Err.Raise -1, , "Unknown email account " & from
        For Each addr In recipients
            With .recipients.Add(addr)
                'This will resolve the recipient as if you had typed the name/email and pressed Tab/Enter
                .Resolve
            End With
        Next addr
        .subject = subject
        .Display 'HTMLBody is only populated after this line
        'Remove blank lines at the top of the body
        .htmlBody = Replace(.htmlBody, "<o:p>&nbsp;</o:p>", "")
        'Insert the html at the start of the 'body' tag
        Dim bodyTagEnd As Long: bodyTagEnd = InStr(InStr(1, .htmlBody, "<body"), .htmlBody, ">")
        .htmlBody = Left(.htmlBody, bodyTagEnd) & htmlBody & Right(.htmlBody, Len(.htmlBody) - bodyTagEnd)
    End With
    Set oApp = Nothing
End Sub

Use as follows:

CreateMail from:="*@contoso.com", _
    recipients:= Array("[email protected]", "Jane Doe", "[email protected]"), _
    subject:= "Test Email", _
    htmlBody:= "<p>Good Day All</p><p>Hello <b>World!</b></p>"

Result:

Sample Outlook Email

C++ queue - simple example

std::queue<myclass*> my_queue; will do the job.

See here for more information on this container.

How to configure WAMP (localhost) to send email using Gmail?

I've answered that here: (WAMP/XAMP) send Mail using SMTP localhost (works not only GMAIL, but for others too).

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.

If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).

It's probably not a concern in your case, since you have a single variate.

Some references:

  1. How high, R-squared?
  2. Goodness of fit statistics
  3. Multiple regression
  4. Re: What is "Adjusted R^2" in Multiple Regression

how to overwrite css style

You can create one more class naming

.flex-control-thumbs-without-width li {
width: auto;
float: initial; or none
}

Add this class whenever you need to override like below,

<li class="flex-control-thumbs flex-control-thumbs-without-width"> </li>

And do remove whenever you don't need for other <li>

batch script - read line by line

Try this:

@echo off
for /f "tokens=*" %%a in (input.txt) do (
  echo line=%%a
)
pause

because of the tokens=* everything is captured into %a

edit: to reply to your comment, you would have to do that this way:

@echo off
for /f "tokens=*" %%a in (input.txt) do call :processline %%a

pause
goto :eof

:processline
echo line=%*

goto :eof

:eof

Because of the spaces, you can't use %1, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a" in combination with %~1. So you need to use %* which gets %1 %2 %3 ..., so the whole line.

Add inline style using Javascript

You can try with this

nFilter.style.cssText = 'width:330px;float:left;';

That should do it for you.

Where does Vagrant download its .box files to?

On Windows, the location can be found here. I didn't find any documentation on the internet for this, and this wasn't immediately obvious to me:

C:\Users\\{username}\\.vagrant.d\boxes

Oracle SQL Developer: Unable to find a JVM

This is known to happen even if there are some syntactical errors in your heap space setting in the sqldeveloper.conf. If you have defined the heap space in any of the wrong ways mentioned here, it still will show the same error when you launch it.

EDIT : The correct way to set your heap size parameters would be something like this:

AddVMOption -XX:MaxPermSize=256M
AddVMOption -Xms256M
AddVMOption -Xmx768M

Squash the first two commits in Git?

This will squash second commit into the first one:

A-B-C-... -> AB-C-...

git filter-branch --commit-filter '
    if [ "$GIT_COMMIT" = <sha1ofA> ];
    then
        skip_commit "$@";
    else
        git commit-tree "$@";
    fi
' HEAD

Commit message for AB will be taken from B (although I'd prefer from A).

Has the same effect as Uwe Kleine-König's answer, but works for non-initial A as well.

Show loading image while $.ajax is performed

You can, of course, show it before making the request, and hide it after it completes:

$('#loading-image').show();
$.ajax({
      url: uri,
      cache: false,
      success: function(html){
        $('.info').append(html);
      },
      complete: function(){
        $('#loading-image').hide();
      }
    });

I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:

$('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});

Static variable inside of a function in C

There are two issues here, lifetime and scope.

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().