Programs & Examples On #Squishit

SquishIt is a free library to compress and minify CSS and JavaScript dynamically in ASP.NET and ASP.NET MVC

How can I search for a multiline pattern in a file?

Using ex/vi editor and globstar option (syntax similar to awk and sed):

ex +"/string1/,/string3/p" -R -scq! file.txt

where aaa is your starting point, and bbb is your ending text.

To search recursively, try:

ex +"/aaa/,/bbb/p" -scq! **/*.py

Note: To enable ** syntax, run shopt -s globstar (Bash 4 or zsh).

Android SeekBar setOnSeekBarChangeListener

All answers are correct, but you need to convert a long big fat number into a timer first:

    public String toTimer(long milliseconds){
    String finalTimerString = "";
    String secondsString;
    // Convert total duration into time
    int hours = (int)( milliseconds / (1000*60*60));
    int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
    int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
    // Add hours if there
    if(hours > 0){
        finalTimerString = hours + ":";
    }
    // Prepending 0 to seconds if it is one digit
    if(seconds < 10){
        secondsString = "0" + seconds;
    }else{
        secondsString = "" + seconds;}
    finalTimerString = finalTimerString + minutes + ":" + secondsString;
    // return timer string
    return finalTimerString;
}

And this is how you use it:

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));        
}

Launching Spring application Address already in use

I would suggest to kill the port number. It worked for me

netstat -ano | findstr :yourPortNumber taskkill /PID typeyourPIDhere /F

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

Finding rows containing a value (or values) in any column

If you want to find the rows that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)), create a logical index of (TRUE/FALSE) with (==). Use Reduce and OR (|) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums), double negate (!!) to get the rows with any matches.

indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)

Or vectorise and get the row indices with which with arr.ind=TRUE

indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),
                                     arr.ind=TRUE)[,1])

Benchmarks

I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500 matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased

val <- paste0('M0', 1:1000)
set.seed(24)
df1 <- as.data.frame(matrix(sample(c(val, NA), 1000*500, 
  replace=TRUE), ncol=500), stringsAsFactors=FALSE) 
set.seed(356)
v1 <- sample(val, 200, replace=FALSE)

 konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
 akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
               na.rm=TRUE)}
 akrun2 <- function() {unique(which(Vectorize(function(x) x %in% 
              v1)(df1),arr.ind=TRUE)[,1])}


 library(microbenchmark)
 microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
 #Unit: relative
 #   expr       min         lq       mean     median         uq      max   neval
 # konvas()   1.00000   1.000000   1.000000   1.000000   1.000000  1.00000    20
 # akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737    20
 # akrun2()   5.85611   5.641451   4.676836   5.330067   5.269937  2.22255    20
 # cld
 #  a 
 #  b
 #  a 

For ncol = 10, the results are slighjtly different:

expr       min        lq     mean    median        uq       max    neval
 konvas()  3.116722  3.081584  2.90660  2.983618  2.998343  2.394908    20
 akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376    20
 akrun2()  1.000000  1.000000  1.00000  1.000000  1.000000  1.000000    20

data

 v1 <- c('M017', 'M018')
 df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53", 
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07", 
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23", 
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>", 
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2", 
"col3", "col4"), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10", "11"))

How can I introduce multiple conditions in LIKE operator?

This might help:

select * from tbl where col like '[ABC-XYZ-PQR]%'

I've used this in SQL Server 2005 and it worked.

In PHP, what is a closure and why does it use the "use" identifier?

Until very recent years, PHP has defined its AST and PHP interpreter has isolated the parser from the evaluation part. During the time when the closure is introduced, PHP's parser is highly coupled with the evaluation.

Therefore when the closure was firstly introduced to PHP, the interpreter has no method to know which which variables will be used in the closure, because it is not parsed yet. So user has to pleased the zend engine by explicit import, doing the homework that zend should do.

This is the so-called simple way in PHP.

jQuery textbox change event doesn't fire until textbox loses focus?

Try the below Code:

$("#textbox").on('change keypress paste', function() {
  console.log("Handler for .keypress() called.");
});

@class vs. #import

If you see this warning:

warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist

you need to #import the file, but you can do that in your implementation file (.m), and use the @class declaration in your header file.

@class does not (usually) remove the need to #import files, it just moves the requirement down closer to where the information is useful.

For Example

If you say @class MyCoolClass, the compiler knows that it may see something like:

MyCoolClass *myObject;

It doesn't have to worry about anything other than MyCoolClass is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class suffices 90% of the time.

However, if you ever need to create or access myObject's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "MyCoolClass.h", to tell the compiler additional information beyond just "this is a class".

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Getting msbuild.exe without installing Visual Studio

The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.

What is the way of declaring an array in JavaScript?

The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:

function Array() { return []; }

alert(Array(1, 2, 3)); // An empty alert box

However, the larger issue is that of consistency. Someone refactoring code could come across this function:

function fetchValue(n) {
    var arr = new Array(1, 2, 3);

    return arr[n];
}

As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:

var arr = new Array(1);

Evaluate list.contains string in JSTL

I found this solution amazing.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
   ArrayList list = new ArrayList();
   list.add("one");
   list.add("two");
   list.add("three");
%>
<c:set var="list" value="<%=list%>" />
<html>
<body>
        My list is ${list}<br/>
<c:if test='${fn:contains(list, "two")}'>
        My list contains two <br/>
</c:if>
<c:if test='${fn:contains(list, ",")}'>
        My list contains , 
</c:if>
</body>
</html>

The output for the code above is

My list is [one, two, three]

My list contains two

My list contains ,

I hope it helps someone.

CRON command to run URL address every 5 minutes

I try GET 'http://example.com/?var=value' Important use ' add >/dev/null 2>&1 for not send email when this activate Sorry for my English

How to check if PHP array is associative or sequential?

This is my function -

public function is_assoc_array($array){

    if(is_array($array) !== true){
        return false;
    }else{

        $check = json_decode(json_encode($array));

        if(is_object($check) === true){
            return true;
        }else{
            return false;
        }

    }

}

Some examples

    print_r((is_assoc_array(['one','two','three']))===true?'Yes':'No'); \\No
    print_r(is_assoc_array(['one'=>'one','two'=>'two','three'=>'three'])?'Yes':'No'); \\Yes
    print_r(is_assoc_array(['1'=>'one','2'=>'two','3'=>'three'])?'Yes':'No'); \\Yes
    print_r(is_assoc_array(['0'=>'one','1'=>'two','2'=>'three'])?'Yes':'No'); \\No

There was a similar solution by @devios1 in one of the answers but this was just another way using the inbuilt json related functions of PHP. I haven't checked how this solution fairs in terms of performance compared to other solutions that have been posted here. But it certainly has helped me solve this problem. Hope this helps.

finding the type of an element using jQuery

It is worth noting that @Marius's second answer could be used as pure Javascript solution.

document.getElementById('elementId').tagName

How to PUT a json object with an array using curl

Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.

curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
     http://example.com/service

Using the exact JSON data from the question, the full command line would become:

curl -H 'Content-Type: application/json' -X PUT \
    -d '{"tags":["tag1","tag2"],
         "question":"Which band?",
         "answers":[{"id":"a0","answer":"Answer1"},
                    {"id":"a1","answer":"answer2"}]}' \
    http://example.com/service

Note: JSON data wrapped only for readability, not valid for curl request.

What is "android.R.layout.simple_list_item_1"?

As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
enter image description here

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

The utf8mb4 character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.

A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.

Thin Black Border for a Table

Style the td and th instead

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

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

table {
    border-collapse: collapse;
}

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

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

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

How to convert string to XML using C#

xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>                    
                    </body></head>");

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

Content is not allowed in Prolog SAXParserException

Check the XML. It is not a valid xml.

Prolog is the first line with xml version info. It ok not to include it in your xml.

This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.

e.g.

  1. Root/><document>
  2. Root<document>

QED symbol in latex

\rule{1.2ex}{1.2ex} will give you a filled box.

\fbox{\phantom{\rule{.7ex}{.7ex}}} will give you an empty box. The \phantom command will typeset with invisible ink.

The advantage of this approach is that no package is needed. Also the size is up to your control. Less is more.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.

Multiple inputs on one line

Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to:

cin >> a;
cin >> b;
cin >> c;

This is due to a technique called "operator chaining".

Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument. So cin >> a returns cin, which can be used as (cin>>a)>>b and so forth.

Note that each call to operator>>(istream&, T) first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

Write values in app.config file

Try the following code:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add("YourKey", "YourValue");
    config.Save(ConfigurationSaveMode.Minimal);

It worked for me :-)

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How to give the background-image path in CSS?

You need to get 2 folders back from your css file.

Try:

background-image: url("../../images/image.png");

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

Create a folder if it doesn't already exist

You first need to check if directory exists file_exists('path_to_directory')

Then use mkdir(path_to_directory) to create a directory

mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool

More about mkdir() here

Full code here:

$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
    mkdir($structure);
}

jQuery to remove an option from drop down list, given option's text/value

Once you have localized the dropdown element

dropdownElement = $("#dropdownElement");

Find the <option> element using the JQuery attribute selector

dropdownElement.find('option[value=foo]').remove();

How to edit incorrect commit message in Mercurial?

I did it this way. Firstly, don't push your changes or you are out of luck. Grab and install the collapse extension. Commit another dummy changeset. Then use collapse to combine the previous two changesets into one. It will prompt you for a new commit message, giving you the messages that you already have as a starting point. You have effectively changed your original commit message.

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

Alter MySQL table to add comments on columns

Script for all fields on database:

SELECT 
table_name,
column_name,
CONCAT('ALTER TABLE `',
        TABLE_SCHEMA,
        '`.`',
        table_name,
        '` CHANGE `',
        column_name,
        '` `',
        column_name,
        '` ',
        column_type,
        ' ',
        IF(is_nullable = 'YES', '' , 'NOT NULL '),
        IF(column_default IS NOT NULL, concat('DEFAULT ', IF(column_default IN ('CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP()', 'NULL', 'b\'0\'', 'b\'1\''), column_default, CONCAT('\'',column_default,'\'') ), ' '), ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '' AND column_type = 'timestamp','NULL ', ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '','DEFAULT NULL ', ''),
        extra,
        ' COMMENT \'',
        column_comment,
        '\' ;') as script
FROM
    information_schema.columns
WHERE
    table_schema = 'my_database_name'
ORDER BY table_name , column_name
  1. Export all to a CSV
  2. Open it on your favorite csv editor

Note: You can improve to only one table if you prefer

The solution given by @Rufinus is great but if you have auto increments it will break it.

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

How to get first N number of elements from an array

Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.

In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like

var items = list
             .filter((i, index) => (index < 3))
             .map((i, index) => {
                   return (
                     <myview item={i} key={i.id} />
                   );
              });

What's the best way to validate an XML file against an XSD file?

Using Woodstox, configure the StAX parser to validate against your schema and parse the XML.

If exceptions are caught the XML is not valid, otherwise it is valid:

// create the XSD schema from your schema file
XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
XMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);

// create the XML reader for your XML file
WstxInputFactory inputFactory = new WstxInputFactory();
XMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);

try {
    // configure the reader to validate against the schema
    xmlReader.validateAgainst(validationSchema);

    // parse the XML
    while (xmlReader.hasNext()) {
        xmlReader.next();
    }

    // no exceptions, the XML is valid

} catch (XMLStreamException e) {

    // exceptions, the XML is not valid

} finally {
    xmlReader.close();
}

Note: If you need to validate multiple files, you should try to reuse your XMLInputFactory and XMLValidationSchema in order to maximize the performance.

Find the paths between two given nodes?

The original code is a bit cumbersome and you might want to use the collections.deque instead if you want to use BFS to find if a path exists between 2 points on the graph. Here is a quick solution I hacked up:

Note: this method might continue infinitely if there exists no path between the two nodes. I haven't tested all cases, YMMV.

from collections import deque

# a sample graph
  graph = {'A': ['B', 'C','E'],
           'B': ['A','C', 'D'],
           'C': ['D'],
           'D': ['C'],
           'E': ['F','D'],
           'F': ['C']}

   def BFS(start, end):
    """ Method to determine if a pair of vertices are connected using BFS

    Args:
      start, end: vertices for the traversal.

    Returns:
      [start, v1, v2, ... end]
    """
    path = []
    q = deque()
    q.append(start)
    while len(q):
      tmp_vertex = q.popleft()
      if tmp_vertex not in path:
        path.append(tmp_vertex)

      if tmp_vertex == end:
        return path

      for vertex in graph[tmp_vertex]:
        if vertex not in path:
          q.append(vertex)

How do I delete an item or object from an array using ng-click?

I usually write in such style :

<a class="btn" ng-click="remove($index)">Delete</a>


$scope.remove = function(index){
  $scope.[yourArray].splice(index, 1)
};

Hope this will help You have to use a dot(.) between $scope and [yourArray]

Using custom fonts using CSS?

Today there are four font container formats in use on the web: EOT, TTF, WOFF,andWOFF2.

Unfortunately, despite the wide range of choices, there isn't a single universal format that works across all old and new browsers:

  • EOT is IE only,
  • TTF has partial IE support,
  • WOFF enjoys the widest support but is not available in some older browsers
  • WOFF 2.0 support is a work in progress for many browsers.

If you want your web app to have the same font across all browsers then you might want to provide all 4 font type in CSS

 @font-face {
      font-family: 'besom'; !important
      src: url('fonts/besom/besom.eot');
      src: url('fonts/besom/besom.eot?#iefix') format('embedded-opentype'),
           url('fonts/besom/besom.woff2') format('woff2'),
           url('fonts/besom/besom.woff') format('woff'),
           url('fonts/besom/besom.ttf') format('truetype'),
           url('fonts/besom/besom.svg#besom_2regular') format('svg');
      font-weight: normal;
      font-style: normal;
  }

How to change the height of a div dynamically based on another div using css?

In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...

function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}

You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/

time delayed redirect?

Include this code somewhere when you slide to your 'section' called blog.

$("#myLink").click(function() {
    setTimeout(function() {
        window.navigate("the url of the page you want to navigate back to");
    }, 2000);
});

Where myLink is the id of your href.

Swift GET request with parameters

When building a GET request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents.

var url = URLComponents(string: "https://www.google.com/search/")!

url.queryItems = [
    URLQueryItem(name: "q", value: "War & Peace")
]

The only trick is that most web services need + character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded specification). But URLComponents will not percent escape it. Apple contends that + is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded requests and really should not be passed unescaped.

Apple acknowledges that we have to percent escaping the + characters, but advises that we do it manually:

var url = URLComponents(string: "https://www.wolframalpha.com/input/")!

url.queryItems = [
    URLQueryItem(name: "i", value: "1+2")
]

url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")

This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a + character and you have a server that interprets them as spaces.

So, combining that with your sendRequest routine, you end up with something like:

func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
    var components = URLComponents(string: url)!
    components.queryItems = parameters.map { (key, value) in 
        URLQueryItem(name: key, value: value) 
    }
    components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
    let request = URLRequest(url: components.url!)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data,                            // is there data
            let response = response as? HTTPURLResponse,  // is there HTTP response
            (200 ..< 300) ~= response.statusCode,         // is statusCode 2XX
            error == nil else {                           // was there no error, otherwise ...
                completion(nil, error)
                return
        }

        let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
        completion(responseObject, nil)
    }
    task.resume()
}

And you'd call it like:

sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
    guard let responseObject = responseObject, error == nil else {
        print(error ?? "Unknown error")
        return
    }

    // use `responseObject` here
}

Personally, I'd use JSONDecoder nowadays and return a custom struct rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.


See previous revision of this answer for Swift 2 and manual percent escaping renditions.

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

This Activity already has an action bar supplied by the window decor

Or Simply change the @Style/AppTheme

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">

This works for me!

How do I change the root directory of an Apache server?

This is for Ubunutu 14.04:

In file /etc/apache2/apache2.conf it should be as below without the directory name:

<Directory /home/username>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

And in file /etc/apache2/sites-available/000-default.conf you should include the custom directory name, i.e., www:

DocumentRoot /home/username/www

If it is not as above, it will give you an error when loading the server:

Forbidden You don't have permission to access / on this server

WARNING: Exception encountered during context initialization - cancelling refresh attempt

This was my stupidity, but a stupidity that was not easy to identify :).

Problem:

  1. My code is compiled on Jdk 1.8.
  2. My eclipse, had JDK 1.8 as the compiler.
  3. My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.
  4. To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
    1. Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.

If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

How can I get session id in php and show it?

You have uniqid function for unique id

You can add prefix to make it more unique

Source : http://pk1.php.net/uniqid

Auto-fit TextView for Android

Try this

TextWatcher changeText = new TextWatcher() {
     @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv3.setText(et.getText().toString());
                tv3.post(new Runnable() {           
                    @Override
                    public void run() {
                    while(tv3.getLineCount() >= 3){                     
                            tv3.setTextSize((tv3.getTextSize())-1);                     
                        }
                    }
                });
            }

            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override public void afterTextChanged(Editable s) { }
        };

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

How can I get the source code of a Python function?

To expand on runeh's answer:

>>> def foo(a):
...    x = 2
...    return x + a

>>> import inspect

>>> inspect.getsource(foo)
u'def foo(a):\n    x = 2\n    return x + a\n'

print inspect.getsource(foo)
def foo(a):
   x = 2
   return x + a

EDIT: As pointed out by @0sh this example works using ipython but not plain python. It should be fine in both, however, when importing code from source files.

Having trouble setting working directory

Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!

Hot to get all form elements values using jQuery?

I needed to get the form data as some sort of object. I used this:

$('#preview_form').serializeArray().reduce((function(acc, val) {
  acc[val.name.replace('[', '_').replace(']', '')] = val.value;
  return acc;
}), {});

Accessing the logged-in user in a template

For symfony 2.6 and above we can use

{{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

phpinfo() is not working on my CentOS server

It may not work for you if you use localhost/info.php.

You may be able to found the clue from the error. Find the port number in the error message. To me it was 80. I changed address as http://localhost:80/info.php, and then it worked to me.

Automatic exit from Bash shell script on error

Use it in conjunction with pipefail.

set -e
set -o pipefail

-e (errexit): Abort the script at the first error, when a command exits with non-zero status (except in until or while loops, if-tests, and list constructs)

-o pipefail: Causes a pipeline to return the exit status of the last command in the pipe that returned a non-zero return value.

Chapter 33. Options

How do I check whether an array contains a string in TypeScript?

If your code is ES7 based (or upper versions):

channelArray.includes('three'); //will return true or false

If not, for example you are using IE with no babel transpile:

channelArray.indexOf('three') !== -1; //will return true or false

the indexOf method will return the position the element has into the array, because of that we use !== different from -1 if the needle is found at the first position.

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

Im my browser, this doesn't work at all. The tooltip field doesn't show a link, but <a href='#' onClick='alert('Hello World!')>The Link</a>. I'm using FF 3.6.12.

You'll have to do this by hand with JS and CSS. Begin here

Android video streaming example

Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

How to condense if/else into one line in Python?

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0

JSON array get length

Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.

How can I round a number in JavaScript? .toFixed() returns a string?

What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00 etc. so it has to be a string.

C++ Best way to get integer division and remainder

You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.

Height equal to dynamic width (CSS fluid layout)

It is possible without any Javascript :)

The HTML:

<div class='box'>
    <div class='content'>Aspect ratio of 1:1</div>
</div> 

The CSS:

.box {
    position: relative;
    width:    50%; /* desired width */
}

.box:before {
    content:     "";
    display:     block;
    padding-top: 100%; /* initial ratio of 1:1*/
}

.content {
    position: absolute;
    top:      0;
    left:     0;
    bottom:   0;
    right:    0;
}

/* Other ratios - just apply the desired class to the "box" element */
.ratio2_1:before{
    padding-top: 50%;
}
.ratio1_2:before{
    padding-top: 200%;
}
.ratio4_3:before{
    padding-top: 75%;
}
.ratio16_9:before{
    padding-top: 56.25%;
}

Finding the handle to a WPF window

you can use :

Process.GetCurrentProcess().MainWindowHandle

Check if a process is running or not on Windows with Python

Would you be happy with your Python command running another program to get the info?

If so, I'd suggest you have a look at PsList and all its options. For example, The following would tell you about any running iTunes process

PsList itunes

If you can work out how to interpret the results, this should hopefully get you going.

Edit:

When I'm not running iTunes, I get the following:

pslist v1.29 - Sysinternals PsList
Copyright (C) 2000-2009 Mark Russinovich
Sysinternals

Process information for CLARESPC:

Name                Pid Pri Thd  Hnd   Priv        CPU Time    Elapsed Time
iTunesHelper       3784   8  10  229   3164     0:00:00.046     3:41:05.053

With itunes running, I get this one extra line:

iTunes              928   8  24  813 106168     0:00:08.734     0:02:08.672

However, the following command prints out info only about the iTunes program itself, i.e. with the -e argument:

pslist -e itunes

Auto-indent spaces with C in vim?

I think the best answer is actually explained on the vim wikia:

http://vim.wikia.com/wiki/Indenting_source_code

Note that it advises against using "set autoindent." The best feature of all I find in this explanation is being able to set per-file settings, which is especially useful if you program in python and C++, for example, as you'd want 4 spaces for tabs in the former and 2 for spaces in the latter.

How to set min-font-size in CSS

It will work perfectly with 50px. Which will act as a static and thus as min-width.

font-size: calc(50px + 5vw);

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

Using jQuery to center a DIV on the screen

Edit:

If the question taught me anything, it's this: don't change something that already works :)

I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:

.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper    {#position:absolute; #top:50%;
            display:table-cell; vertical-align:middle;}
.content   {#position:relative; #top:-50%;
            margin:0 auto; width:200px; border:1px solid orange;}

Fiddle: http://jsfiddle.net/S9upd/4/

I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.

Original:

Looks like I'm late to the party!

There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:

.container {
    position:absolute;
    left: 50%;
    top: 50%;
    overflow:visible;
}
.content {
    position:relative;
    margin:-50% 50% 50% -50%;
}

Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/

Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.


Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:

<table class="super-centered"><tr><td>
    <div class="content">
        <p>I am centered like a boss!</p>
    </div>
</td></tr></table>

And than the content's position is fine-tuned with good old margin:0 auto;:

.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}?

Working fiddle as promised: http://jsfiddle.net/teDQ2/

How can you run a Java program without main method?

Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.

public class Hello {
  static {
    System.out.println("Hello, World!");
  }
}

Of course, you can run the program as java Hello and you will see the message; however, the command will also fail with a message stating:

Exception in thread "main" java.lang.NoSuchMethodError: main

[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0) immediately after printing the message.

As of JDK6 onward, you no longer see the message from the static initializer block; details here.

Concrete Javascript Regex for Accented Characters (Diacritics)

The easier way to accept all accents is this:

[A-zÀ-ú] // accepts lowercase and uppercase characters
[A-zÀ-ÿ] // as above but including letters with an umlaut (includes [ ] ^ \ × ÷)
[A-Za-zÀ-ÿ] // as above but not including [ ] ^ \
[A-Za-zÀ-ÖØ-öø-ÿ] // as above but not including [ ] ^ \ × ÷

See https://unicode-table.com/en/ for characters listed in numeric order.

Is it ok to scrape data from Google results?

Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..

SQL Server CASE .. WHEN .. IN statement

Thanks for the Answer I have modified the statements to look like below

SELECT
     AlarmEventTransactionTable.TxnID,
     CASE 
    WHEN DeviceID IN('7', '10', '62', '58', '60',
            '46', '48', '50', '137', '139',
             '141', '145', '164') THEN '01'
    WHEN DeviceID IN('8', '9', '63', '59', '61',
            '47', '49', '51', '138', '140',
            '142', '146', '165') THEN '02'
             ELSE 'NA' END AS clocking,
     AlarmEventTransactionTable.DateTimeOfTxn
FROM
     multiMAXTxn.dbo.AlarmEventTransactionTable

Java: How to check if object is null?

Edited Java 8 Solution:

final Drawable drawable = 
    Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
        .orElseGet(() -> getRandomDrawable());

You can declare drawable final in this case.

As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.

Best Practice for Forcing Garbage Collection in C#

One more thing, triggering GC Collect explicitly may NOT improve your program's performance. It is quite possible to make it worse.

The .NET GC is well designed and tuned to be adaptive, which means it can adjust GC0/1/2 threshold according to the "habit" of your program memory usage. So, it will be adapted to your program after some time running. Once you invoke GC.Collect explicitly, the thresholds will be reset! And the .NET has to spent time to adapt to your program's "habit" again.

My suggestion is always trust .NET GC. Any memory problem surfaces, check ".NET Memory" performance counter and diagnose my own code.

How to Update Date and Time of Raspberry Pi With out Internet

Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)

server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst

3. If you want to make sure that date and time update at startup run this python script in rpi,

import os

try:
    client = ntplib.NTPClient()
    response = client.request('xxx.xxx.xxx.xxx', version=4)
    print "===================================="
    print "Offset : "+str(response.offset)
    print "Version : "+str(response.version)
    print "Date Time : "+str(ctime(response.tx_time))
    print "Leap : "+str(ntplib.leap_to_text(response.leap))
    print "Root Delay : "+str(response.root_delay)
    print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
    os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
    print "===================================="
except:
    os.system("sudo date")
    print "NTP Server Down Date Time NOT Set At The Startup"
    pass

I found more info in raspberry pi forum.

How can I create a keystore?

This tutorial:

http://techdroid.kbeanie.com/2010/02/sign-your-android-applications-for.html

was very helpful for me the first time I had to create a keystore. It is simple but the instructions on developer.android.com are a little too brief.

The part I was unsure about was where to save and what name to give the keystore file.

I seems it doesn't matter where you put it just be sure to keep it safe and keep a number of backups. I just put it in my app directory

Name the file "something.keystore" where something can be whatever you want. I used app_name.keystore, where app_name was the name of my app.

The next part was what to name the alias. Again it doesn't seem to matter so again I just used the app_name again. Keep the passwords the same as you used before. Fill out the rest of the fields and you are done.

2D cross-platform game engine for Android and iOS?

Recently I used an AS3 engine: PushButton (now is dead, but it's still functional and you could use something else) to do this job. To make it works with Android and iOS, the project was compiled in AIR for both platforms and everything worked with no performance damage. Since Flash Builder is kinda expensive ($249), you could use FlashDevelop (there is some tutorials to compile in AIR with it).

Flash could be an option since is very easy to learn.

How to get current class name including package name in Java?

There is a class, Class, that can do this:

Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass();          // if you want to use the current class

System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());

If c represented the class MyClass in the package mypackage, the above code would print:

Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass

You can take this information and modify it for whatever you need, or go check the API for more information.

How do I setup the InternetExplorerDriver so it works

This is just to help somebody in future. When we initiate InternetExplorerDriver() instance in a java project it uses IEDriver.exe (downloaded by individuals) which tries to extract temporary files in user's TEMP folder when it's not in path then ur busted.

Safest way is to provide your own extract path as shown below

System.setProperty("webdriver.ie.driver.extractpath", "F:\\Study\\");
System.setProperty("webdriver.ie.driver", "F:\\Study\\IEDriverServer.exe");
System.setProperty("webdriver.ie.logfile", "F:\\Study\\IEDriverServer.log");
InternetExplorerDriver d = new InternetExplorerDriver();
d.get("http://www.google.com");
d.quit();

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

If your newline character is CRLF, that means it's a CHR(13) followed by CHR(10). If you REPLACE(input, CHR(10), '_'), that turns into CHR(13) followed by an underscore. Since CR on its own can be just as well rendered as a newline character, it'll appear to you as if an underscore has ben inserted after your newline, but actually only half of your newline has been replaced.

Use REPLACE(REPLACE(input, CHR(13)), CHR(10)) to replace all CR's and LF's.

What is the difference between java and core java?

Core Java:
It’s a general term used by Sun Microsystems to describe the standard version of Java (JSE). It’s the most basic version of Java which sets the foundation for all other editions of Java plus a set of related technologies such as CORBA, Java VM, etc. Core Java refers to a collection of libraries rather than just the programming language.

Java :
Java is hypothetically everywhere, thanks to its readability and simplicity. From mobile applications to websites, game consoles to datacenters, from mobile phones to the Internet, Java is everywhere. Millions of devices throughout the world use Java as a core programming language. Even all native Android apps come built-in with Java and several companies use Java as server-side scripting language for backend development.

How to create a simple map using JavaScript/JQuery

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);

Wordpress keeps redirecting to install-php after migration

It seems that in general, this happens when Wordpress doesn't find the site information in the expected places (tables) in the database. It thinks no site has been created yet, so it starts going through the installation process.

This situation means that:

  1. Wordpress WAS ABLE to connect to a database. If it didn't, it would say there was an error and refuse to install or do anything else

AND

  1. it didn't find the things it was looking for in the expected places in the database it connected to.

Just to be clear, both 1) and 2) are happening when you see this symptom.

Possible causes:

  • Wrong database. You're working on several projects and you copied and pasted wrong database name, database host, or table prefix to the wp-config file. So now, you're unwittingly destroying ANOTHER client's website while agonizing over why isn't THIS website working at all.

  • Wrong database prefix. You can put several Wordpress sites in one database by using different prefixes for each. Make sure the tables in the database have the same prefixes as you entered in your wp-config. So, if wp-config says: $table_prefix = 'wp_'; Check that the tables in your database are called "wp_options", etc. and not "WP_options", "mysite_options" or something like that.

  • The data in the database is corrupted. Maybe you messed up while importing the sql dump, you imported a truncated file, a file belonging to some other project, or whatever.

GCC dump preprocessor defines

The simple approach (gcc -dM -E - < /dev/null) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:

g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates

always fails, because it silently invokes the C-drivers (as if invoked by gcc). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C.

Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++ option to force the invocation of the C++ compiler (Credits for using the -x c++ options instead of an empty dummy file go to yuyichao, see below):

g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates

There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use

g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates

which finally yields

#define __cpp_alias_templates 200704

noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11.

Does it matter what extension is used for SQLite database files?

Emacs expects one of db, sqlite, sqlite2 or sqlite3 in the default configuration for sql-sqlite mode.

How to get all selected values of a multiple select box?

Check-it Out:

HTML:

<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server"  SelectionMode="Multiple" Width="100px">
    <asp:ListItem Text="Raj" Value="1"></asp:ListItem>
    <asp:ListItem Text="Karan" Value="2"></asp:ListItem>
    <asp:ListItem Text="Riya" Value="3"></asp:ListItem>
    <asp:ListItem Text="Aman" Value="4"></asp:ListItem>
    <asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>

JQUERY:

$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});

CLICK HERE TO SEE THE DEMO

How to use __doPostBack()

This is how I do it

    public void B_ODOC_OnClick(Object sender, EventArgs e)
    {
        string script="<script>__doPostBack(\'fileView$ctl01$OTHDOC\',\'{\"EventArgument\":\"OpenModal\",\"EncryptedData\":null}\');</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(),"JsOtherDocuments",script);               
    }

HTML5 Video // Completely Hide Controls

A simple solution is – just to ignore user interactions :-)

video {
  pointer-events: none;
}

Web API Put Request generates an Http 405 Method Not Allowed error

So, I checked Windows Features to make sure I didn't have this thing called WebDAV installed, and it said I didn't. Anyways, I went ahead and placed the following in my web.config (both front end and WebAPI, just to be sure), and it works now. I placed this inside <system.webServer>.

<modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule"/> <!-- add this -->
</modules>

Additionally, it is often required to add the following to web.config in the handlers. Thanks to Babak

<handlers>
    <remove name="WebDAV" />
    ...
</handlers>

Shortcut to create properties in Visual Studio?

In addition to Amra's answer, you can find other snippets by typing

Ctrl + K, Ctrl + X

Which is mapped to Edit.InsertSnippet in my Visual Studio and shows you the full list of snippets available.

Also remember that you can configure your own snippets by using the Snippets Manager, which is available in the Tools menu, Code Snippets Manager.... Basically you create a file *.snippet and use the Import button in the Code Snippets Manager to add it to Visual Studio. For a full tutorial you can go to the docs; Walkthrough: Create a code snippet.


In Visual Studio Code snippets are handled slightly different than in Visual Studio. You can access all snippets by typing Ctrl + Shift + P and type in snippet. Two options should be available, Insert Snippet and Preferences: Configure User Snippets.

The former inserts a snippet from your list of snippets (using the Language Mode which you can see in the status bar), and with the latter you can create your own snippets for any Language Mode.

If you know the shortname you can just type that and use Tab to expand the snippet. For inserting a C# property you have three snippets available, prop, propfull, and propg, for different purposes.

What is the default database path for MongoDB?

The default dbpath for mongodb is /data/db.

There is no default config file, so you will either need to specify this when starting mongod with:

 mongod --config /etc/mongodb.conf

.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.

Note: to check the dbpath and command-line options for a running mongod, connect via the mongo shell and run:

db.serverCmdLineOpts()

In particular, if a custom dbpath is set it will be the value of:

db.serverCmdLineOpts().parsed.dbpath           // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath   // MongoDB 2.6+

How to get data from database in javascript based on the value passed to the function

Try the following:

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

You don't have access to javascript variable names in SQL, you must pass the values to the Database.

Why use prefixes on member variables in C++ classes

Some responses focus on refactoring, rather than naming conventions, as the way to improve readability. I don't feel that one can replace the other.

I've known programmers who are uncomfortable with using local declarations; they prefer to place all the declarations at the top of a block (as in C), so they know where to find them. I've found that, where scoping allows for it, declaring variables where they're first used decreases the time that I spend glancing backwards to find the declarations. (This is true for me even for small functions.) That makes it easier for me to understand the code I'm looking at.

I hope it's clear enough how this relates to member naming conventions: When members are uniformly prefixed, I never have to look back at all; I know the declaration won't even be found in the source file.

I'm sure that I didn't start out preferring these styles. Yet over time, working in environments where they were used consistently, I optimized my thinking to take advantage of them. I think it's possible that many folks who currently feel uncomfortable with them would also come to prefer them, given consistent usage.

How to set .net Framework 4.5 version in IIS 7 application pool

There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:

appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5

Appcmd is located in %windir%\System32\inetsrv. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.

MS article on setting .Net version for App Pool

ReflectionException: Class ClassName does not exist - Laravel

Check your capitalization!

Your host system (Windows or Mac) is case insensitive by default, and Homestead inherits this behavior. Your production server on the other hand is case sensitive.

Whenever you get a ClassNotFound Exception check the following:

  1. Spelling
  2. Namespaces
  3. Capitalization

Calculate logarithm in python

From the documentation:

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

But the log10 is made available as math.log10(), which does not resort to log division if possible.

What are Unwind segues for and how do you use them?

In a Nutshell

An unwind segue (sometimes called exit segue) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. "go back" multiple steps in your navigation hierarchy with a single unwind action.

When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.

Objective-C:

- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
}

Swift:

@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
}

The name of this action method is used when you create the unwind segue in the storyboard. Furthermore, this method is called just before the unwind segue is performed. You can get the source view controller from the passed UIStoryboardSegue parameter to interact with the view controller that initiated the segue (e.g. to get the property values of a modal view controller). In this respect, the method has a similar function as the prepareForSegue: method of UIViewController.

iOS 8 update: Unwind segues also work with iOS 8's adaptive segues, such as Show and Show Detail.

An Example

Let us have a storyboard with a navigation controller and three child view controllers:

enter image description here

From Green View Controller you can unwind (navigate back) to Red View Controller. From Blue you can unwind to Green or to Red via Green. To enable unwinding you must add the special action methods to Red and Green, e.g. here is the action method in Red:

Objective-C:

@implementation RedViewController

- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
}

@end

Swift:

@IBAction func unwindToRed(segue: UIStoryboardSegue) {
}

After the action method has been added, you can define the unwind segue in the storyboard by control-dragging to the Exit icon. Here we want to unwind to Red from Green when the button is pressed:

enter image description here

You must select the action which is defined in the view controller you want to unwind to:

enter image description here

You can also unwind to Red from Blue (which is "two steps away" in the navigation stack). The key is selecting the correct unwind action.

Before the the unwind segue is performed, the action method is called. In the example I defined an unwind segue to Red from both Green and Blue. We can access the source of the unwind in the action method via the UIStoryboardSegue parameter:

Objective-C:

- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
    UIViewController* sourceViewController = unwindSegue.sourceViewController;

    if ([sourceViewController isKindOfClass:[BlueViewController class]])
    {
        NSLog(@"Coming from BLUE!");
    }
    else if ([sourceViewController isKindOfClass:[GreenViewController class]])
    {
        NSLog(@"Coming from GREEN!");
    }
}

Swift:

@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) {
    if let blueViewController = unwindSegue.sourceViewController as? BlueViewController {
        println("Coming from BLUE")
    }
    else if let redViewController = unwindSegue.sourceViewController as? RedViewController {
        println("Coming from RED")
    }
}

Unwinding also works through a combination of push/modal segues. E.g. if I added another Yellow view controller with a modal segue, we could unwind from Yellow all the way back to Red in a single step:

enter image description here

Unwinding from Code

When you define an unwind segue by control-dragging something to the Exit symbol of a view controller, a new segue appears in the Document Outline:

enter image description here

Selecting the segue and going to the Attributes Inspector reveals the "Identifier" property. Use this to give a unique identifier to your segue:

enter image description here

After this, the unwind segue can be performed from code just like any other segue:

Objective-C:

[self performSegueWithIdentifier:@"UnwindToRedSegueID" sender:self];

Swift:

performSegueWithIdentifier("UnwindToRedSegueID", sender: self)

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

Including jars in classpath on commandline (javac or apt)

Using:

apt HelloImpl.java -classpath /sac/tools/thirdparty/jaxws-ri/jaxws-ri-2.1.4/lib/jsr181-api.jar:.

works but it gives me another error, see new question

Cannot get a text value from a numeric cell “Poi”

This is one of the other method to solve the Error: "Cannot get a text value from a numeric cell “Poi”"

Go to the Excel Sheet. Drag and Select the Numerics which you are importing Data from the Excel sheet. Go to Format > Number > Then Select "Plain Text" Then Export as .xlsx. Now Try to Run the Script

Hope works Fine...!

Cannot get a text value from a numeric cell “Poi”.img

Get last 30 day records from today date in SQL Server

I dont know why all these complicated answers are on here but this is what I would do

where pdate >= CURRENT_TIMESTAMP -30

OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30

<img>: Unsafe value used in a resource URL context

Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.

I have created the pipe SanitizeUrlPipe for this

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustResourceUrl(v);
    }
}

and this is how you can use

<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>

If you want to add HTML, then SanitizeHtmlPipe can help

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustHtml(v);
    }
}

Read more about angular security here.

How to show full column content in a Spark Dataframe?

In c# Option("truncate", false) does not truncate data in the output.

StreamingQuery query = spark
                    .Sql("SELECT * FROM Messages")
                    .WriteStream()
                    .OutputMode("append")
                    .Format("console")
                    .Option("truncate", false)
                    .Start();

Word wrap for a label in Windows Forms

The quick answer: switch off AutoSize.

The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.

Basically what you need to do in OnPaint is:

  1. Measure the height of the text (Graphics.MeasureString).
  2. If the label height is not equal to the height of the text set the height and return.
  3. Draw the text.

You will also need to set the ResizeRedraw style flag in the constructor.

Dynamically add event listener

Renderer has been deprecated in Angular 4.0.0-rc.1, read the update below

The angular2 way is to use listen or listenGlobal from Renderer

For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement)

constructor(elementRef: ElementRef, renderer: Renderer) {

    // Listen to click events in the component
    renderer.listen(elementRef.nativeElement, 'click', (event) => {
      // Do something with 'event'
    })
);

You can use listenGlobal that will give you access to document, body, etc.

renderer.listenGlobal('document', 'click', (event) => {
  // Do something with 'event'
});

Note that since beta.2 both listen and listenGlobal return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).

So to remove the listener we added dynamically we must assign listen or listenGlobal to a variable that will hold the function returned, and then we execute it.

// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;

// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;

constructor(elementRef: ElementRef, renderer: Renderer) {
    
    // We cache the function "listen" returns
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
        // Do something with 'event'
    });
}

ngOnDestroy() {
    // We execute both functions to remove the respectives listeners

    // Removes "listen" listener
    this.listenFunc();
    
    // Removs "listenGlobal" listener
    this.globalListenFunc();
}

Here's a plnkr with an example working. The example contains the usage of listen and listenGlobal.

Using RendererV2 with Angular 4.0.0-rc.1+ (Renderer2 since 4.0.0-rc.3)

  • 25/02/2017: Renderer has been deprecated, now we should use RendererV2 (see line below). See the commit.

  • 10/03/2017: RendererV2 was renamed to Renderer2. See the breaking changes.

RendererV2 has no more listenGlobal function for global events (document, body, window). It only has a listen function which achieves both functionalities.

For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).

listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
      () => void {
    if (typeof target === 'string') {
      return <() => void>this.eventManager.addGlobalEventListener(
          target, event, decoratePreventDefault(callback));
    }
    return <() => void>this.eventManager.addEventListener(
               target, event, decoratePreventDefault(callback)) as() => void;
  }

As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener

To remove the listener it's the same as it was with Renderer in angular 2.x. listen returns a function, then call that function.

Example

// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
  console.log('Clicking the document', evt);
})

let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
  console.log('Clicking the button', evt);
});

// Remove listeners
global();
simple();

plnkr with Angular 4.0.0-rc.1 using RendererV2

plnkr with Angular 4.0.0-rc.3 using Renderer2

CSS transition when class removed

The @jfriend00's answer helps me to understand the technique to animate only remove class (not add).

A "base" class should have transition property (like transition: 2s linear all;). This enables animations when any other class is added or removed on this element. But to disable animation when other class is added (and only animate class removing) we need to add transition: none; to the second class.

Example

CSS:

.issue {
  background-color: lightblue;
  transition: 2s linear all;
}

.recently-updated {
  background-color: yellow;
  transition: none;
}

HTML:

<div class="issue" onclick="addClass()">click me</div>

JS (only needed to add class):

var timeout = null;

function addClass() {
  $('.issue').addClass('recently-updated');
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  timeout = setTimeout(function () {
    $('.issue').removeClass('recently-updated');
  }, 1000);
}

plunker of this example.

With this code only removing of recently-updated class will be animated.

UTF-8 text is garbled when form is posted as multipart/form-data

I had the same problem. The only solution that worked for me was adding <property = "defaultEncoding" value = "UTF-8"> to multipartResoler in spring configurations file.

Run ssh and immediately execute command

ssh -t 'command; bash -l'

will execute the command and then start up a login shell when it completes. For example:

ssh -t [email protected] 'cd /some/path; bash -l'

TypeError: expected string or buffer

'lines' term from your snippet consists of set of strings.

 lines = f.readlines()
 match = re.findall('[A-Z]+', lines)

You cannot send entire lines into the re.findall('pattern',<string>)

You can try to send line by line

 for i in lines:
  match = re.findall('[A-Z]+', i)
  print match

or to convert the entire lines collection into single line (each line seperated by space)

 NEW_LIST=' '.join(lines)
 match=re.findall('[A-Z]+' ,NEW_LIST)
 print match

This might help you

Convert JSON String To C# Object

Or, you can use the Newtownsoft.Json library as follows:

using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);

Where T is your object type that matches your JSON string.

How to execute python file in linux

Add this at the top of your file:

#!/usr/bin/python

This is a shebang. You can read more about it on Wikipedia.

After that, you must make the file executable via

chmod +x your_script.py

User Get-ADUser to list all properties and export to .csv

This can be simplified by completely skipping the where object and the $users declaration. All you need is:

Code

get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Here if you are referring to my previous answers Here is an Update. 1. Compile would be removed from the dependencies after 2018.

a new version build Gradle is available.

enter image description here

Use the above-noted stuff it will help you to resolve the errors. It is needed for the developers who are working after March 2018. Also, maven update might be needed. All above answers will not work on the Android Studio 3.1. Hence Above code block is needed to be changed if you are using 3.1. See also I replaced compile by implementation.

function to return a string in java

In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.

I would change to this, though. You don't need "ans" at all.

return String.format("%d:%d", mins, secs);

Create Log File in Powershell

Gist with log rotation: https://gist.github.com/barsv/85c93b599a763206f47aec150fb41ca0

Usage:

. .\logger.ps1
Write-Log "debug message"
Write-Log "info message" "INFO"

vagrant login as root by default

Adding this to the Vagrantfile worked for me. These lines are the equivalent of you entering sudo su - every time you login. Please notice that this requires reprovisioning the VM.

config.vm.provision "shell", inline: <<-SHELL
    echo "sudo su -" >> .bashrc
SHELL

Set a DateTime database field to "Now"

Use GETDATE()

Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

UPDATE table SET date = GETDATE()

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

I have tried to do aspnet_regiis in command prompt but I got answer that I don't have admin rights. Then, after some more googling and looking for a solution I tried to right click cmd and run it as an admin. Confirmed yes when dialog appeared, ran aspnet_iis again ant worked like a charm. In short: 1. check .NET framework in app_pool 2. run cmd as an admin 3. run aspnet_regiis -i

React Native fixed footer

Simple stuff here:

Incase you don't need a ScrollView for this approach you can go with the below code to achieve Something like this :

Something like this

<View style={{flex: 1, backgroundColor:'grey'}}>
    <View style={{flex: 1, backgroundColor: 'red'}} />
    <View style={{height: 100, backgroundColor: 'green'}} />
</View>

How to terminate a python subprocess launched with shell=True

As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:

if isinstance(command, unicode):
    cmd = command.encode('utf8')
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Then p.kill() and p.terminate() should work how you expect.

How can I remove the search bar and footer added by the jQuery DataTables plugin?

You can also not draw the header or footer at all by setting sDom: http://datatables.net/usage/options#sDom

'sDom': 't' 

will display JUST the table, no headers or footers or anything.

It's discussed some here: http://www.datatables.net/forums/discussion/2722/how-to-hide-empty-header-and-footer/p1

Improve SQL Server query performance on large tables

Simple Answer: NO. You cannot help ad hoc queries on a 238 column table with a 50% Fill Factor on the Clustered Index.

Detailed Answer:

As I have stated in other answers on this topic, Index design is both Art and Science and there are so many factors to consider that there are few, if any, hard and fast rules. You need to consider: the volume of DML operations vs SELECTs, disk subsystem, other indexes / triggers on the table, distribution of data within the table, are queries using SARGable WHERE conditions, and several other things that I can't even remember right now.

I can say that no help can be given for questions on this topic without an understanding of the Table itself, its indexes, triggers, etc. Now that you have posted the table definition (still waiting on the Indexes but the Table definition alone points to 99% of the issue) I can offer some suggestions.

First, if the table definition is accurate (238 columns, 50% Fill Factor) then you can pretty much ignore the rest of the answers / advice here ;-). Sorry to be less-than-political here, but seriously, it's a wild goose chase without knowing the specifics. And now that we see the table definition it becomes quite a bit clearer as to why a simple query would take so long, even when the test queries (Update #1) ran so quickly.

The main problem here (and in many poor-performance situations) is bad data modeling. 238 columns is not prohibited just like having 999 indexes is not prohibited, but it is also generally not very wise.

Recommendations:

  1. First, this table really needs to be remodeled. If this is a data warehouse table then maybe, but if not then these fields really need to be broken up into several tables which can all have the same PK. You would have a master record table and the child tables are just dependent info based on commonly associated attributes and the PK of those tables is the same as the PK of the master table and hence also FK to the master table. There will be a 1-to-1 relationship between master and all child tables.
  2. The use of ANSI_PADDING OFF is disturbing, not to mention inconsistent within the table due to the various column additions over time. Not sure if you can fix that now, but ideally you would always have ANSI_PADDING ON, or at the very least have the same setting across all ALTER TABLE statements.
  3. Consider creating 2 additional File Groups: Tables and Indexes. It is best not to put your stuff in PRIMARY as that is where SQL SERVER stores all of its data and meta-data about your objects. You create your Table and Clustered Index (as that is the data for the table) on [Tables] and all Non-Clustered indexes on [Indexes]
  4. Increase the Fill Factor from 50%. This low number is likely why your index space is larger than your data space. Doing an Index Rebuild will recreate the data pages with a max of 4k (out of the total 8k page size) used for your data so your table is spread out over a wide area.
  5. If most or all queries have "ER101_ORG_CODE" in the WHERE condition, then consider moving that to the leading column of the clustered index. Assuming that it is used more often than "ER101_ORD_NBR". If "ER101_ORD_NBR" is used more often then keep it. It just seems, assuming that the field names mean "OrganizationCode" and "OrderNumber", that "OrgCode" is a better grouping that might have multiple "OrderNumbers" within it.
  6. Minor point, but if "ER101_ORG_CODE" is always 2 characters, then use CHAR(2) instead of VARCHAR(2) as it will save a byte in the row header which tracks variable width sizes and adds up over millions of rows.
  7. As others here have mentioned, using SELECT * will hurt performance. Not only due to it requiring SQL Server to return all columns and hence be more likely to do a Clustered Index Scan regardless of your other indexes, but it also takes SQL Server time to go to the table definition and translate * into all of the column names. It should be slightly faster to specify all 238 column names in the SELECT list though that won't help the Scan issue. But do you ever really need all 238 columns at the same time anyway?

Good luck!

UPDATE
For the sake of completeness to the question "how to improve performance on a large table for ad-hoc queries", it should be noted that while it will not help for this specific case, IF someone is using SQL Server 2012 (or newer when that time comes) and IF the table is not being updated, then using Columnstore Indexes is an option. For more details on that new feature, look here: http://msdn.microsoft.com/en-us/library/gg492088.aspx (I believe these were made to be updateable starting in SQL Server 2014).

UPDATE 2
Additional considerations are:

  • Enable compression on the Clustered Index. This option became available in SQL Server 2008, but as an Enterprise Edition-only feature. However, as of SQL Server 2016 SP1, Data Compression was made available in all editions! Please see the MSDN page for Data Compression for details on Row and Page Compression.
  • If you cannot use Data Compression, or if it won't provide much benefit for a particular table, then IF you have a column of a fixed-length type (INT, BIGINT, TINYINT, SMALLINT, CHAR, NCHAR, BINARY, DATETIME, SMALLDATETIME, MONEY, etc) and well over 50% of the rows are NULL, then consider enabling the SPARSE option which became available in SQL Server 2008. Please see the MSDN page for Use Sparse Columns for details.

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

Is it possible to use an input value attribute as a CSS selector?

It is possible, if you're using a browser which supports the CSS :valid pseudo-class and the pattern validation attribute on inputs -- which includes most modern browsers except IE9.

For instance, to change the text of an input from black to green when the correct answer is entered:

_x000D_
_x000D_
input {_x000D_
  color: black;_x000D_
}_x000D_
input:valid {_x000D_
  color: green;_x000D_
}
_x000D_
<p>Which country has fifty states?</p>_x000D_
_x000D_
<input type="text" pattern="^United States$">
_x000D_
_x000D_
_x000D_

How do I echo and send console output to a file in a bat script?

Yes, there is a way to show a single command output on the console (screen) and in a file. Using your example, use...

@ECHO OFF
FOR /F "tokens=*" %%I IN ('DIR') DO ECHO %%I & ECHO %%I>>windows-dir.txt

Detailed explanation:

The FOR command parses the output of a command or text into a variable, which can be referenced multiple times.

For a command, such as DIR /B, enclose in single quotes as shown in example below. Replace the DIR /B text with your desired command.

FOR /F "tokens=*" %%I IN ('DIR /B') DO ECHO %%I & ECHO %%I>>FILE.TXT

For displaying text, enclose text in double quotes as shown in example below.

FOR /F "tokens=*" %%I IN ("Find this text on console (screen) and in file") DO ECHO %%I & ECHO %%I>>FILE.TXT

... And with line wrapping...

FOR /F "tokens=*" %%I IN ("Find this text on console (screen) and in file") DO (
  ECHO %%I & ECHO %%I>>FILE.TXT
)

If you have times when you want the output only on console (screen), and other times sent only to file, and other times sent to both, specify the "DO" clause of the FOR loop using a variable, as shown below with %TOECHOWHERE%.

@ECHO OFF
FOR %%I IN (TRUE FALSE) DO (
  FOR %%J IN (TRUE FALSE) DO (
    SET TOSCREEN=%%I & SET TOFILE=%%J & CALL :Runit)
)
GOTO :Finish

:Runit
  REM Both TOSCREEN and TOFILE get assigned a trailing space in the FOR loops
  REM above when the FOR loops are evaluating the first item in the list,
  REM "TRUE".  So, the first value of TOSCREEN is "TRUE " (with a trailing
  REM space), the second value is "FALSE" (no trailing or leading space).
  REM Adding the ": =" text after "TOSCREEN" tells the command processor to
  REM remove all spaces from the value in the "TOSCREEN" variable.
  IF "%TOSCREEN: =%"=="TRUE" (
      IF "%TOFILE: =%"=="TRUE" (
          SET TEXT=On screen, and in "FILE.TXT"
          SET TOECHOWHERE="ECHO %%I & ECHO %%I>>FILE.TXT"
        ) ELSE (
          SET TEXT=On screen, not in "FILE.TXT"
          SET TOECHOWHERE="ECHO %%I"
      )
    ) ELSE (
      IF "%TOFILE: =%"=="TRUE" (
          SET TEXT=Not on screen, but in "FILE.TXT"
          SET TOECHOWHERE="ECHO %%I>>FILE.txt"
        ) ELSE (
          SET TEXT=Not on screen, nor in "FILE.TXT"
          SET TOECHOWHERE="ECHO %%I>NUL"
      )
  )
  FOR /F "tokens=*" %%I IN ("%TEXT%") DO %TOECHOWHERE:~1,-1%
GOTO :eof

:Finish
  ECHO Finished [this text to console (screen) only].
  PAUSE

UIScrollView Scrollable Content Size Ambiguity

Xcode 11+, Swift 5

If you are wondering why all of the answers does not work anymore, make sure that you have pinned the content view (the one you've put inside the scroll view) to Content Layout Guide of the scroll view and NOT to Frame Layout Guide.

Content view edges (leading, trailing, top, bottom) should not be pinned like leading on the image - to Frame Layout Guide

Not like this

but like this - to Content Layout Guide.

Select Content Layout Guide from dropdown

enter image description here

And then the most of the answers will work for you.

The most simple approach now is going like this:

  1. Put scroll view in the root view
  2. Pin all the sides of scroll view to the superview
  3. Take another UIView (will call it content view) and put it inside the scroll view
  4. Pin all the sides of the content view to scroll view's Content Layout Guide
  5. Pin the content view's width to be equal to scroll view's Frame Layout Guide
  6. Fix the content view height in any way you want (I used just constant height constraint in the example below)

Overall your structure in the simplest implementation will look like this

enter image description here

Clear input fields on form submit

Still using empty strings you can use:

document.getElementById("name").value = '';
document.getElementById("review").value = '';

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

It's really interesting case. Actually in your setup the following statement is true:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

This means that up to a constant multiplication factor your losses are equivalent. The weird behaviour that you are observing during a training phase might be an example of a following phenomenon:

  1. At the beginning the most frequent class is dominating the loss - so network is learning to predict mostly this class for every example.
  2. After it learnt the most frequent pattern it starts discriminating among less frequent classes. But when you are using adam - the learning rate has a much smaller value than it had at the beginning of training (it's because of the nature of this optimizer). It makes training slower and prevents your network from e.g. leaving a poor local minimum less possible.

That's why this constant factor might help in case of binary_crossentropy. After many epochs - the learning rate value is greater than in categorical_crossentropy case. I usually restart training (and learning phase) a few times when I notice such behaviour or/and adjusting a class weights using the following pattern:

class_weight = 1 / class_frequency

This makes loss from a less frequent classes balancing the influence of a dominant class loss at the beginning of a training and in a further part of an optimization process.

EDIT:

Actually - I checked that even though in case of maths:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

should hold - in case of keras it's not true, because keras is automatically normalizing all outputs to sum up to 1. This is the actual reason behind this weird behaviour as in case of multiclassification such normalization harms a training.

How to convert current date into string in java?

// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}

Taken from here

How can I declare a global variable in Angular 2 / Typescript?

Here is the simplest solution w/o Service nor Observer:

Put the global variables in a file an export them.

//
// ===== File globals.ts    
//
'use strict';

export const sep='/';
export const version: string="22.2.2";    

To use globals in another file use an import statement: import * as myGlobals from 'globals';

Example:

// 
// ===== File heroes.component.ts    
//
import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {HeroService} from './hero.service';
import {HeroDetailComponent} from './hero-detail.component';
import {Hero} from './hero';
import * as myGlobals from 'globals'; //<==== this one (**Updated**)

export class HeroesComponent implements OnInit {
    public heroes: Hero[];
    public selectedHero: Hero;
    // 
    //
    // Here we access the global var reference.
    //  
    public helloString: string="hello " + myGlobals.sep + " there";

         ...

        }
    }

Thanks @eric-martinez

show/hide a div on hover and hover out

Here are different method of doing this. And i found your code is even working fine.

Your code: http://jsfiddle.net/NKC2j/

Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/

Jquery fade toggle: http://jsfiddle.net/NKC2j/3/

Jquery slide toggle: http://jsfiddle.net/NKC2j/4/

And you can do this with CSS as answered by Sandeep

Read files from a Folder present in project

If you need to get all the files in the folder named 'Data', just code it as below

string[] Documents = System.IO.Directory.GetFiles("../../Data/");

Now the 'Documents' consists of array of complete object name of two text files in the 'Data' folder 'Data'.

Custom Card Shape Flutter SDK

When Card I always use RoundedRectangleBorder.

Card(
  color: Colors.grey[900],
  shape: RoundedRectangleBorder(
    side: BorderSide(color: Colors.white70, width: 1),
    borderRadius: BorderRadius.circular(10),
  ),
  margin: EdgeInsets.all(20.0),
  child: Container(
    child: Column(
        children: <Widget>[
        ListTile(
            title: Text(
            'example',
            style: TextStyle(fontSize: 18, color: Colors.white),
            ),
        ),
        ],
    ),
  ),
),

How to move table from one tablespace to another in oracle 11g

Try this to move your table (tbl1) to tablespace (tblspc2).

alter table tb11 move tablespace tblspc2;

Getting Java version at runtime

Here is the answer from @mvanle, converted to Scala: scala> val Array(javaVerPrefix, javaVerMajor, javaVerMinor, _, _) = System.getProperty("java.runtime.version").split("\\.|_|-b") javaVerPrefix: String = 1 javaVerMajor: String = 8 javaVerMinor: String = 0

How to get local server host and port in Spring Boot?

I used to declare the configuration in application.properties like this (you can use you own property file)

server.host = localhost
server.port = 8081

and in application you can get it easily by @Value("${server.host}") and @Value("${server.port}") as field level annotation.

or if in your case it is dynamic than you can get from system properties

Here is the example

@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")

For a better understanding of this annotation , see this example Multiple uses of @Value annotation

Should I add the Visual Studio .suo and .user files to source control?

Using Rational ClearCase the answer is no. Only the .sln & .*proj should be registered in source code control.

I can't answer for other vendors. If I recall correctly, these files are "user" specific options, your environment.

How to edit Docker container files from the host?

We can use another way to edit files inside working containers (this won't work if container is stoped).

Logic is to:
-)copy file from container to host
-)edit file on host using its host editor
-)copy file back to container

We can do all this steps manualy, but i have written simple bash script to make this easy by one call.

/bin/dmcedit:

#!/bin/sh
set -e

CONTAINER=$1
FILEPATH=$2
BASE=$(basename $FILEPATH)
DIR=$(dirname $FILEPATH)
TMPDIR=/tmp/m_docker_$(date +%s)/

mkdir $TMPDIR
cd $TMPDIR
docker cp $CONTAINER:$FILEPATH ./$DIR
mcedit ./$FILEPATH
docker cp ./$FILEPATH $CONTAINER:$FILEPATH
rm -rf $TMPDIR

echo 'END'
exit 1;

Usage example:

dmcedit CONTAINERNAME /path/to/file/in/container

The script is very easy, but it's working fine for me.

Any suggestions are appreciated.

How to create a unique index on a NULL column?

Pretty sure you can't do that, as it violates the purpose of uniques.

However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change' event by listening to a <form> element (not the input itself) and none of the answers here worked for me. I tried to do:

$(form).on('change change.dp dp.change changeDate' function () {...})

And nothing would fire. I ended up listening to the focus and blur events and setting a custom property before/after on the element itself:

// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {  
    $('input[bs-datepicker]').on('focus', function (e){
        e.currentTarget.focusValue = e.currentTarget.value;
    });        
    $('input[bs-datepicker]').on('blur', function (e){
        if (e.currentTarget.focusValue !== e.currentTarget.value) {
            var event = new Event('change', { bubbles: true });
            e.currentTarget.dispatchEvent(event);
        }
    });
})

This basically manually checks the value before and after the focus and blur and dispatches a new 'change' event. The { bubbles: true } bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if you'll need to wrap the listeners in a $timeout to make sure the digest happens first so all of your datepicker elements exist.

Hope this helps someone!

How to detect scroll direction

This one deserves an update - nowadays we have the wheel event :

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
$(window).on('wheel', function(e) {_x000D_
_x000D_
 var delta = e.originalEvent.deltaY;_x000D_
_x000D_
 if (delta > 0) $('body').text('down');_x000D_
 else $('body').text('up');_x000D_
_x000D_
 return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
  font-size: 22px;_x000D_
  text-align: center;_x000D_
  color: white;_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Support has been pretty good on modern browsers for quite a while already :

  • Chrome 31+
  • Firefox 17+
  • IE9+
  • Opera 18+
  • Safari 7+

https://developer.mozilla.org/en-US/docs/Web/Events/wheel

If deeper browser support is required, probably best to use mousewheel.js instead of messing about :

https://plugins.jquery.com/mousewheel/

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
$(window).mousewheel(function(turn, delta) {_x000D_
_x000D_
 if (delta > 0) $('body').text('up');_x000D_
 else $('body').text('down');_x000D_
_x000D_
 return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
  font-size: 22px;_x000D_
  text-align: center;_x000D_
  color: white;_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
_x000D_
_x000D_
_x000D_

how to define ssh private key for servers fetched by dynamic inventory in files

I'm using the following configuration:

#site.yml:
- name: Example play
  hosts: all
  remote_user: ansible
  become: yes
  become_method: sudo
  vars:
    ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"

AngularJS sorting rows by table header

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

The template:

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

The JavaScript code:

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

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

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

How do I show a running clock in Excel?

Found the code that I referred to in my comment above. To test it, do this:

  1. In Sheet1 change the cell height and width of say A1 as shown in the snapshot below.
  2. Format the cell by right clicking on it to show time format
  3. Add two buttons (form controls) on the worksheet and name them as shown in the snapshot
  4. Paste this code in a module
  5. Right click on the Start Timer button on the sheet and click on Assign Macros. Select StartTimer macro.
  6. Right click on the End Timer button on the sheet and click on Assign Macros. Select EndTimer macro.

Now click on Start Timer button and you will see the time getting updated in cell A1. To stop time updates, Click on End Timer button.

Code (TRIED AND TESTED)

Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long

Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long

'~~> Start Timer
Sub StartTimer()
    '~~ Set the timer for 1 second
    TimerSeconds = 1
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub

'~~> End Timer
Sub EndTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
End Sub

Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
    '~~> Update value in Sheet 1
    Sheet1.Range("A1").Value = Time
End Sub

SNAPSHOT

enter image description here

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

Changing the width of Bootstrap popover

One tested solution for Bootstrap 4 beta:

.popover {
        min-width: 30em !important;
    }

Together with the jQuery statement:

$('[data-toggle="popover"]').popover({
      container: 'body',
      trigger: 'focus',
      html: true,
      placement: 'top'
    })

Side-note, data-container="body" or container: "body" in either HTML or as an option to the popover({}) object didn't really do the trick [maybe the do work but only together with the CSS statement];

Also, remember that Bootstrap 4 beta relies on popper.js for its popover and tooltip positioning (prior to that it was tether.js)

Compare dates in MySQL

this is what it worked for me:

select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
 AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load

Read text from response

The accepted answer does not correctly dispose the WebResponse or decode the text. Also, there's a new way to do this in .NET 4.5.

To perform an HTTP GET and read the response text, do the following.

.NET 1.1 - 4.0

public static string GetResponseText(string address)
{
    var request = (HttpWebRequest)WebRequest.Create(address);

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        var encoding = Encoding.GetEncoding(response.CharacterSet);

        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream, encoding))
            return reader.ReadToEnd();
    }
}

.NET 4.5

private static readonly HttpClient httpClient = new HttpClient();

public static async Task<string> GetResponseText(string address)
{
    return await httpClient.GetStringAsync(address);
}

What's the key difference between HTML 4 and HTML 5?

HTML5 introduces a number of APIs that help in creating Web applications. These can be used together with the new elements introduced for applications:

  • An API for playing of video and audio which can be used with the new video and audio elements.
  • An API that enables offline Web applications.
  • An API that allows a Web application to register itself for certain protocols or media types.
  • An editing API in combination with a new global contenteditable attribute.
  • A drag & drop API in combination with a draggable attribute.
  • An API that exposes the history and allows pages to add to it to prevent breaking the back button.

Ignoring new fields on JSON objects using Jackson

Jackson provides an annotation that can be used on class level (JsonIgnoreProperties).

Add the following to the top of your class (not to individual methods):

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
    ...
}

Depending on the jackson version you are using you would have to use a different import in the current version it is:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

in older versions it has been:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

git with IntelliJ IDEA: Could not read from remote repository

I solved this issue by removing the password for the ssh key in PuTTY.

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

How to create json by JavaScript for loop?

Your question is pretty hard to decode, but I'll try taking a stab at it.

You say:

I want to create a json object having two fields uniqueIDofSelect and optionValue in javascript.

And then you say:

I need output like

[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Well, this example output doesn't have the field named uniqueIDofSelect, it only has optionValue.

Anyway, you are asking for array of objects...

Then in the comment to michaels answer you say:

It creates json object array. but I need only one json object.

So you don't want an array of objects?

What do you want then?

Please make up your mind.

Commenting in a Bash script inside a multiline command

Here is a bash script that combines the ideas and idioms of several previous comments to provide, with examples, inline comments having the general form ${__+ <comment text>}.

In particular

  • <comment text> can be multi-line
  • <comment text> is not parameter-expanded
  • no subprocesses are spawned (so comments are efficient)

There is one restriction on the <comment text>, namely, unbalanced braces '}' and parentheses ')' must be protected (i.e., '\}' and '\)').

There is one requirement on the local bash environment:

  • the parameter name __ must be unset

Any other syntactically valid bash parameter-name will serve in place of __, provided that the name has no set value.

An example script follows

# provide bash inline comments having the form
#     <code> ${__+ <comment>} <code> 
#     <code> ${__+ <multiline
#                   comment>} <code>

# utility routines that obviate "useless use of cat"
function bashcat { printf '%s\n' "$(</dev/stdin)"; }
function scat { 1>&2 bashcat; exit 1; }

# ensure that '__' is unset && remains unset
[[ -z ${__+x} ]] &&  # if '__' is unset
  declare -r __ ||   # then ensure that '__' remains unset 
  scat <<EOF         # else exit with an error
Error: the parameter __='${__}' is set, hence the
  comment-idiom '\${__+ <comment text>}' will fail
EOF

${__+ (example of inline comments)
------------------------------------------------
the following inline comment-idiom is supported
    <code> ${__+ <comment>} <code> 
    <code> ${__+ <multiline
                  comment>} <code> 
(advisory) the parameter '__' must NOT be set;
  even the null declaration __='' will fail
(advisory) protect unbalanced delimiters \} and \) 
(advisory) NO parameter-expansion of <comment> 
(advisory) NO subprocesses are spawned
(advisory) a functionally equivalent idiom is 
    <code> `# <comment>` <code> 
    <code> `# <multiline
               comment>` <code>
however each comment spawns a bash subprocess
that inelegantly requires ~1ms of computation 
------------------------------------------------}

OpenCV - DLL missing, but it's not?

Just for your information,after add the "PATH",for my win7 i need to reboot it to get it work.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

How to sleep the thread in node.js without affecting other threads?

In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

   var startTimeout = function(timeout, i){
        setTimeout(function() {
            myAsyncFunc(i).then(function(data){
                console.log(data);
            })
        }, timeout);
   }

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;
            i++;
        }
    }

This examples waits 1 second after each request before sending the next one.

Disable vertical scroll bar on div overflow: auto

This rules are compatible whit all browser:

body {overflow: hidden; }
body::-webkit-scrollbar { width: 0 !important; }
body { overflow: -moz-scrollbars-none; }
body { -ms-overflow-style: none; }

How do I center this form in css?

  1. Wrap your form in a div.
  2. Set the div's display to block and text-align to center (this will center the contained form).
  3. Set the form's display to inline-block (auto-sizes to content), left and right margins to auto (centers it horizontally), and text-align to left (or else its children will be center-aligned too).

HTML:

<div class="form">
    <form name="Form1" action="mypage.asp" method="get">
        ...
    </form>
</div>

CSS:

div.form
{
    display: block;
    text-align: center;
}
form
{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    text-align: left;
}

How to test if parameters exist in rails

I just read this on RubyInRails classes http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F

you can use blank? method which is equivalent to params[:one].nil? || params[:one].empty?

(e.g)

if params[:one].blank? 
  # do something if not exist
else
  # do something if exist
end

HTTP authentication logout via PHP

AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.

This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details. From then on, until the browser is closed, it will always send the credentials without further prompting.

maven "cannot find symbol" message unhelpful

SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again

WHY SO :
I get this error many times. Most of the times I will try to build my component alone (As I have not made changes elsewhere).

Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times

Decreasing for loops in Python impossible?

for n in range(6,0,-1):
    print n
# prints [6, 5, 4, 3, 2, 1]

How do I get the value of text input field using JavaScript?

There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):

Method 1:

document.getElementById('textbox_id').value to get the value of desired box

For example, document.getElementById("searchTxt").value;

 

Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use 1, and so on...

Method 2:

Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection

For example, document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.

Method 3:

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection

For example, document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.

Method 4:

document.getElementsByName('name')[whole_number].value which also >returns a live NodeList

For example, document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.

Method 5:

Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element

For example, document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name

Method 6:

document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.

For example, document.querySelectorAll('#searchTxt')[0].value; selected by id
document.querySelectorAll('.searchField')[0].value; selected by class
document.querySelectorAll('input')[0].value; selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name

Support

Browser          Method1   Method2  Method3  Method4    Method5/6
IE6              Y(Buggy)   N        Y        Y(Buggy)   N
IE7              Y(Buggy)   N        Y        Y(Buggy)   N
IE8              Y          N        Y        Y(Buggy)   Y
IE9              Y          Y        Y        Y(Buggy)   Y
IE10             Y          Y        Y        Y          Y
FF3.0            Y          Y        Y        Y          N    IE=Internet Explorer
FF3.5/FF3.6      Y          Y        Y        Y          Y    FF=Mozilla Firefox
FF4b1            Y          Y        Y        Y          Y    GC=Google Chrome
GC4/GC5          Y          Y        Y        Y          Y    Y=YES,N=NO
Safari4/Safari5  Y          Y        Y        Y          Y
Opera10.10/
Opera10.53/      Y          Y        Y        Y(Buggy)   Y
Opera10.60
Opera 12         Y          Y        Y        Y          Y

Useful links

  1. To see the support of these methods with all the bugs including more details click here
  2. Difference Between Static collections and Live collections click Here
  3. Difference Between NodeList and HTMLCollection click Here

Conditionally change img src based on model data

Another alternative (other than binary operators suggested by @jm-) is to use ng-switch:

<span ng-switch on="interface">
   <img ng-switch-when="UP" src='green-checkmark.png'>
   <img ng-switch-default   src='big-black-X.png'>
</span>

ng-switch will likely be better/easier if you have more than two images.

Running interactive commands in Paramiko

I'm not familiar with paramiko, but this may work:

ssh_stdin.write('input value')
ssh_stdin.flush()

For information on stdin:

http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin

JavaScript string with new line - but not using \n

I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.

The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it. There is no README.md file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.
https://github.com/mahmalsami/migrate-github-gitlab/blob/master/migrate.sh

What is the worst programming language you ever worked with?

CodeGear Delphi

Its really not the language I disliked, but the IDE: CodeGear RAD Studio for Delphi. This is easily the worst, most buggy, crash-happy IDE I've ever used. Me and the other Delphi programmers would routinely lose hours of development time everyday because the IDE would crash or freeze.

After we installed CodeRush, the application became virtually unsuable. It crashed in regular 5-15 minute intervals, even without user input. Even worse, mysterious errors were triggered by basic debugging, such as hitting a breakpoint (routinely, the debugger would hit a breakpoint and simply freeze in its tracks on a trivial line, like a variable assignment. Nothing you could do would make it proceed any further). If you left the program alone, it would sit stable for up to a half hours before throwing some kind of memory exception.

So, after we'd spent thousands of dollars on licenses CodeGear RAD Studio, no one wanted to use it. By the time I left the company, all of our Delphi projects were coded with VIM instead.

Split string with string as delimiter

I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).

@echo off
setlocal

set "str=string1&with spaces by string2&with spaces.txt"

set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"

echo "%string1%"
echo "%string2%"

For further details on the split method, see this post.

How do I import the javax.servlet API in my Eclipse project?

Many of us develop in Eclipse via a Maven project. If so, you can include Tomcat dependencies in Maven via the tomcat-servlet-api and tomcat-jsp-api jars. One exists for each version of Tomcat. Usually adding these with scope provided to your POM is sufficient. This will keep your build more portable.

If you upgrade Tomcat in the future, you simply update the version of these jars as well.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

You can use this, it works fine:

<input type="date" class="form1"  
  value="{{date | date:MM/dd/yyyy}}"
  ng-model="date" 
  name="id" 
  validatedateformat 
  data-date-format="mm/dd/yyyy"
  maxlength="10" 
  id="id" 
  calendar 
  maxdate="todays"
  ng-click="openCalendar('id')">
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar" ng-click="openCalendar('id')"></span>
    </span>
</input>

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

Why does one use dependency injection?

I think the classic answer is to create a more decoupled application, which has no knowledge of which implementation will be used during runtime.

For example, we're a central payment provider, working with many payment providers around the world. However, when a request is made, I have no idea which payment processor I'm going to call. I could program one class with a ton of switch cases, such as:

class PaymentProcessor{

    private String type;

    public PaymentProcessor(String type){
        this.type = type;
    }

    public void authorize(){
        if (type.equals(Consts.PAYPAL)){
            // Do this;
        }
        else if(type.equals(Consts.OTHER_PROCESSOR)){
            // Do that;
        }
    }
}

Now imagine that now you'll need to maintain all this code in a single class because it's not decoupled properly, you can imagine that for every new processor you'll support, you'll need to create a new if // switch case for every method, this only gets more complicated, however, by using Dependency Injection (or Inversion of Control - as it's sometimes called, meaning that whoever controls the running of the program is known only at runtime, and not complication), you could achieve something very neat and maintainable.

class PaypalProcessor implements PaymentProcessor{

    public void authorize(){
        // Do PayPal authorization
    }
}

class OtherProcessor implements PaymentProcessor{

    public void authorize(){
        // Do other processor authorization
    }
}

class PaymentFactory{

    public static PaymentProcessor create(String type){

        switch(type){
            case Consts.PAYPAL;
                return new PaypalProcessor();

            case Consts.OTHER_PROCESSOR;
                return new OtherProcessor();
        }
    }
}

interface PaymentProcessor{
    void authorize();
}

** The code won't compile, I know :)

How to install Python MySQLdb module using pip?

For Python3 I needed to do this:

python3 -m pip install MySQL

Best way to define private methods for a class in Objective-C

There's no way of getting around issue #2. That's just the way the C compiler (and hence the Objective-C compiler) work. If you use the XCode editor, the function popup should make it easy to navigate the @interface and @implementation blocks in the file.

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

You can't create a new branch with this command

git checkout --track origin/branch

if you have changes that are not staged.

Here is example:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   src/App.js

no changes added to commit (use "git add" and/or "git commit -a")

// TRY TO CREATE:

$ git checkout --track origin/new-branch
fatal: 'origin/new-branch' is not a commit and a branch 'new-branch' cannot be created from it

However you can easily create a new branch with un-staged changes with git checkout -b command:

$ git checkout -b new-branch
Switched to a new branch 'new-branch'
M       src/App.js

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

How do I programmatically force an onchange event on an input?

Create an Event object and pass it to the dispatchEvent method of the element:

var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);

This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.


If you want the event to bubble, you need to pass a second argument to the Event constructor:

var event = new Event('change', { bubbles: true });

Information about browser compability:

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Split string into array of characters?

Here's another way to do it in VBA.

Function ConvertToArray(ByVal value As String)
    value = StrConv(value, vbUnicode)
    ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
    Dim originalString As String
    originalString = "hi there"
    Dim myArray() As String
    myArray = ConvertToArray(originalString)
End Sub

How to find time complexity of an algorithm

This is an excellent article : http://www.daniweb.com/software-development/computer-science/threads/13488/time-complexity-of-algorithm

The below answer is copied from above (in case the excellent link goes bust)

The most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:

statement;

Is constant. The running time of the statement will not change in relation to N.

for ( i = 0; i < N; i++ )
     statement;

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

for ( i = 0; i < N; i++ ) {
  for ( j = 0; j < N; j++ )
    statement;
}

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

while ( low <= high ) {
  mid = ( low + high ) / 2;
  if ( target < list[mid] )
    high = mid - 1;
  else if ( target > list[mid] )
    low = mid + 1;
  else break;
}

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

void quicksort ( int list[], int left, int right )
{
  int pivot = partition ( list, left, right );
  quicksort ( list, left, pivot - 1 );
  quicksort ( list, pivot + 1, right );
}

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( <type> ) where <type> is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note that none of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course. ;)

How can I get the IP address from NIC in Python?

This is the result of ifconfig:

pi@raspberrypi:~ $ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.2.24  netmask 255.255.255.0  broadcast 192.168.2.255
        inet6 fe80::88e9:4d2:c057:2d5f  prefixlen 64  scopeid 0x20<link>
        ether b8:27:eb:d0:9a:f3  txqueuelen 1000  (Ethernet)
        RX packets 261861  bytes 250818555 (239.1 MiB)
        RX errors 0  dropped 6  overruns 0  frame 0
        TX packets 299436  bytes 280053853 (267.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 74  bytes 16073 (15.6 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 74  bytes 16073 (15.6 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlan0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether b8:27:eb:85:cf:a6  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

pi@raspberrypi:~ $ 

Cutting a bit the output, we have:

pi@raspberrypi:~ $ 
pi@raspberrypi:~ $ ifconfig eth0 | grep "inet 192" | cut -c 14-25
192.168.2.24
pi@raspberrypi:~ $ 
pi@raspberrypi:~ $ 

Now, we can go to python and do:

import os
mine = os.popen('ifconfig eth0 | grep "inet 192" | cut -c 14-25')
myip = mine.read()
print (myip)

Refresh Page C# ASP.NET

Careful with rewriting URLs, though. I'm using this, so it keeps URLs rewritten.

Response.Redirect(Request.RawUrl);

How to restart a single container with docker-compose

The answer's here are talking about the reflection of the change on the docker-compose.yml file.

But what if I want to incorporate the changes I have done in my code, and I believe that will be only possible by rebuilding the image and that I do with following commands

1. docker container stop

docker stop container-id

2. docker container removal

docker rm container-id

3. docker image removal

docker rmi image-id

4. compose the container again

docker-compose up container-name