Programs & Examples On #Addremoveprograms

The "Add/Remove Programs" utility is a standard Microsoft Windows UI for listing applications installed on the computer and providing basic mainterance actions like uninstalling, repairing or modifying the installations.

Show git diff on file in staging area

You can also use git diff HEAD file to show the diff for a specific file.

See the EXAMPLE section under git-diff(1)

NPM clean modules

You can take advantage of the 'npm cache' command which downloads the package tarball and unpacks it into the npm cache directory.

The source can then be copied in.

Using ideas gleaned from https://groups.google.com/forum/?fromgroups=#!topic/npm-/mwLuZZkHkfU I came up with the following node script. No warranties, YMMV, etcetera.

var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
util = require('util');

var packageFileName = 'package.json';
var modulesDirName = 'node_modules';
var cacheDirectory = process.cwd();
var npmCacheAddMask = 'npm cache add %s@%s; echo %s';
var sourceDirMask = '%s/%s/%s/package';
var targetDirMask = '%s/node_modules/%s';

function deleteFolder(folder) {
    if (fs.existsSync(folder)) {
        var files = fs.readdirSync(folder);
        files.forEach(function(file) {
            file = folder + "/" + file;
            if (fs.lstatSync(file).isDirectory()) {
                deleteFolder(file);
            } else {
                fs.unlinkSync(file);
            }
        });
        fs.rmdirSync(folder);
    }
}

function downloadSource(folder) {
    var packageFile = path.join(folder, packageFileName);
    if (fs.existsSync(packageFile)) {
        var data = fs.readFileSync(packageFile);
        var package = JSON.parse(data);

        function getVersion(data) {
            var version = data.match(/-([^-]+)\.tgz/);
            return version[1];
        }

        var callback = function(error, stdout, stderr) {
            var dependency = stdout.trim();
            var version = getVersion(stderr);
            var sourceDir = util.format(sourceDirMask, cacheDirectory, dependency, version);
            var targetDir = util.format(targetDirMask, folder, dependency);
            var modulesDir = folder + '/' + modulesDirName;

            if (!fs.existsSync(modulesDir)) {
                fs.mkdirSync(modulesDir);
            }

            fs.renameSync(sourceDir, targetDir);
            deleteFolder(cacheDirectory + '/' + dependency);
            downloadSource(targetDir);
        };

        for (dependency in package.dependencies) {
            var version = package.dependencies[dependency];
            exec(util.format(npmCacheAddMask, dependency, version, dependency), callback);
        }
    }
}

if (!fs.existsSync(path.join(process.cwd(), packageFileName))) {
    console.log(util.format("Unable to find file '%s'.", packageFileName));
    process.exit();
}

deleteFolder(path.join(process.cwd(), modulesDirName));
process.env.npm_config_cache = cacheDirectory;
downloadSource(process.cwd());

Iterating through all nodes in XML file

This is what I quickly wrote for myself:

public static class XmlDocumentExtensions
{
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
    {
        if (doc != null && elementVisitor != null)
        {
            foreach (XmlNode node in doc.ChildNodes)
            {
                doIterateNode(node, elementVisitor);
            }
        }
    }

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)
    {
        elementVisitor(node);

        foreach (XmlNode childNode in node.ChildNodes)
        {
            doIterateNode(childNode, elementVisitor);
        }
    }
}

To use it, I've used something like:

var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });

Maybe it helps someone out there.

Reading content from URL with Node.js

HTTP and HTTPS:

const getScript = (url) => {
    return new Promise((resolve, reject) => {
        const http      = require('http'),
              https     = require('https');

        let client = http;

        if (url.toString().indexOf("https") === 0) {
            client = https;
        }

        client.get(url, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (err) => {
            reject(err);
        });
    });
};

(async (url) => {
    console.log(await getScript(url));
})('https://sidanmor.com/');

SQL Inner join 2 tables with multiple column conditions and update

You should join T1 and T2 tables using sql joins in order to analyze from two tables. Link for learn joins : https://www.w3schools.com/sql/sql_join.asp

Background images: how to fill whole div if image is small and vice versa

To automatically enlarge the image and cover the entire div section without leaving any part of it unfilled, use:

background-size: cover;

MySQL - DATE_ADD month interval

Do I understand right that you assume that DATE_ADD("2011-01-01", INTERVAL 6 MONTH) should give you '2011-06-30' instead of '2011-07-01'? Of course, 2011-01-01 + 6 months is 2011-07-01. You want something like DATE_SUB(DATE_ADD("2011-01-01", INTERVAL 6 MONTH), INTERVAL 1 DAY).

Removing multiple classes (jQuery)

There are many ways can do that!

jQuery

  1. remove all class
    $("element").removeClass();
    OR
    $("#item").removeAttr('class');
    OR
    $("#item").attr('class', '');
    OR
    $('#item')[0].className = '';

  2. remove multi class
    $("element").removeClass("class1 ... classn");
    OR
    $("element").removeClass("class1").removeClass("...").removeClass("classn");

Vanilla Javascript

  1. remove all class

_x000D_
_x000D_
// remove all items all class  _x000D_
const items = document.querySelectorAll('item');_x000D_
for (let i = 0; i < items.length; i++) {_x000D_
    items[i].className = '';_x000D_
}
_x000D_
_x000D_
_x000D_

  1. remove multi class

_x000D_
_x000D_
// only remove all class of first item_x000D_
const item1 = document.querySelector('item');_x000D_
item1.className = '';
_x000D_
_x000D_
_x000D_

Javascript to stop HTML5 video playback on modal window close

Try this:

$(document).ready(function(){
    $("#showSimpleModal").click(function() {
        $("div#simpleModal").addClass("show");
        $("#videoContainer")[0].play();
        return false;   
    });

    $("#closeSimple").click(function() {
        $("div#simpleModal").removeClass("show");
        $("#videoContainer")[0].pause();
        return false;                   
    });
});

How to remove word wrap from textarea?

Textareas shouldn't wrap by default, but you can set wrap="soft" to explicitly disable wrap:

<textarea name="nowrap" cols="30" rows="3" wrap="soft"></textarea>

EDIT: The "wrap" attribute is not officially supported. I got it from the german SELFHTML page (an english source is here) that says IE 4.0 and Netscape 2.0 support it. I also tested it in FF 3.0.7 where it works as supposed. Things have changed here, SELFHTML is now a wiki and the english source link is dead.

EDIT2: If you want to be sure every browser supports it, you can use CSS to change wrap behaviour:

Using Cascading Style Sheets (CSS), you can achieve the same effect with white-space: nowrap; overflow: auto;. Thus, the wrap attribute can be regarded as outdated.

From here (seems to be an excellent page with information about textarea).

EDIT3: I'm not sure when it changed (according to the comments, must've been around 2014), but wrap is now an official HTML5 attribute, see w3schools. Changed the answer to match this.

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

You can use ExtendedXmlSerializer. If you have a class:

public class TestClass
{
    public Dictionary<int, string> Dictionary { get; set; }
}

and create instance of this class:

var obj = new TestClass
{
    Dictionary = new Dictionary<int, string>
    {
        {1, "First"},
        {2, "Second"},
        {3, "Other"},
    }
};

You can serialize this object using ExtendedXmlSerializer:

var serializer = new ConfigurationContainer()
    .UseOptimizedNamespaces() //If you want to have all namespaces in root element
    .Create();

var xml = serializer.Serialize(
    new XmlWriterSettings { Indent = true }, //If you want to formated xml
    obj);

Output xml will look like:

<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
  <Dictionary>
    <sys:Item>
      <Key>1</Key>
      <Value>First</Value>
    </sys:Item>
    <sys:Item>
      <Key>2</Key>
      <Value>Second</Value>
    </sys:Item>
    <sys:Item>
      <Key>3</Key>
      <Value>Other</Value>
    </sys:Item>
  </Dictionary>
</TestClass>

You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

php $_GET and undefined index

I recommend you check your arrays before you blindly access them :

if(isset($_GET['s'])){
    if ($_GET['s'] == 'jwshxnsyllabus')
        /* your code here*/
}

Another (quick) fix is to disable the error reporting by writing this on the top of the script :

error_reporting(0);  

In your case, it is very probable that your other server had the error reporting configuration in php.ini set to 0 as default.
By calling the error_reporting with 0 as parameter, you are turning off all notices/warnings and errors. For more details check the php manual.

Remeber that this is a quick fix and it's highly recommended to avoid errors rather than ignore them.

Access a JavaScript variable from PHP

The short answer is you can't.

I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).

You're doing a $_GET, which is used to retrieve form values:

The built-in $_GET function is used to collect values in a form with method="get".

In other words, if on your page you had:

<form method="get" action="blah.php">
    <input name="test"></input>
</form>

Your $_GET call would retrieve the value in that input field.

So how to retrieve a value from JavaScript?

Well, you could stick the javascript value in a hidden form field...

<script type="text/javascript" charset="utf-8">
    var test = "tester";
    // find the 'test' input element and set its value to the above variable
    document.getElementByID("test").value = test;
</script>

... elsewhere on your page ...

<form method="get" action="blah.php">
    <input id="test" name="test" visibility="hidden"></input>
    <input type="submit" value="Click me!"></input>
</form>

Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.

Maven artifact and groupId naming

Weirdness is highly subjective, I just suggest to follow the official recommendation:

Guide to naming conventions on groupId, artifactId and version

  • groupId will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.

    eg. org.apache.maven, org.apache.commons

    A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.

    eg. org.apache.maven, org.apache.maven.plugins, org.apache.maven.reporting

  • artifactId is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.

    eg. maven, commons-math

  • version if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.

    eg. 2.0, 2.0.1, 1.3.1

How do I remove a substring from the end of a string in Python?

In one line:

text if not text.endswith(suffix) or len(suffix) == 0 else text[:-len(suffix)]

curl: (6) Could not resolve host: google.com; Name or service not known

I have today similar problem. But weirder.

  • host - works host pl.archive.ubuntu.com
  • dig - works on default and on all other DNS's dig pl.archive.ubuntu.com, dig @127.0.1.1 pl.archive.ubuntu.com
  • curl - doesn't work! but for some addresses it does. WEIRD! Same in Ruby, APT and many more.
$ curl -v http://google.com/
*   Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact

$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com

Revelation

Eventually I used strace on curl and found that it was connection to nscd deamon.

connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0

Solution

I've restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!

systemctl restart nscd.service

How to do jquery code AFTER page loading?

And if you want to run a second function after the first one finishes, see this stackoverflow answer.

How to set the height of table header in UITableView?

In case you still need it, have you tried to set the property

self.tableView.tableHeaderView 

If you calculate the heigh you need, and set a new view for tableHeaderView:

CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = newHeight;

self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];

It should work.

JavaScript "cannot read property "bar" of undefined

Compound checking:

   if (thing.foo && thing.foo.bar) {
      ... thing.foor.bar exists;
   }

Declaring variables inside or outside of a loop

if you want to use str outside looop also; declare it outside. otherwise, 2nd version is fine.

Removing padding gutter from grid columns in Bootstrap 4

You should use built-in bootstrap4 spacing classes for customizing the spacing of elements, that's more convenient method .

Get div's offsetTop positions in React

A better solution with ref to avoid findDOMNode that is discouraged.

...
onScroll() {
    let offsetTop  = this.instance.getBoundingClientRect().top;
}
...
render() {
...
<Component ref={(el) => this.instance = el } />
...

When to use If-else if-else over switch statements and vice versa

The tendency to avoid stuff because it takes longer to type is a bad thing, try to root it out. That said, overly verbose things are also difficult to read, so small and simple is important, but it's readability not writability that's important. Concise one-liners can often be more difficult to read than a simple well laid out 3 or 4 lines.

Use whichever construct best descibes the logic of the operation.

Returning JSON object from an ASP.NET page

With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.

var json = Json.Encode(new {
    orientation = Cache["orientation"],
    alerted = Cache["alerted"] as bool?,
    since = Cache["since"] as DateTime?
});
Response.Write(json);

Meaning of $? (dollar question mark) in shell scripts

See The Bash Manual under 3.4.2 Special Parameters:

? - Expands to the exit status of the most recently executed foreground pipeline.

It is a little hard to find because it is not listed as $? (the variable name is "just" ?). Also see the exit status section, of course ;-)

Happy coding.

How to use JNDI DataSource provided by Tomcat in Spring?

Another feature: instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml (according to tomcat docs) like this:

<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
  username="dbUsername" password="dbPasswd"
  url="jdbc:postgresql://localhost/dbname"
  driverClassName="org.postgresql.Driver"
  initialSize="5" maxWait="5000"
  maxActive="120" maxIdle="5"
  validationQuery="select 1"
  poolPreparedStatements="true"/>
</Context>

Hive: Filtering Data between Specified Dates when Date is a String

The great thing about yyyy-mm-dd date format is that there is no need to extract month() and year(), you can do comparisons directly on strings:

SELECT *
  FROM your_table
  WHERE your_date_column >= '2010-09-01' AND your_date_column <= '2013-08-31';

How do I update the element at a certain position in an ArrayList?

arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.

notify is optional, depends on conditions.

How can I shrink the drawable on a button?

It is because you did not setLevel. after you setLevel(1), it will be display as u want

When should I use a trailing slash in my URL?

Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.

CSS/HTML: What is the correct way to make text italic?

TLDR

The correct way to make text italic is to ignore the problem until you get to the CSS, then style according to presentational semantics. The first two options you provided could be right depending on the circumstances. The last two are wrong.

Longer Explanation

Don't worry about presentation when writing the markup. Don't think in terms of italics. Think in terms of semantics. If it requires stress emphasis, then it's an em. If it's tangential to the main content, then it's an aside. Maybe it'll be bold, maybe it'll be italic, maybe it'll be fluorescent green. It doesn't matter when you're writing markup.

When you do get to the CSS, you might already have a semantic element that makes sense to put italics for all its occurrences in your site. em is a good example. But maybe you want all aside > ul > li on your site in italics. You have to separate thinking about the markup from thinking about the presentation.

As mentioned by DisgruntledGoat, i is semantic in HTML5. The semantics seem kind of narrow to me, though. Use will probably be rare.

The semantics of em have changed in HTML5 to stress emphasis. strong can be used to show importance as well. strong can be italic rather than bold if that's how you want to style it. Don't let the browser's stylesheet limit you. You can even use a reset stylesheet to help you stop thinking within the defaults. (Though there are some caveats.)

class="italic" is bad. Don't use it. It is not semantic and is not flexible at all. Presentation still has semantics, just a different kind from markup.

class="footnote" is emulating markup semantics and is incorrect as well. Your CSS for the footnote should not be completely unique to your footnote. Your site will look too messy if every part is styled differently. You should have some visual patterns scattered through your pages that you can turn into CSS classes. If your style for your footnotes and your blockquotes are very similar, then you should put the similarities into one class rather than repeat yourself over and over again. You might consider adopting the practices of OOCSS (links below).

Separation of concerns and semantics are big in HTML5. People often don't realize that the markup isn't the only place where semantics is important. There is content semantics (HTML), but there is also presentational semantics (CSS) and behavioral semantics (JavaScript) as well. They all have their own separate semantics that are important to pay attention to for maintainability and staying DRY.

OOCSS Resources

How can I pad an int with leading zeros when using cout << operator?

With the following,

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 25;
}

the output will be

00025

setfill is set to the space character (' ') by default. setw sets the width of the field to be printed, and that's it.


If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.

PHP get dropdown value and text

Is there a reason you didn't just use this?

<select id="animal" name="animal">                      
  <option value="0">--Select Animal--</option>
  <option value="Cat">Cat</option>
  <option value="Dog">Dog</option>
  <option value="Cow">Cow</option>
</select>

if($_POST['submit'] && $_POST['submit'] != 0)
{
   $animal=$_POST['animal'];
}

How to normalize a 2-dimensional numpy array in python less verbose?

Here is one more possible way using reshape:

a_norm = (a/a.sum(axis=1).reshape(-1,1)).round(3)
print(a_norm)

Or using None works too:

a_norm = (a/a.sum(axis=1)[:,None]).round(3)
print(a_norm)

Output:

array([[0.   , 0.333, 0.667],
       [0.25 , 0.333, 0.417],
       [0.286, 0.333, 0.381]])

Pass table as parameter into sql server UDF

I've been dealing with a very similar problem and have been able to achieve what I was looking for, even though I'm using SQL Server 2000. I know it is an old question, but think its valid to post here the solution since there should be others like me that use old versions and still need help.

Here's the trick: SQL Server won't accept passing a table to a UDF, nor you can pass a T-SQL query so the function creates a temp table or even calls a stored procedure to do that. So, instead, I've created a reserved table, which I called xtList. This will hold the list of values (1 column, as needed) to work with.

CREATE TABLE [dbo].[xtList](
    [List] [varchar](1000) NULL
) ON [PRIMARY]

Then, a stored procedure to populate the list. This is not strictly necessary, but I think is very usefull and best practice.

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE PROCEDURE [dbo].[xpCreateList]
    @ListQuery varchar(2000)
AS
BEGIN
    SET NOCOUNT ON;

  DELETE FROM xtList

  INSERT INTO xtList
    EXEC(@ListQuery)
END

Now, just deal with the list in any way you want, using the xtList. You can use in a procedure (for executing several T-SQL commands), scalar functions (for retrieving several strings) or multi-statement table-valued functions (retrieves the strings but like it was inside a table, 1 string per row). For any of that, you'll need cursors:

DECLARE @Item varchar(100)
DECLARE cList CURSOR DYNAMIC
  FOR (SELECT * FROM xtList WHERE List is not NULL)
  OPEN cList

FETCH FIRST FROM cList INTO @Item
WHILE @@FETCH_STATUS = 0 BEGIN

  << desired action with values >>

FETCH NEXT FROM cList INTO @Item
END
CLOSE cList
DEALLOCATE cList

The desired action would be as follows, depending on which type of object created:

Stored procedures

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE PROCEDURE [dbo].[xpProcreateExec]
(
    @Cmd varchar(8000),
    @ReplaceWith varchar(1000)
)
AS
BEGIN
  DECLARE @Query varchar(8000)

  << cursor start >>
    SET @Query = REPLACE(@Cmd,@ReplaceWith,@Item)
    EXEC(@Query)
  << cursor end >>
END

/* EXAMPLES

  (List A,B,C)

  Query = 'SELECT x FROM table'
    with EXEC xpProcreateExec(Query,'x') turns into
  SELECT A FROM table
  SELECT B FROM table
  SELECT C FROM table

  Cmd = 'EXEC procedure ''arg''' --whatchout for wrong quotes, since it executes as dynamic SQL
    with EXEC xpProcreateExec(Cmd,'arg') turns into
  EXEC procedure 'A'
  EXEC procedure 'B'
  EXEC procedure 'C'

*/

Scalar functions

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE FUNCTION [dbo].[xfProcreateStr]
(
    @OriginalText varchar(8000),
    @ReplaceWith varchar(1000)
)
RETURNS varchar(8000)
AS
BEGIN
    DECLARE @Result varchar(8000)

  SET @Result = ''
  << cursor start >>
    SET @Result = @Result + REPLACE(@OriginalText,@ReplaceWith,@Item) + char(13) + char(10)
  << cursor end >>

    RETURN @Result
END

/* EXAMPLE

  (List A,B,C)

  Text = 'Access provided for user x'
    with "SELECT dbo.xfProcreateStr(Text,'x')" turns into
  'Access provided for user A
  Access provided for user B
  Access provided for user C'

*/

Multi-statement table-valued functions

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE FUNCTION [dbo].[xfProcreateInRows]
(
    @OriginalText varchar(8000),
    @ReplaceWith varchar(1000)
)
RETURNS 
@Texts TABLE 
(
    Text varchar(2000)
)
AS
BEGIN
  << cursor start >>
      INSERT INTO @Texts VALUES(REPLACE(@OriginalText,@ReplaceWith,@Item))
  << cursor end >>
END

/* EXAMPLE

  (List A,B,C)

  Text = 'Access provided for user x'
    with "SELECT * FROM dbo.xfProcreateInRow(Text,'x')" returns rows
  'Access provided for user A'
  'Access provided for user B'
  'Access provided for user C'

*/

How to input automatically when running a shell over SSH?

For simple input, like two prompts and two corresponding fixed responses, you could also use a "here document", the syntax of which looks like this:

test.sh <<!
y
pasword
!

The << prefixes a pattern, in this case '!'. Everything up to a line beginning with that pattern is interpreted as standard input. This approach is similar to the suggestion to pipe a multi-line echo into ssh, except that it saves the fork/exec of the echo command and I find it a bit more readable. The other advantage is that it uses built-in shell functionality so it doesn't depend on expect.

Can you style an html radio button to look like a checkbox?

I tweaked user2314737's answer to use font awesome for the icon. For those unfamiliar with fa, one significant benefit over img's is the vector based rendering inherent to fonts. I.e. no image jaggies at any zoom level.

jsFiddle

Result

enter image description here

_x000D_
_x000D_
div.checkRadioContainer > label > input {_x000D_
 visibility: hidden;_x000D_
}_x000D_
_x000D_
div.checkRadioContainer {_x000D_
 max-width: 10em;_x000D_
}_x000D_
div.checkRadioContainer > label {_x000D_
 display: block;_x000D_
 border: 2px solid grey;_x000D_
 margin-bottom: -2px;_x000D_
 cursor: pointer;_x000D_
}_x000D_
_x000D_
div.checkRadioContainer > label:hover {_x000D_
 background-color: AliceBlue;_x000D_
}_x000D_
_x000D_
div.checkRadioContainer > label > span {_x000D_
 display: inline-block;_x000D_
 vertical-align: top;_x000D_
 line-height: 2em;_x000D_
}_x000D_
_x000D_
div.checkRadioContainer > label > input + i {_x000D_
 visibility: hidden;_x000D_
 color: green;_x000D_
 margin-left: -0.5em;_x000D_
 margin-right: 0.2em;_x000D_
}_x000D_
_x000D_
div.checkRadioContainer > label > input:checked + i {_x000D_
 visibility: visible;_x000D_
}
_x000D_
<div class="checkRadioContainer">_x000D_
 <label>_x000D_
  <input type="radio" name="radioGroup" />_x000D_
  <i class="fa fa-check fa-2x"></i>_x000D_
  <span>Item 1</span>_x000D_
 </label>_x000D_
 <label>_x000D_
  <input type="radio" name="radioGroup" />_x000D_
  <i class="fa fa-check fa-2x"></i>_x000D_
  <span>Item 2</span>_x000D_
 </label>_x000D_
 <label>_x000D_
  <input type="radio" name="radioGroup" />_x000D_
  <i class="fa fa-check fa-2x"></i>_x000D_
  <span>Item 3</span>_x000D_
 </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Property [title] does not exist on this collection instance

$about = DB::where('page', 'about-me')->first(); 

in stead of get().

It works on my project. Thanks.

PHP cURL, extract an XML response

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

How to align content of a div to the bottom

You can simply achieved flex

_x000D_
_x000D_
header {_x000D_
  border: 1px solid blue;_x000D_
  height: 150px;_x000D_
  display: flex;                   /* defines flexbox */_x000D_
  flex-direction: column;          /* top to bottom */_x000D_
  justify-content: space-between;  /* first item at start, last at end */_x000D_
}_x000D_
h1 {_x000D_
  margin: 0;_x000D_
}
_x000D_
<header>_x000D_
  <h1>Header title</h1>_x000D_
  Some text aligns to the bottom_x000D_
</header>
_x000D_
_x000D_
_x000D_

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

MessageBox.Show(
  "your message",
  "window title", 
  MessageBoxButtons.OK, 
  MessageBoxIcon.Asterisk //For Info Asterisk
  MessageBoxIcon.Exclamation //For triangle Warning 
)

Convert hex string to int

Try with this:

long abc=convertString2Hex("1A2A3B");

private  long  convertString2Hex(String numberHexString)
{
    char[] ChaArray = numberHexString.toCharArray();
    long HexSum=0;
    long cChar =0;

    for(int i=0;i<numberHexString.length();i++ )
    {
        if( (ChaArray[i]>='0') && (ChaArray[i]<='9') )
            cChar = ChaArray[i] - '0';
        else
            cChar = ChaArray[i]-'A'+10;
        HexSum = 16 * HexSum + cChar;
    }
    return  HexSum;
}

Python memory leaks

To detect and locate memory leaks for long running processes, e.g. in production environments, you can now use stackimpact. It uses tracemalloc underneath. More info in this post.

enter image description here

Remove HTML Tags from an NSString on the iPhone

If you want to get the content without the html tags from the web page (HTML document) , then use this code inside the UIWebViewDidfinishLoading delegate method.

  NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];

SQL Server: Is it possible to insert into two tables at the same time?

The following sets up the situation I had, using table variables.

DECLARE @Object_Table TABLE
(
    Id INT NOT NULL PRIMARY KEY
)

DECLARE @Link_Table TABLE
(
    ObjectId INT NOT NULL,
    DataId INT NOT NULL
)

DECLARE @Data_Table TABLE
(
    Id INT NOT NULL Identity(1,1),
    Data VARCHAR(50) NOT NULL
)

-- create two objects '1' and '2'
INSERT INTO @Object_Table (Id) VALUES (1)
INSERT INTO @Object_Table (Id) VALUES (2)

-- create some data
INSERT INTO @Data_Table (Data) VALUES ('Data One')
INSERT INTO @Data_Table (Data) VALUES ('Data Two')

-- link all data to first object
INSERT INTO @Link_Table (ObjectId, DataId)
SELECT Objects.Id, Data.Id
FROM @Object_Table AS Objects, @Data_Table AS Data
WHERE Objects.Id = 1

Thanks to another answer that pointed me towards the OUTPUT clause I can demonstrate a solution:

-- now I want to copy the data from from object 1 to object 2 without looping
INSERT INTO @Data_Table (Data)
OUTPUT 2, INSERTED.Id INTO @Link_Table (ObjectId, DataId)
SELECT Data.Data
FROM @Data_Table AS Data INNER JOIN @Link_Table AS Link ON Data.Id = Link.DataId
                INNER JOIN @Object_Table AS Objects ON Link.ObjectId = Objects.Id 
WHERE Objects.Id = 1

It turns out however that it is not that simple in real life because of the following error

the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship

I can still OUTPUT INTO a temp table and then finish with normal insert. So I can avoid my loop but I cannot avoid the temp table.

Set focus to field in dynamically loaded DIV

This runs on page load.

<script type="text/javascript">
    $(function () {
        $("#header").focus();
    });
</script>

Constructors in Go

There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

Supposing you have a struct like this :

type Thing struct {
    Name  string
    Num   int
}

then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // <- a very sensible default value
    return p
}

When your struct is simple enough, you can use this condensed construct :

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference : Allocation with new in Effective Go.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

IE9 jQuery AJAX with CORS returns "Access is denied"

Building off the accepted answer by @dennisg, I accomplished this successfully using jQuery.XDomainRequest.js by MoonScript.

The following code worked correctly in Chrome, Firefox and IE10, but failed in IE9. I simply included the script and it now automagically works in IE9. (And probably 8, but I haven't tested it.)

var displayTweets = function () {
    $.ajax({
        cache: false,
        type: 'GET',
        crossDomain: true,
        url: Site.config().apiRoot + '/Api/GetTwitterFeed',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
            for (var tweet in data) {
                displayTweet(data[tweet]);
            }
        }
    });
};

ValueError: max() arg is an empty sequence

in one line,

v = max(v) if v else None

>>> v = []
>>> max(v)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
>>> v = max(v) if v else None
>>> v
>>> 

Among $_REQUEST, $_GET and $_POST which one is the fastest?

$_GET retrieves variables from the querystring, or your URL.>

$_POST retrieves variables from a POST method, such as (generally) forms.

$_REQUEST is a merging of $_GET and $_POST where $_POST overrides $_GET. Good to use $_REQUEST on self refrential forms for validations.

How do you convert WSDLs to Java classes using Eclipse?

Using command prompt in windows you can use below command to get class files.

wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl

if you want to generate source code you should be using below commnad.

wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl

Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.

In PowerShell, how can I test if a variable holds a numeric value?

Each numeric type has its own value. See TypeCode enum definition: https://docs.microsoft.com/en-us/dotnet/api/system.typecode?view=netframework-4.8 Based on this info, all your numeric type-values are in the range from 5 to 15. This means, you can write the condition-check like this:

$typeValue = $x.getTypeCode().value__
if ($typeValue -ge 5 -and $typeValue -le 15) {"x has a numeric type!"}

How is CountDownLatch used in Java Multithreading?

From oracle documentation about CountDownLatch:

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset.

A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes.

A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown().

A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

public void await()
           throws InterruptedException

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.

If the current count is zero then this method returns immediately.

public void countDown()

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

If the current count is greater than zero then it is decremented. If the new count is zero then all waiting threads are re-enabled for thread scheduling purposes.

Explanation of your example.

  1. You have set count as 3 for latch variable

    CountDownLatch latch = new CountDownLatch(3);
    
  2. You have passed this shared latch to Worker thread : Processor

  3. Three Runnable instances of Processor have been submitted to ExecutorService executor
  4. Main thread ( App ) is waiting for count to become zero with below statement

     latch.await();  
    
  5. Processor thread sleeps for 3 seconds and then it decrements count value with latch.countDown()
  6. First Process instance will change latch count as 2 after it's completion due to latch.countDown().

  7. Second Process instance will change latch count as 1 after it's completion due to latch.countDown().

  8. Third Process instance will change latch count as 0 after it's completion due to latch.countDown().

  9. Zero count on latch causes main thread App to come out from await

  10. App program prints this output now : Completed

nodejs get file name from absolute path?

So Nodejs comes with the default global variable called '__fileName' that holds the current file being executed My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic

Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.

You can write a service like this (Note this is in typescript , but you can very well write it in js )

export class AppLoggingConstants {

    constructor(){

    }
      // Here make sure the fileName param is actually '__fileName'
    getDefaultMedata(fileName: string, methodName: string) {
        const appName = APP_NAME;
        const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
        //const actualFileName = fileName;
     return appName+ ' -- '+actualFileName;
    }


}

export const AppLoggingConstantsInstance = new AppLoggingConstants();

How to rotate the background image in the container?

CSS:

.reverse {
  transform: rotate(180deg);
}

.rotate {
  animation-duration: .5s;
  animation-iteration-count: 1;
  animation-name: yoyo;
  animation-timing-function: linear;
}

@keyframes yoyo {
  from { transform: rotate(  0deg); }
  to   { transform: rotate(360deg); }
}

Javascript:

$(buttonElement).click(function () {
  $(".arrow").toggleClass("reverse")

  return false
})

$(buttonElement).hover(function () {
  $(".arrow").addClass("rotate")
}, function() {
  $(".arrow").removeClass("rotate")
})

PS: I've found this somewhere else but don't remember the source

Detect backspace and del on "input" event?

keydown with event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Modern style:

input.addEventListener('keydown', ({key}) => {
    if (["Backspace", "Delete"].includes(key)) {
        return false
    }
})

Mozilla Docs

Supported Browsers

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

//In the Application_OnBeginRequest method in GLOBAL.ASX add the following:-  

var res = HttpContext.Current.Response;  
var req = HttpContext.Current.Request;  
res.AppendHeader("Access-Control-Allow-Origin", "*");  
res.AppendHeader("Access-Control-Allow-Credentials", "true");  
res.AppendHeader("Access-Control-Allow-Headers", "Authorization");  
res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");  

    // ==== Respond to the OPTIONS verb =====
    if (req.HttpMethod == "OPTIONS")
    {
        res.StatusCode = 200;
        res.End();
    }

//Remove any entries in the custom headers as this will throw an error that there's to  
//many values in the header.  

<httpProtocol>
    <customHeaders>
    </customHeaders>
</httpProtocol>

How can I determine installed SQL Server instances and their versions?

From Windows command-line, type:

SC \\server_name query | find /I "SQL Server ("

Where "server_name" is the name of any remote server on which you wish to display the SQL instances.

This requires enough permissions of course.

Why doesn't Python have a sign function?

Since cmp has been removed, you can get the same functionality with

def cmp(a, b):
    return (a > b) - (a < b)

def sign(a):
    return (a > 0) - (a < 0)

It works for float, int and even Fraction. In the case of float, notice sign(float("nan")) is zero.

Python doesn't require that comparisons return a boolean, and so coercing the comparisons to bool() protects against allowable, but uncommon implementation:

def sign(a):
    return bool(a > 0) - bool(a < 0)

Maven compile: package does not exist

You have to add the following dependency to your build:

<dependency>
    <groupId>org.openrdf.sesame</groupId>
    <artifactId>sesame-rio-api</artifactId>
    <version>2.7.2</version>
</dependency>

Furthermore i would suggest to take a deep look into the documentation about how to use the lib.

Sublime Text 2 Code Formatting

Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.

For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).

Greets

Where is NuGet.Config file located in Visual Studio project?

In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.

How can my iphone app detect its own version number?

This is a good thing to handle with a revision control system. That way when you get a bug report from a user, you can check out that revision of code and (hopefully) reproduce the bug running the exact same code as the user.

The idea is that every time you do a build, you will run a script that gets the current revision number of your code and updates a file within your project (usually with some form of token replacement). You can then write an error handling routine that always includes the revision number in the error output, or you can display it on an "About" page.

Unclosed Character Literal error

In Java, single quotes can only take one character, with escape if necessary. You need to use full quotation marks as follows for strings:

y = "hello";

You also used

System.out.println(g);

which I assume should be

System.out.println(y);

Note: When making char values (you'll likely use them later) you need single quotes. For example:

char foo='m';

How to insert blank lines in PDF?

You can also use

document.add(new Paragraph());
document.add(new Paragraph());

before seperator if you are using either it is fine.

Can I set up HTML/Email Templates with ASP.NET?

@bardev provides a good solution, but unfortunately it's not ideal in all cases. Mine was one of them.

I'm using WebForms in a Website (I swear I'll never use a Website again--what a PITA) in VS 2013.

I tried the Razor suggestion, but mine being a Website I didn't get the all-important IntelliSense that the IDE delivers in an MVC project. I also like to use the designer for my templates--a perfect spot for a UserControl.

Nix on Razor again.

So I came up with this little framework instead (hat tips to @mun for UserControl and @imatoria for Strong Typing). Just about the only potential trouble spot I can see is that you have to be careful to keep your .ASCX filename in sync with its class name. If you stray, you'll get a runtime error.

FWIW: In my testing at least the RenderControl() call doesn't like a Page control, so I went with UserControl.

I'm pretty sure I've included everything here; let me know if I left something out.

HTH

Usage:

Partial Class Purchase
  Inherits UserControl

  Private Sub SendReceipt()
    Dim oTemplate As MailTemplates.PurchaseReceipt

    oTemplate = MailTemplates.Templates.PurchaseReceipt(Me)
    oTemplate.Name = "James Bond"
    oTemplate.OrderTotal = 3500000
    oTemplate.OrderDescription = "Q-Stuff"
    oTemplate.InjectCss("PurchaseReceipt")

    Utils.SendMail("{0} <[email protected]>".ToFormat(oTemplate.Name), "Purchase Receipt", oTemplate.ToHtml)
  End Sub
End Class

Base Class:

Namespace MailTemplates
  Public MustInherit Class BaseTemplate
    Inherits UserControl

    Public Shared Function GetTemplate(Caller As TemplateControl, Template As Type) As BaseTemplate
      Return Caller.LoadControl("~/MailTemplates/{0}.ascx".ToFormat(Template.Name))
    End Function



    Public Sub InjectCss(FileName As String)
      If Me.Styler IsNot Nothing Then
        Me.Styler.Controls.Add(New Controls.Styler(FileName))
      End If
    End Sub



    Private ReadOnly Property Styler As PlaceHolder
      Get
        If _Styler Is Nothing Then
          _Styler = Me.FindNestedControl(GetType(PlaceHolder))
        End If

        Return _Styler
      End Get
    End Property
    Private _Styler As PlaceHolder
  End Class
End Namespace

"Factory" Class:

Namespace MailTemplates
  Public Class Templates
    Public Shared ReadOnly Property PurchaseReceipt(Caller As TemplateControl) As PurchaseReceipt
      Get
        Return BaseTemplate.GetTemplate(Caller, GetType(PurchaseReceipt))
      End Get
    End Property
  End Class
End Namespace

Template Class:

Namespace MailTemplates
  Public MustInherit Class PurchaseReceipt
    Inherits BaseTemplate

    Public MustOverride WriteOnly Property Name As String
    Public MustOverride WriteOnly Property OrderTotal As Decimal
    Public MustOverride WriteOnly Property OrderDescription As String
  End Class
End Namespace

ASCX Header:

<%@ Control Language="VB" ClassName="_Header" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!--
  See https://www.campaignmonitor.com/blog/post/3317/ for discussion of DocType in HTML Email
-->

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <asp:PlaceHolder ID="plcStyler" runat="server"></asp:PlaceHolder>
</head>
<body>

ASCX Footer:

<%@ Control Language="VB" ClassName="_Footer" %>

</body>
</html>

ASCX Template:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="PurchaseReceipt.ascx.vb" Inherits="PurchaseReceipt" %>

<%@ Register Src="_Header.ascx" TagName="Header" TagPrefix="uc" %>
<%@ Register Src="_Footer.ascx" TagName="Footer" TagPrefix="uc" %>

<uc:Header ID="ctlHeader" runat="server" />

  <p>Name: <asp:Label ID="lblName" runat="server"></asp:Label></p>
  <p>Order Total: <asp:Label ID="lblOrderTotal" runat="server"></asp:Label></p>
  <p>Order Description: <asp:Label ID="lblOrderDescription" runat="server"></asp:Label></p>

<uc:Footer ID="ctlFooter" runat="server" />

ASCX Template CodeFile:

Partial Class PurchaseReceipt
  Inherits MailTemplates.PurchaseReceipt

  Public Overrides WriteOnly Property Name As String
    Set(Value As String)
      lblName.Text = Value
    End Set
  End Property



  Public Overrides WriteOnly Property OrderTotal As Decimal
    Set(Value As Boolean)
      lblOrderTotal.Text = Value
    End Set
  End Property



  Public Overrides WriteOnly Property OrderDescription As Decimal
    Set(Value As Boolean)
      lblOrderDescription.Text = Value
    End Set
  End Property
End Class

Helpers:

'
' FindNestedControl helpers based on tip by @andleer
' at http://stackoverflow.com/questions/619449/
'

Public Module Helpers
  <Extension>
  Public Function AllControls(Control As Control) As List(Of Control)
    Return Control.Controls.Flatten
  End Function



  <Extension>
  Public Function FindNestedControl(Control As Control, Id As String) As Control
    Return Control.Controls.Flatten(Function(C) C.ID = Id).SingleOrDefault
  End Function



  <Extension>
  Public Function FindNestedControl(Control As Control, Type As Type) As Control
    Return Control.Controls.Flatten(Function(C) C.GetType = Type).SingleOrDefault
  End Function



  <Extension>
  Public Function Flatten(Controls As ControlCollection) As List(Of Control)
    Flatten = New List(Of Control)

    Controls.Traverse(Sub(Control) Flatten.Add(Control))
  End Function


  <Extension>
  Public Function Flatten(Controls As ControlCollection, Predicate As Func(Of Control, Boolean)) As List(Of Control)
    Flatten = New List(Of Control)

    Controls.Traverse(Sub(Control)
                        If Predicate(Control) Then
                          Flatten.Add(Control)
                        End If
                      End Sub)
  End Function



  <Extension>
  Public Sub Traverse(Controls As ControlCollection, Action As Action(Of Control))
    Controls.Cast(Of Control).ToList.ForEach(Sub(Control As Control)
                                               Action(Control)

                                               If Control.HasControls Then
                                                 Control.Controls.Traverse(Action)
                                               End If
                                             End Sub)
  End Sub



  <Extension()>
  Public Function ToFormat(Template As String, ParamArray Values As Object()) As String
    Return String.Format(Template, Values)
  End Function



  <Extension()>
  Public Function ToHtml(Control As Control) As String
    Dim oSb As StringBuilder

    oSb = New StringBuilder

    Using oSw As New StringWriter(oSb)
      Using oTw As New HtmlTextWriter(oSw)
        Control.RenderControl(oTw)
        Return oSb.ToString
      End Using
    End Using
  End Function
End Module



Namespace Controls
  Public Class Styler
    Inherits LiteralControl

    Public Sub New(FileName As String)
      Dim _
        sFileName,
        sFilePath As String

      sFileName = Path.GetFileNameWithoutExtension(FileName)
      sFilePath = HttpContext.Current.Server.MapPath("~/Styles/{0}.css".ToFormat(sFileName))

      If File.Exists(sFilePath) Then
        Me.Text = "{0}<style type=""text/css"">{0}{1}</style>{0}".ToFormat(vbCrLf, File.ReadAllText(sFilePath))
      Else
        Me.Text = String.Empty
      End If
    End Sub
  End Class
End Namespace



Public Class Utils
  Public Shared Sub SendMail(Recipient As MailAddress, Subject As String, HtmlBody As String)
    Using oMessage As New MailMessage
      oMessage.To.Add(Recipient)
      oMessage.IsBodyHtml = True
      oMessage.Subject = Subject.Trim
      oMessage.Body = HtmlBody.Trim

      Using oClient As New SmtpClient
        oClient.Send(oMessage)
      End Using
    End Using
  End Sub
End Class

Java 8 Lambda filter by Lists

I would like share an example to understand the usage of stream().filter

Code Snippet: Sample program to identify even number.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public void fetchEvenNumber(){
        List<Integer> numberList = new ArrayList<>();
        numberList.add(10);
        numberList.add(11);
        numberList.add(12);
        numberList.add(13);
        numberList.add(14);
        numberList.add(15);

        List<Integer> evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());
        System.out.println(evenNumberListObj);
}

Output will be : [10, 12, 14]

List evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());

numberList: it is an ArrayList object contains list of numbers.

java.util.Collection.stream() : stream() will get the stream of collection, which will return the Stream of Integer.

filter: Returns a stream that match the given predicate. i.e based on given condition (i -> i%2 != 0) returns the matching stream.

collect: whatever the stream of Integer filter based in the filter condition, those integer will be put in a list.

How do you remove duplicates from a list whilst preserving order?

For no hashable types (e.g. list of lists), based on MizardX's:

def f7_noHash(seq)
    seen = set()
    return [ x for x in seq if str( x ) not in seen and not seen.add( str( x ) )]

Bootstrap select dropdown list placeholder

<option value="" defaultValue disabled> Something </option>

you can replace defaultValue with selected but that would give warning.

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

Preloading images with jQuery

function preload(imgs) {
    $(imgs).each(function(index, value) {
        $('<img />').attr('src', value).appendTo('body').css('display', 'none');
    });
}

.attr('src',value) not .attr('src',this)

just to point it out :)

Operator overloading on class templates

// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);


// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
  // ...
  return *this;
}

This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.

Edit: Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.

More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.

How to stop asynctask thread in android?

declare your asyncTask in your activity:

private YourAsyncTask mTask;

instantiate it like this:

mTask = new YourAsyncTask().execute();

kill/cancel it like this:

mTask.cancel(true);

Bootstrap 3 Slide in Menu / Navbar on Mobile

Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:

_x000D_
_x000D_
$('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
  $navMenuCont = $($(this).data('target'));_x000D_
  $navMenuCont.animate({_x000D_
    'width': 'toggle'_x000D_
  }, 350);_x000D_
  $(".menu-overlay").fadeIn(500);_x000D_
});_x000D_
_x000D_
$(".menu-overlay").click(function(event) {_x000D_
  $(".navbar-toggle").trigger("click");_x000D_
  $(".menu-overlay").fadeOut(500);_x000D_
});_x000D_
_x000D_
// if ($(window).width() >= 767) {_x000D_
//     $('ul.nav li.dropdown').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
//     $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
_x000D_
//     $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
//         event.preventDefault();_x000D_
//         event.stopPropagation();_x000D_
//         $(this).parent().siblings().removeClass('open');_x000D_
//         $(this).parent().toggleClass('open');_x000D_
//         $('b', this).toggleClass("caret caret-up");_x000D_
//     });_x000D_
// }_x000D_
_x000D_
// $(window).resize(function() {_x000D_
//     if( $(this).width() >= 767) {_x000D_
//         $('ul.nav li.dropdown').hover(function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//         }, function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//         });_x000D_
//     }_x000D_
// });_x000D_
_x000D_
var windowWidth = $(window).width();_x000D_
if (windowWidth > 767) {_x000D_
  // $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
  //     event.preventDefault();_x000D_
  //     event.stopPropagation();_x000D_
  //     $(this).parent().siblings().removeClass('open');_x000D_
  //     $(this).parent().toggleClass('open');_x000D_
  //     $('b', this).toggleClass("caret caret-up");_x000D_
  // });_x000D_
_x000D_
  $('ul.nav li.dropdown').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
  $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
if (windowWidth < 767) {_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
_x000D_
// $('.dropdown a').append('Some text');
_x000D_
@media only screen and (max-width: 767px) {_x000D_
  #slide-navbar-collapse {_x000D_
    position: fixed;_x000D_
    top: 0;_x000D_
    left: 15px;_x000D_
    z-index: 999999;_x000D_
    width: 280px;_x000D_
    height: 100%;_x000D_
    background-color: #f9f9f9;_x000D_
    overflow: auto;_x000D_
    bottom: 0;_x000D_
    max-height: inherit;_x000D_
  }_x000D_
  .menu-overlay {_x000D_
    display: none;_x000D_
    background-color: #000;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    opacity: 0.5;_x000D_
    filter: alpha(opacity=50);_x000D_
    /* IE7 & 8 */_x000D_
    position: fixed;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    z-index: 49;_x000D_
  }_x000D_
  .navbar-fixed-top {_x000D_
    position: initial !important;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu {_x000D_
    background-color: #ffffff;_x000D_
  }_x000D_
  ul.nav.navbar-nav li {_x000D_
    border-bottom: 1px solid #eee;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
  .navbar-nav .open .dropdown-menu>li>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
}_x000D_
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
  margin-top: -1px;_x000D_
}_x000D_
_x000D_
li.dropdown a {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 5px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 10px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
ul.dropdown-menu li {_x000D_
  border-bottom: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.dropdown-menu {_x000D_
  padding: 0px;_x000D_
  margin: 0px;_x000D_
  border: none !important;_x000D_
}_x000D_
_x000D_
li.dropdown.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
li.dropdown>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
.navbar-default .navbar-nav>li>a {_x000D_
  font-weight: bold !important;_x000D_
  padding: 10px 20px 10px 15px;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 9px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 767px) {_x000D_
  li.dropdown-submenu>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
  li.dropdown>a:before {_x000D_
    content: "\f107";_x000D_
    font-family: FontAwesome;_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 12px;_x000D_
    font-size: 15px;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
  <head>_x000D_
    <title>Bootstrap Example</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <nav class="navbar navbar-default navbar-fixed-top">_x000D_
      <div class="container-fluid">_x000D_
        <!-- Brand and toggle get grouped for better mobile display -->_x000D_
        <div class="navbar-header">_x000D_
          <button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
          <a class="navbar-brand" href="#">Brand</a>_x000D_
        </div>_x000D_
        <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
        <div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
          <ul class="nav navbar-nav">_x000D_
            <li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
                <li><a href="#">One more separated link</a></li>_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
          </ul>_x000D_
          <ul class="nav navbar-nav navbar-right">_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.navbar-collapse -->_x000D_
      </div>_x000D_
      <!-- /.container-fluid -->_x000D_
    </nav>_x000D_
    <div class="menu-overlay"></div>_x000D_
    <div class="col-md-12">_x000D_
      <h1>Resize the window to see the result</h1>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference JS fiddle

What is the correct XPath for choosing attributes that contain "foo"?

John C is the closest, but XPath is case sensitive, so the correct XPath would be:

/bla/a[contains(@prop, 'Foo')]

What does -z mean in Bash?

-z

string is null, that is, has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

Reference excel worksheet by name?

To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.

Access cell value of datatable

string abc= dt.Rows[0]["column name"].ToString();

Python - How to cut a string in Python?

s[0:"s".index("&")]

what does this do:

  • take a slice from the string starting at index 0, up to, but not including the index of &in the string.

How to make matrices in Python?

I got a simple fix to this by casting the lists into strings and performing string operations to get the proper print out of the matrix.

Creating the function

By creating a function, it saves you the trouble of writing the for loop every time you want to print out a matrix.

def print_matrix(matrix):
    for row in matrix:
        new_row = str(row)
        new_row = new_row.replace(',','')
        new_row = new_row.replace('[','')
        new_row = new_row.replace(']','')
        print(new_row)

Examples

Example of a 5x5 matrix with 0 as every entry:

>>> test_matrix = [[0] * 5 for i in range(5)]
>>> print_matrix(test_matrix)
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 

Example of a 2x3 matrix with 0 as every entry:

>>> test_matrix = [[0] * 3 for i in range(2)]
>>> print_matrix(test_matrix)
0 0 0
0 0 0

EDIT

If you want to make it print:

A A A A A
B B B B B
C C C C C
D D D D D 
E E E E E

I suggest you just change the way you enter your data into your lists within lists. In my method, each list within the larger list represents a line in the matrix, not columns.

Grep to find item in Perl array

You can also check single value in multiple arrays like,

if (grep /$match/, @array, @array_one, @array_two, @array_Three)
{
    print "found it\n";
}

How do I specify the JDK for a GlassFish domain?

Had the same problem in my IntelliJ 17 after adding fresh glassfish 4.1.

I had set my JAVA_HOME environment variable as follow:

echo %JAVA_HOME%
C:\Java\jdk1.8.0_121\

Then opened %GLASSFISH_HOME%\glassfish\config\asenv.bat

And just added and the end of the file:

set AS_JAVA=%JAVA_HOME%

Then Glassfish started without problems.

Can scripts be inserted with innerHTML?

Yes you can, but you have to do it outside of the DOM and the order has to be right.

var scr = '<scr'+'ipt>alert("foo")</scr'+'ipt>';
window.onload = function(){
    var n = document.createElement("div");
    n.innerHTML = scr;
    document.body.appendChild(n);
}

...will alert 'foo'. This won't work:

document.getElementById("myDiv").innerHTML = scr;

And even this won't work, because the node is inserted first:

var scr = '<scr'+'ipt>alert("foo")</scr'+'ipt>';
window.onload = function(){
    var n = document.createElement("div");
    document.body.appendChild(n);
    n.innerHTML = scr;  
}

Guid is all 0's (zeros)?

Lessons to learn from this:

1) Guid is a value type, not a reference type.

2) Calling the default constructor new S() on any value type always gives you back the all-zero form of that value type, whatever it is. It is logically the same as default(S).

How can I add a column that doesn't allow nulls in a Postgresql database?

this query will auto-update the nulls

ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) DEFAULT 'whatever' NOT NULL;

Execute the setInterval function without delay the first time

Here's a simple version for novices without all the messing around. It just declares the function, calls it, then starts the interval. That's it.

_x000D_
_x000D_
//Declare your function here_x000D_
function My_Function(){_x000D_
  console.log("foo");_x000D_
}    _x000D_
_x000D_
//Call the function first_x000D_
My_Function();_x000D_
_x000D_
//Set the interval_x000D_
var interval = window.setInterval( My_Function, 500 );
_x000D_
_x000D_
_x000D_

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

The problem is that you compiled the code with java 13 (class file 57), and the java runtime is set to java 8 (class file 52).

Assuming you have the JRE 13 installed in your local system, you could change your runtime from 52 to 57. That you can do with the plugin Choose Runtime. To install it go to File/Settings/Plugins

enter image description here

Once installed go to Help/Find Action, type "runtime" and select the jre 13 from the dropdown menu.

enter image description here

How to configure CORS in a Spring Boot + Spring Security application?

If you are using Spring Security, you can do the following to ensure that CORS requests are handled first:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

See Spring 4.2.x CORS for more information.

Without Spring Security this will work:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
        }
    };
}

Javascript: How to pass a function with string parameters as a parameter to another function

Me, I'd do it something like this:

HTML:

onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"

JS:

function myfunction(params)
{
  var path = params.path;

  /* do stuff */

  // on ok condition 
  params.ok(params.okArgs);

  // on cancel condition
  params.cancel(params.cancelArgs);  
}

But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.

Get difference between 2 dates in JavaScript?

var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

I've seen these 3 errors for pod command in terminal

pod install

[!] The MY_APP [Debug/Release] target overrides the HEADER_SEARCH_PATHS ...
[!] The MY_APP [Debug/Release] target overrides the OTHER_LDFLAGS ...
[!] The MY_APP [Debug/Release] target overrides the GCC_PREPROCESSOR_DEFINITIONS ...

All these 3 errors would be gone by adding $(inherited) to

  1. Header Search Paths
  2. Other Linker Flags
  3. Preprocessor Macros

in Project -> Target -> Build Settings

And now the command would run without giving any errors

pod install

Python Finding Prime Factors

The code is wrong with 100. It should check case i * i = n:

I think it should be:

while i * i <= n:
    if i * i = n:
        n = i
        break

    while n%i == 0:
        n = n / i
    i = i + 1

print (n)

Python: Fetch first 10 results from a list

The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice function:

from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
    print item

If "0" then leave the cell blank

An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.

=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))

Understanding REST: Verbs, error codes, and authentication

Verbose, but copied from the HTTP 1.1 method specification at http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

9.3 GET

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.

The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client.

The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in section 13.

See section 15.1.3 for security considerations when used for forms.

9.5 POST

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  - Annotation of existing resources;
  - Posting a message to a bulletin board, newsgroup, mailing list,
    or similar group of articles;
  - Providing a block of data, such as the result of submitting a
    form, to a data-handling process;
  - Extending a database through an append operation.

The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a database.

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).

Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent to retrieve a cacheable resource.

POST requests MUST obey the message transmission requirements set out in section 8.2.

See section 15.1.3 for security considerations.

9.6 PUT

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

A single resource MAY be identified by many different URIs. For example, an article might have a URI for identifying "the current version" which is separate from the URI identifying each particular version. In this case, a PUT request on a general URI might result in several other URIs being defined by the origin server.

HTTP/1.1 does not define how a PUT method affects the state of an origin server.

PUT requests MUST obey the message transmission requirements set out in section 8.2.

Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request SHOULD be applied to the resource created or modified by the PUT.

9.7 DELETE

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

C# removing items from listbox

Your question implies that you're willing to modify other parts of the code, even though you can't modify the SQL Statement itself. Instead of removing them from the ListBox Collection, it might be easier to just exclude them in the first place. This code assumes you're connecting to SQL Server:

void PopulateListBox(ListBox listToPopulate)
{
    SqlConnection conn = new SqlConnection("myConnectionString"); 
    SqlCommand cmd = new SqlCommand("spMyStoredProc", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        string item = reader.GetString(0); //or whatever column is displayed in the list
        if (!item.Contains("OBJECT_"))
            listToPopulate.Items.Add(item); 
    }
}

But if you're absolutely determined to do it this way you should check out this question on modifying an enumerable collection while iterating through it.

UTL_FILE.FOPEN() procedure not accepting path for directory?

You need to have your DBA modify the init.ora file, adding the directory you want to access to the 'utl_file_dir' parameter. Your database instance will then need to be stopped and restarted because init.ora is only read when the database is brought up.

You can view (but not change) this parameter by running the following query:

SELECT *
  FROM V$PARAMETER
  WHERE NAME = 'utl_file_dir'

Share and enjoy.

What does request.getParameter return?

Per the Javadoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse into the URL to enable logging, without needing to specify &log=true. In this case, the value will be an empty String ("").

What is the purpose of global.asax in asp.net

MSDN has an outline of the purpose of the global.asax file.

Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):

  • Application_Start
  • Application_End
  • Session_Start
  • Session_End
  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_Error

There are other events that you can also hook into, such as "LogRequest".

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.

You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.

To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').

For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)

How to find longest string in the table column data

You can:

SELECT CR 
FROM table1 
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)

Having just recieved an upvote more than a year after posting this, I'd like to add some information.

  • This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not desired.
  • This query must probably read the table twice: a full table scan to get the maximum length and another full table scan to get all values of that length. These operations, however, are very simple operations and hence rather fast. With a TOP 1 query a DBMS reads all records from the table and then sorts them. So the table is read only once, but a sort operation on a whole table is quite some task and can be very slow on large tables.
  • One would usually add DISTINCT to my query (SELECT DISTINCT CR FROM ...), so as to get every value just once. That would be a sort operation, but only on the few records already found. Again, no big deal.
  • If the string lengths have to be dealt with quite often, one might think of creating a computed column (calculated field) for it. This is available as of Ms Access 2010. But reading up on this shows that you cannot index calculated fields in MS Access. As long as this holds true, there is hardly any benefit from them. Applying LEN on the strings is usually not what makes such queries slow.

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

How to uninstall after "make install"

Method #1 (make uninstall)

Step 1: You only need to follow this step if you've deleted/altered the build directory in any way: Download and make/make install using the exact same procedure as you did before.

Step 2: try make uninstall.

cd $SOURCE_DIR 
sudo make uninstall

If this succeeds you are done. If you're paranoid you may also try the steps of "Method #3" to make sure make uninstall didn't miss any files.

Method #2 (checkinstall -- only for debian based systems)

Overview of the process

In debian based systems (e.g. Ubuntu) you can create a .deb package very easily by using a tool named checkinstall. You then install the .deb package (this will make your debian system realize that the all parts of your package have been indeed installed) and finally uninstall it to let your package manager properly cleanup your system.

Step by step

sudo apt-get -y install checkinstall
cd $SOURCE_DIR 
sudo checkinstall

At this point checkinstall will prompt for a package name. Enter something a bit descriptive and note it because you'll use it in a minute. It will also prompt for a few more data that you can ignore. If it complains about the version not been acceptable just enter something reasonable like 1.0. When it completes you can install and finally uninstall:

sudo dpkg -i $PACKAGE_NAME_YOU_ENTERED 
sudo dpkg -r $PACKAGE_NAME_YOU_ENTERED

Method #3 (install_manifest.txt)

If a file install_manifest.txt exists in your source dir it should contain the filenames of every single file that the installation created.

So first check the list of files and their mod-time:

cd $SOURCE_DIR 
sudo xargs -I{} stat -c "%z %n" "{}" < install_manifest.txt

You should get zero errors and the mod-times of the listed files should be on or after the installation time. If all is OK you can delete them in one go:

cd $SOURCE_DIR 
mkdir deleted-by-uninstall
sudo xargs -I{} mv -t deleted-by-uninstall "{}" < install_manifest.txt

User Merlyn Morgan-Graham however has a serious notice regarding this method that you should keep in mind (copied here verbatim): "Watch out for files that might also have been installed by other packages. Simply deleting these files [...] could break the other packages.". That's the reason that we've created the deleted-by-uninstall dir and moved files there instead of deleting them.


99% of this post existed in other answers. I just collected everything useful in a (hopefully) easy to follow how-to and tried to give extra attention to important details (like quoting xarg arguments and keeping backups of deleted files).

Cannot assign requested address using ServerSocket.socketBind

if your are using server, there's "public network IP" and "internal network IP". Use the "internal network IP" in your file /etc/hosts and "public network IP" in your code. if you use "public network IP" in your file /etc/hosts then you will get this error.

How to deal with SettingWithCopyWarning in Pandas

Followup beginner question / remark

Maybe a clarification for other beginners like me (I come from R which seems to work a bit differently under the hood). The following harmless-looking and functional code kept producing the SettingWithCopy warning, and I couldn't figure out why. I had both read and understood the issued with "chained indexing", but my code doesn't contain any:

def plot(pdb, df, title, **kw):
    df['target'] = (df['ogg'] + df['ugg']) / 2
    # ...

But then, later, much too late, I looked at where the plot() function is called:

    df = data[data['anz_emw'] > 0]
    pixbuf = plot(pdb, df, title)

So "df" isn't a data frame but an object that somehow remembers that it was created by indexing a data frame (so is that a view?) which would make the line in plot()

 df['target'] = ...

equivalent to

 data[data['anz_emw'] > 0]['target'] = ...

which is a chained indexing. Did I get that right?

Anyway,

def plot(pdb, df, title, **kw):
    df.loc[:,'target'] = (df['ogg'] + df['ugg']) / 2

fixed it.

Parse RSS with jQuery

The jQuery-rss project is pretty lightweight and doesn't impose any particular styling.

The syntax can be as simple as

$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")

See a working example at http://jsfiddle.net/jhfrench/AFHfn/

How to show text on image when hovering?

It's simple. Wrap the image and the "appear on hover" description in a div with the same dimensions of the image. Then, with some CSS, order the description to appear while hovering that div.

_x000D_
_x000D_
/* quick reset */_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
}_x000D_
_x000D_
/* relevant styles */_x000D_
.img__wrap {_x000D_
  position: relative;_x000D_
  height: 200px;_x000D_
  width: 257px;_x000D_
}_x000D_
_x000D_
.img__description {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  background: rgba(29, 106, 154, 0.72);_x000D_
  color: #fff;_x000D_
  visibility: hidden;_x000D_
  opacity: 0;_x000D_
_x000D_
  /* transition effect. not necessary */_x000D_
  transition: opacity .2s, visibility .2s;_x000D_
}_x000D_
_x000D_
.img__wrap:hover .img__description {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div class="img__wrap">_x000D_
  <img class="img__img" src="http://placehold.it/257x200.jpg" />_x000D_
  <p class="img__description">This image looks super neat.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

A nice fiddle: https://jsfiddle.net/govdqd8y/

Replace image src location using CSS

You can use a background image

_x000D_
_x000D_
.application-title img {_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
  box-sizing:border-box;_x000D_
  padding-left: 200px;_x000D_
  /*width of the image*/_x000D_
  background: url(http://lorempixel.com/200/200/city/2) left top no-repeat;_x000D_
}
_x000D_
<div class="application-title">_x000D_
  <img src="http://lorempixel.com/200/200/city/1/">_x000D_
</div><br />_x000D_
Original Image: <br />_x000D_
_x000D_
<img src="http://lorempixel.com/200/200/city/1/">
_x000D_
_x000D_
_x000D_

Mocking member variables of a class using Mockito

This is not possible if you can't change your code. But I like dependency injection and Mockito supports it:

public class First {    
    @Resource
    Second second;

    public First() {
        second = new Second();
    }

    public String doSecond() {
        return second.doSecond();
    }
}

Your test:

@RunWith(MockitoJUnitRunner.class)
public class YourTest {
   @Mock
   Second second;

   @InjectMocks
   First first = new First();

   public void testFirst(){
      when(second.doSecond()).thenReturn("Stubbed Second");
      assertEquals("Stubbed Second", first.doSecond());
   }
}

This is very nice and easy.

Split string into individual words Java

A regex can also be used to split words.

\w can be used to match word characters ([A-Za-z0-9_]), so that punctuation is removed from the results:

String s = "I want to walk my dog, and why not?";
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Outputs:

I
want
to
walk
my
dog
and
why
not

See Java API documentation for Pattern

.Net: How do I find the .NET version?

My god, so much mess to find version of installed .net framework?

Windows > Search > Visual Studio Installer > for installed version of VS, tap on More > Modify > Individual Components and see it there:

enter image description here

How to print to stderr in Python?

The same applies to stdout:

print 'spam'
sys.stdout.write('spam\n')

As stated in the other answers, print offers a pretty interface that is often more convenient (e.g. for printing debug information), while write is faster and can also be more convenient when you have to format the output exactly in certain way. I would consider maintainability as well:

  1. You may later decide to switch between stdout/stderr and a regular file.

  2. print() syntax has changed in Python 3, so if you need to support both versions, write() might be better.

php delete a single file in directory

If you want to delete a single file, you must, as you found out, use the unlink() function.

That function will delete what you pass it as a parameter : so, it's up to you to pass it the path to the file that it must delete.


For example, you'll use something like this :

unlink('/path/to/dir/filename');

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

Align two divs horizontally side by side center to the page using bootstrap css

The response provided by Ranveer (second answer above) absolutely does NOT work.

He says to use col-xx-offset-#, but that is not how offsets are used.

If you wasted your time trying to use col-xx-offset-#, as I did based on his answer, the solution is to use offset-xx-#.

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

Subtract one day from datetime

To simply subtract one day from todays date:

Select DATEADD(day,-1,GETDATE())

(original post used -7 and was incorrect)

CSS: Set Div height to 100% - Pixels

I added the height property to the body and html tags.

HTML:

<body>
<div id="wrapper">
 <div id="header">header</div>
 <div id="content">content</div>
</div>

CSS:

html, body
{
    height: 100%;
    min-height: 100%;
    margin: 0;
    padding: 0;
}
#wrapper
{
    height: 100%;
    min-height: 100%;
}
#header
{
    height: 111px;
}

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

What's the difference between Visual Studio Community and other, paid versions?

All these answers are partially wrong.

Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.

Even the lack of TFS support is not true. I can verify it is present and works perfectly.

EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)

EDIT: Even over the revenue limit, open source is still free.

Jquery: How to check if the element has certain css class/style

CSS Styles are key-value pairs, not just "tags". By default, each element has a full set of CSS styles assigned to it, most of them is implicitly using the browser defaults and some of them is explicitly redefined in CSS stylesheets.

To get the value assigned to a particular CSS entry of an element and compare it:

if ($('#yourElement').css('position') == 'absolute')
{
   // true
}

If you didn't redefine the style, you will get the browser default for that particular element.

Generate ER Diagram from existing MySQL database, created for CakePHP

If you don't want to install MySQL workbench, and are looking for an online tool, this might help: http://ondras.zarovi.cz/sql/demo/

I use it quite often to create simple DB schemas for various apps I build.

How can I de-install a Perl module installed via `cpan`?

You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Best way to format if statement with multiple conditions

Other answers explain why the first option is normally the best. But if you have multiple conditions, consider creating a separate function (or property) doing the condition checks in option 1. This makes the code much easier to read, at least when you use good method names.

if(MyChecksAreOk()) { Code to execute }

...

private bool MyChecksAreOk()
{ 
    return ConditionOne && ConditionTwo && ConditionThree;
}

It the conditions only rely on local scope variables, you could make the new function static and pass in everything you need. If there is a mix, pass in the local stuff.

Removing spaces from string

String  input = EditTextinput.getText().toString();
input = input.replace(" ", "");

Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:

input = input.trim();

How to count how many values per level in a given factor?

Use the package plyr with lapply to get frequencies for every value (level) and every variable (factor) in your data frame.

library(plyr)
lapply(df, count)

JBoss default password

Step 1:

jmx-console-users.properties 
admin=admin

Step 2:

jmx-console-roles.properties 
admin=JBossAdmin,HttpInvoker

Step 3: Restart or start the JBoss instance.

Now you should good to go...

Go to the jmx console, enter JBoss login URL, then enter admin as username and admin password.

Enable & Disable a Div and its elements in Javascript

You should be able to set these via the attr() or prop() functions in jQuery as shown below:

jQuery (< 1.7):

// This will disable just the div
$("#dcacl").attr('disabled','disabled');

or

// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");

jQuery (>= 1.7):

// This will disable just the div
$("#dcacl").prop('disabled',true);

or

// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);

or

//  disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);

Javascript:

// This will disable just the div
document.getElementById("dcalc").disabled = true;

or

// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
     nodes[i].disabled = true;
}

Install Node.js on Ubuntu

Really simple:

sudo apt install nodejs

And then type:

nodejs

to use it.

How to set timer in android?

If anyone is interested, I started playing around with creating a standard object to run on an activities UI thread. Seems to work ok. Comments welcome. I'd love this to be available on the layout designer as a component to drag onto an Activity. Can't believe something like that doesn't already exist.

package com.example.util.timer;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;

public class ActivityTimer {

    private Activity m_Activity;
    private boolean m_Enabled;
    private Timer m_Timer;
    private long m_Delay;
    private long m_Period;
    private ActivityTimerListener m_Listener;
    private ActivityTimer _self;
    private boolean m_FireOnce;

    public ActivityTimer() {
        m_Delay = 0;
        m_Period = 100;
        m_Listener = null;
        m_FireOnce = false;
        _self = this;
    }

    public boolean isEnabled() {
        return m_Enabled;
    }

    public void setEnabled(boolean enabled) {
        if (m_Enabled == enabled)
            return;

        // Disable any existing timer before we enable a new one
        Disable();

        if (enabled) {
            Enable();
        }
    }

    private void Enable() {
        if (m_Enabled)
            return;

        m_Enabled = true;

        m_Timer = new Timer();
        if (m_FireOnce) {
            m_Timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    OnTick();
                }
            }, m_Delay);
        } else {
            m_Timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    OnTick();
                }
            }, m_Delay, m_Period);
        }
    }

    private void Disable() {
        if (!m_Enabled)
            return;

        m_Enabled = false;

        if (m_Timer == null)
            return;

        m_Timer.cancel();
        m_Timer.purge();
        m_Timer = null;
    }

    private void OnTick() {
        if (m_Activity != null && m_Listener != null) {
            m_Activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    m_Listener.OnTimerTick(m_Activity, _self);
                }
            });
        }
        if (m_FireOnce)
            Disable();
    }

    public long getDelay() {
        return m_Delay;
    }

    public void setDelay(long delay) {
        m_Delay = delay;
    }

    public long getPeriod() {
        return m_Period;
    }

    public void setPeriod(long period) {
        if (m_Period == period)
            return;
        m_Period = period;
    }

    public Activity getActivity() {
        return m_Activity;
    }

    public void setActivity(Activity activity) {
        if (m_Activity == activity)
            return;
        m_Activity = activity;
    }

    public ActivityTimerListener getActionListener() {
        return m_Listener;
    }

    public void setActionListener(ActivityTimerListener listener) {
        m_Listener = listener;
    }

    public void start() {
        if (m_Enabled)
            return;
        Enable();
    }

    public boolean isFireOnlyOnce() {
        return m_FireOnce;
    }

    public void setFireOnlyOnce(boolean fireOnce) {
        m_FireOnce = fireOnce;
    }
}

In the activity, I have this onStart:

@Override
protected void onStart() {
    super.onStart();

    m_Timer = new ActivityTimer();
    m_Timer.setFireOnlyOnce(true);
    m_Timer.setActivity(this);
    m_Timer.setActionListener(this);
    m_Timer.setDelay(3000);
    m_Timer.start();
}

Convert month int to month name

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
    Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3) 
    + "-" 
    + Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

Ruby - test for array

Also consider using Array(). From the Ruby Community Style Guide:

Use Array() instead of explicit Array check or [*var], when dealing with a variable you want to treat as an Array, but you're not certain it's an array.

# bad
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }

# bad (always creates a new Array instance)
[*paths].each { |path| do_something(path) }

# good (and a bit more readable)
Array(paths).each { |path| do_something(path) }

Is there a way to change the spacing between legend items in ggplot2?

Use any of these

legend.spacing = unit(1,"cm")
legend.spacing.x = unit(1,"cm")
legend.spacing.y = unit(1,"cm")

PYTHONPATH on Linux

  1. PYTHONPATH is an environment variable
  2. Yes (see https://unix.stackexchange.com/questions/24802/on-which-unix-distributions-is-python-installed-as-part-of-the-default-install)
  3. /usr/lib/python2.7 on Ubuntu
  4. you shouldn't install packages manually. Instead, use pip. When a package isn't in pip, it usually has a setuptools setup script which will install the package into the proper location (see point 3).
  5. if you use pip or setuptools, then you don't need to set PYTHONPATH explicitly

If you look at the instructions for pyopengl, you'll see that they are consistent with points 4 and 5.

Remove duplicates from a list of objects based on property in Java 8

You can get a stream from the List and put in in the TreeSet from which you provide a custom comparator that compares id uniquely.

Then if you really need a list you can put then back this collection into an ArrayList.

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

...
List<Employee> unique = employee.stream()
                                .collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingInt(Employee::getId))),
                                                           ArrayList::new));

Given the example:

List<Employee> employee = Arrays.asList(new Employee(1, "John"), new Employee(1, "Bob"), new Employee(2, "Alice"));

It will output:

[Employee{id=1, name='John'}, Employee{id=2, name='Alice'}]

Another idea could be to use a wrapper that wraps an employee and have the equals and hashcode method based with its id:

class WrapperEmployee {
    private Employee e;

    public WrapperEmployee(Employee e) {
        this.e = e;
    }

    public Employee unwrap() {
        return this.e;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        WrapperEmployee that = (WrapperEmployee) o;
        return Objects.equals(e.getId(), that.e.getId());
    }

    @Override
    public int hashCode() {
        return Objects.hash(e.getId());
    }
}

Then you wrap each instance, call distinct(), unwrap them and collect the result in a list.

List<Employee> unique = employee.stream()
                                .map(WrapperEmployee::new)
                                .distinct()
                                .map(WrapperEmployee::unwrap)
                                .collect(Collectors.toList());

In fact, I think you can make this wrapper generic by providing a function that will do the comparison:

public class Wrapper<T, U> {
    private T t;
    private Function<T, U> equalityFunction;

    public Wrapper(T t, Function<T, U> equalityFunction) {
        this.t = t;
        this.equalityFunction = equalityFunction;
    }

    public T unwrap() {
        return this.t;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        @SuppressWarnings("unchecked")
        Wrapper<T, U> that = (Wrapper<T, U>) o;
        return Objects.equals(equalityFunction.apply(this.t), that.equalityFunction.apply(that.t));
    }

    @Override
    public int hashCode() {
        return Objects.hash(equalityFunction.apply(this.t));
    }
}

and the mapping will be:

.map(e -> new Wrapper<>(e, Employee::getId))

node.js execute system command synchronously

Native Node.js solution is:

const {execSync} = require('child_process');

const result = execSync('node -v'); //  this do the trick 

Just be aware that some commands returns Buffer instead of string. And if you need string just add encoding to execSync options:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8'});

... and it is also good to have timeout on sync exec:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8', timeout: 10000});

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

How can I configure my makefile for debug and release builds?

Note that you can also make your Makefile simpler, at the same time:

DEBUG ?= 1
ifeq (DEBUG, 1)
    CFLAGS =-g3 -gdwarf2 -DDEBUG
else
    CFLAGS=-DNDEBUG
endif

CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)

EXECUTABLE = output
OBJECTS = CommandParser.tab.o CommandParser.yy.o Command.o
LIBRARIES = -lfl

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CXX) -o $@ $^ $(LIBRARIES)

%.yy.o: %.l 
    flex -o $*.yy.c $<
    $(CC) -c $*.yy.c

%.tab.o: %.y
    bison -d $<
    $(CXX) -c $*.tab.c

%.o: %.cpp
    $(CXX) -c $<

clean:
    rm -f $(EXECUTABLE) $(OBJECTS) *.yy.c *.tab.c

Now you don't have to repeat filenames all over the place. Any .l files will get passed through flex and gcc, any .y files will get passed through bison and g++, and any .cpp files through just g++.

Just list the .o files you expect to end up with, and Make will do the work of figuring out which rules can satisfy the needs...

for the record:

  • $@ The name of the target file (the one before the colon)

  • $< The name of the first (or only) prerequisite file (the first one after the colon)

  • $^ The names of all the prerequisite files (space separated)

  • $* The stem (the bit which matches the % wildcard in the rule definition.

How to draw polygons on an HTML5 canvas?

Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.

Here is a full article on how it works and more.

// Defines a path for any regular polygon with the specified number of sides and radius, 
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
  if (sides < 3) return;
  var a = (Math.PI * 2)/sides;
  a = anticlockwise?-a:a;
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(startAngle);
  ctx.moveTo(radius,0);
  for (var i = 1; i < sides; i++) {
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
  }
  ctx.closePath();
  ctx.restore();
}

// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();

Is a URL allowed to contain a space?

Yes, the space is usually encoded to "%20" though. Any parameters that pass to a URL should be encoded, simply for safety reasons.

What is "git remote add ..." and "git push origin master"?

Update: note that the currently accepted answer perpetuates a common misunderstanding about the behaviour of git push, which hasn't been corrected despite a comment pointing it out.

Your summary of what remotes are - like a nickname for the URL of a repository - is correct.

So why does the URL not git://[email protected]/peter/first_app.git but in the other syntax -- what syntax is it? Why must it end with .git? I tried not using .git at the end and it works too. If not .git, what else can it be? The git at the beginner seems to be a user account on the git server?

The two URLs that you've mentioned indicate that two different transport protocols should be used. The one beginning with git:// is for the git protocol, which is usually only used for read-only access to repositories. The other one, [email protected]:peter/first_app.git, is one of the different ways of specifying access to a repository over SSH - this is the "scp-style syntax" described in the documentation. That the username in the scp-style syntax is git is because of the way that GitHub deals with identifying users - essentially that username is ignored, and the user is identified based on the SSH key-pair that they used to authenticate.

As for the verbosity of git push origin master, you've noticed that after the first push, you can then just do git push. This is because of a series of difficult-to-remember-but-generally-helpful defaults :)

  • If no remote is specified, the remote configured for the current branch (in remote.master.url in your case) is used. If that's not set up, then origin is used.
  • If there's no "refspec" (e.g. master, master:my-experiment, etc.) specified, then git defaults to pushing every local branch that has the same name as a branch on the remote. If you just have a branch called master in common between your repository and the remote one, that'll be the same as pushing your master to the remote master.

Personally, since I tend to have many topic branches (and often several remotes) I always use the form:

git push origin master

... to avoid accidentally pushing other branches.


In reply to your comments on one of the other answers, it sounds to me as if are learning about git in a top-down way very effectively - you've discovered that the defaults work, and your question is asking about why ;) To be more serious, git can be used essentially as simply as SVN, but knowing a bit about remotes and branches means you can use it much more flexibily and this can really change the way you work for the better. Your remark about a semester course makes me think of something Scott Chacon said in a podcast interview - students are taught about all kinds of basic tools in computer science and software engineering, but very rarely version control. Distributed version control systems such as git and Mercurial are now so important, and so flexible, that it would be worth teaching courses on them to give people a good grounding.

My view is that with git, this learning curve is absolutely worth it - working with lots of topic branches, merging them easily, and pushing and pulling them about between different repositories is fantastically useful once you become confident with the system. It's just unfortunate that:

  • The primary documentation for git is so hard to parse for newcomers. (Although I'd argue that if you Google for almost any git question, helpful tutorial material (or Stack Overflow answers :)) come up nowadays.)
  • There are a few odd behaviours in git that are hard to change now because many scripts may rely on them, but are confusing to people.

How to printf long long

First of all, %d is for a int

So %1.16lld makes no sense, because %d is an integer

That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

What you want to use is the type double, for calculating pi and then using %f or %1.16f.

Open files always in a new tab

enabling using GUI

go to Code -> Preferences -> Settings -> User -> Window -> New Window

here Open Files In New Window under drop down list select "on" that's it.

my VS Code version 1.38.1

How to Call a Function inside a Render in React/Jsx

The fix was at the accepted answer. Yet if someone wants to know why it worked and why the implementation in the SO question didn't work,

First, functions are first class objects in JavaScript. That means they are treated like any other variable. Function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Read more here.

So we use that variable to invoke the function by adding parentheses () at the end.

One thing, If you have a function that returns a funtion and you just need to call that returned function, you can just have double paranthesis when you call the outer function ()().

Resize a picture to fit a JLabel

The best and easy way for image resize using Java Swing is:

jLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource("/res/image.png")).getImage().getScaledInstance(200, 50, Image.SCALE_SMOOTH)));

For better display, identify the actual height & width of image and resize based on width/height percentage

Filling a List with all enum values in Java

private ComboBox gender;
private enum Selgender{Male,Famle};
ObservableList<Object> observableList  =FXCollections.observableArrayList(Selgender.values());

how to redirect to external url from c# controller

Use the Controller's Redirect() method.

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}

Update

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});

Set Date in a single line

Why don't you just write a simple utility method:

public final class DateUtils {
    private DateUtils() {
    }

    public static Calendar calendarFor(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
        return cal;
    }

    // ... maybe other utility methods
}

And then call that everywhere in the rest of your code:

Calendar cal = DateUtils.calendarFor(2010, Calendar.MAY, 21);

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

get size of json object

Consider using underscore.js. It will allow you to check the size i.e. like that:

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link

https://www.postgresql.org/docs/current/xfunc-sql.html

EX:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

JPA : How to convert a native query result set to POJO class collection

Not sure if this fits here, but I had similar question and found following simple solution/example for me:

private EntityManager entityManager;
...
    final String sql = " SELECT * FROM STORE "; // select from the table STORE
    final Query sqlQuery = entityManager.createNativeQuery(sql, Store.class);

    @SuppressWarnings("unchecked")
    List<Store> results = (List<Store>) sqlQuery.getResultList();

In my case I had to use SQL parts defined in Strings somewhere else, so I could not just use NamedNativeQuery.

Adding POST parameters before submit

PURE JavaScript:

Creating the XMLHttpRequest:

function getHTTPObject() {
    /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
       por lo que se puede copiar tal como esta aqui */
    var xmlhttp = false;
    /* No mas soporte para Internet Explorer
    try { // Creacion del objeto AJAX para navegadores no IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(nIE) {
        try { // Creacion del objet AJAX para IE
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(IE) {
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                xmlhttp = new XMLHttpRequest();
        }
    }
    */
    xmlhttp = new XMLHttpRequest();
    return xmlhttp; 
}

JavaScript function to Send the info via POST:

function sendInfo() {
    var URL = "somepage.html"; //depends on you
    var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
    console.log(Params);
    var ajax = getHTTPObject();     
    ajax.open("POST", URL, true); //True:Sync - False:ASync
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.setRequestHeader("Content-length", Params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = function() { 
        if (ajax.readyState == 4 && ajax.status == 200) {
            alert(ajax.responseText);
        } 
    }
    ajax.send(Params);
}

How can I compare time in SQL Server?

If you're using SQL Server 2008, you can do this:

WHERE CONVERT(time(0), startHour) >= CONVERT(time(0), @startTime)

Here's a full test:

DECLARE @tbEvents TABLE (
    timeEvent   int      IDENTITY,
    startHour   datetime
)

INSERT INTO @tbEvents (startHour) SELECT DATEADD(hh, 0, GETDATE())
INSERT INTO @tbEvents (startHour) SELECT DATEADD(hh, 1, GETDATE())
INSERT INTO @tbEvents (startHour) SELECT DATEADD(hh, 2, GETDATE())
INSERT INTO @tbEvents (startHour) SELECT DATEADD(hh, 3, GETDATE())
INSERT INTO @tbEvents (startHour) SELECT DATEADD(hh, 4, GETDATE())
INSERT INTO @tbEvents (startHour) SELECT DATEADD(hh, 5, GETDATE())

--SELECT * FROM @tbEvents

DECLARE @startTime  datetime

SET @startTime = DATEADD(mi, 65, GETDATE())

SELECT
    timeEvent,
    CONVERT(time(0), startHour)  AS 'startHour',
    CONVERT(time(0), @startTime) AS '@startTime'
FROM @tbEvents
WHERE CONVERT(time(0), startHour) >= CONVERT(time(0), @startTime)

Can we cast a generic object to a custom object type in javascript?

This borrows from a few other answers here but I thought it might help someone. If you define the following function on your custom object, then you have a factory function that you can pass a generic object into and it will return for you an instance of the class.

CustomObject.create = function (obj) {
    var field = new CustomObject();
    for (var prop in obj) {
        if (field.hasOwnProperty(prop)) {
            field[prop] = obj[prop];
        }
    }

    return field;
}

Use like this

var typedObj = CustomObject.create(genericObj);

Java ArrayList for integers

How about creating an ArrayList of a set amount of Integers?

The below method returns an ArrayList of a set amount of Integers.

public static ArrayList<Integer> createRandomList(int sizeParameter)
{
    // An ArrayList that method returns
    ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
    // Random Object helper
    Random randomHelper = new Random();
    
    for (int x = 0; x < sizeParameter; x++)
    {
        setIntegerList.add(randomHelper.nextInt());
    }   // End of the for loop
    
    return setIntegerList;
}

Upload artifacts to Nexus, without Maven

No need to use these commands .. you can directly use the nexus web Interface in order to upload your JAR using GAV parameters.

enter image description here

So it is very simple.

Windows 10 SSH keys

I'm running Microsoft Windows 10 Pro, Version 10.0.17763 Build 17763, and I see my .ssh folder easily at C:\Users\jrosario\.ssh without having to edit permissions or anything (though in File Explorer, I did select "Show hidden files, folders and drives"): enter image description here

The keys are stored in a text file named known_hosts, which looks roughly like this: enter image description here

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

Split String into an array of String

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}

Best way to change the background color for an NSView

In Swift 3, you can create an extension to do it:

extension NSView {
    func setBackgroundColor(_ color: NSColor) {
        wantsLayer = true
        layer?.backgroundColor = color.cgColor
    }
}

// how to use
btn.setBackgroundColor(NSColor.gray)

How to move columns in a MySQL table?

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;

Find an element in DOM based on an attribute value

FindByAttributeValue("Attribute-Name", "Attribute-Value");   

p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...):

FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");   

but at first, define this function:

function FindByAttributeValue(attribute, value, element_type)    {
  element_type = element_type || "*";
  var All = document.getElementsByTagName(element_type);
  for (var i = 0; i < All.length; i++)       {
    if (All[i].getAttribute(attribute) == value) { return All[i]; }
  }
}

p.s. updated per comments recommendations.

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.dev.khamsat"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Pluto's idea in a nicer way:

CustomWebViewPage.cs:

    public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> {

    public IHtmlString PartialWithScripts(string partialViewName, object model) {
        return Html.Partial(partialViewName: partialViewName, model: model, viewData: new ViewDataDictionary { ["view"] = this, ["html"] = Html });
    }

    public void RenderScriptsInBasePage(HelperResult scripts) {
        var parentView = ViewBag.view as WebPageBase;
        var parentHtml = ViewBag.html as HtmlHelper;
        parentView.DefineSection("scripts", () => {
            parentHtml.ViewContext.Writer.Write(scripts.ToHtmlString());
        });
    }
}

Views\web.config:

<pages pageBaseType="Web.Helpers.CustomWebViewPage">

View:

@PartialWithScripts("_BackendSearchForm")

Partial (_BackendSearchForm.cshtml):

@{ RenderScriptsInBasePage(scripts()); }

@helper scripts() {
<script>
    //code will be rendered in a "scripts" section of the Layout page
</script>
}

Layout page:

@RenderSection("scripts", required: false)

Is not an enclosing class Java

No need to make the nested class as static but it must be public

public class Test {
    public static void main(String[] args) {
        Shape shape = new Shape();
        Shape s = shape.new Shape.ZShape();
    }
}

Checkboxes in web pages – how to make them bigger?

I tried changing the padding and margin and well as the width and height, and then finally found that if you just increase the scale it'll work:

input[type=checkbox] {
    transform: scale(1.5);
}

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

Java 7 defaults to TLS 1.0, which can cause this error when that protocol is not accepted. I ran into this problem with a Tomcat application and a server that would not accept TLS 1.0 connections any longer. I added

-Dhttps.protocols=TLSv1.1,TLSv1.2

to the Java options and that fixed it. (Tomcat was running Java 7.)

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Java : Sort integer array without using Arrays.sort()

int x[] = { 10, 30, 15, 69, 52, 89, 5 };
    int max, temp = 0, index = 0;
    for (int i = 0; i < x.length; i++) {
        int counter = 0;
        max = x[i];
        for (int j = i + 1; j < x.length; j++) {

            if (x[j] > max) {
                max = x[j];
                index = j;
                counter++;
            }

        }
        if (counter > 0) {
            temp = x[index];
            x[index] = x[i];
            x[i] = temp;
        }
    }
    for (int i = 0; i < x.length; i++) {
        System.out.println(x[i]);
    }

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

"date(): It is not safe to rely on the system's timezone settings..."

In my particular case, I have PHP configured to use PHP-FPM (FastCGI Process Manager). When executing phpinfo() from CLI I saw correct timezone that I had set in the php.ini, however it was still incorrect in the browser and causing my code to fail. I simply needed to restart the php-fpm service on the server.

service rh-php56-php-fpm restart

You may also need to restart the httpd service if you edited the php.ini

service httpd restart

How to open, read, and write from serial port in C?

I wrote this a long time ago (from years 1985-1992, with just a few tweaks since then), and just copy and paste the bits needed into each project.

You must call cfmakeraw on a tty obtained from tcgetattr. You cannot zero-out a struct termios, configure it, and then set the tty with tcsetattr. If you use the zero-out method, then you will experience unexplained intermittent failures, especially on the BSDs and OS X. "Unexplained intermittent failures" include hanging in read(3).

#include <errno.h>
#include <fcntl.h> 
#include <string.h>
#include <termios.h>
#include <unistd.h>

int
set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tcgetattr", errno);
                return -1;
        }

        cfsetospeed (&tty, speed);
        cfsetispeed (&tty, speed);

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                error_message ("error %d from tcsetattr", errno);
                return -1;
        }
        return 0;
}

void
set_blocking (int fd, int should_block)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tggetattr", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                error_message ("error %d setting term attributes", errno);
}


...
char *portname = "/dev/ttyUSB1"
 ...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
        error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
        return;
}

set_interface_attribs (fd, B115200, 0);  // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0);                // set no blocking

write (fd, "hello!\n", 7);           // send 7 character greeting

usleep ((7 + 25) * 100);             // sleep enough to transmit the 7 plus
                                     // receive 25:  approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf);  // read up to 100 characters if ready to read

The values for speed are B115200, B230400, B9600, B19200, B38400, B57600, B1200, B2400, B4800, etc. The values for parity are 0 (meaning no parity), PARENB|PARODD (enable parity and use odd), PARENB (enable parity and use even), PARENB|PARODD|CMSPAR (mark parity), and PARENB|CMSPAR (space parity).

"Blocking" sets whether a read() on the port waits for the specified number of characters to arrive. Setting no blocking means that a read() returns however many characters are available without waiting for more, up to the buffer limit.


Addendum:

CMSPAR is needed only for choosing mark and space parity, which is uncommon. For most applications, it can be omitted. My header file /usr/include/bits/termios.h enables definition of CMSPAR only if the preprocessor symbol __USE_MISC is defined. That definition occurs (in features.h) with

#if defined _BSD_SOURCE || defined _SVID_SOURCE
 #define __USE_MISC     1
#endif

The introductory comments of <features.h> says:

/* These are defined by the user (or the compiler)
   to specify the desired environment:

...
   _BSD_SOURCE          ISO C, POSIX, and 4.3BSD things.
   _SVID_SOURCE         ISO C, POSIX, and SVID things.
...
 */

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

As @Indigenuity states, this appears to be caused by browsers parsing the <meta name="viewport"> tag.

To solve this problem at the source, try the following:

<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">.

In my tests this prevents the user from zooming out to view the overflowed content, and as a result prevents panning/scrolling to it as well.

How to save data file into .RData?

Alternatively, when you want to save individual R objects, I recommend using saveRDS.

You can save R objects using saveRDS, then load them into R with a new variable name using readRDS.

Example:

# Save the city object
saveRDS(city, "city.rds")

# ...

# Load the city object as city
city <- readRDS("city.rds")

# Or with a different name
city2 <- readRDS("city.rds")

But when you want to save many/all your objects in your workspace, use Manetheran's answer.

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

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

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

HTTP requests and JSON parsing in Python

Also for pretty Json on console:

 json.dumps(response.json(), indent=2)

possible to use dumps with indent. (Please import json)

Get the difference between dates in terms of weeks, months, quarters, and years

I just wrote this for another question, then stumbled here.

library(lubridate)

#' Calculate age
#' 
#' By default, calculates the typical "age in years", with a
#' \code{floor} applied so that you are, e.g., 5 years old from
#' 5th birthday through the day before your 6th birthday. Set
#' \code{floor = FALSE} to return decimal ages, and change \code{units}
#' for units other than years.
#' @param dob date-of-birth, the day to start calculating age.
#' @param age.day the date on which age is to be calculated.
#' @param units unit to measure age in. Defaults to \code{"years"}. Passed to \link{\code{duration}}.
#' @param floor boolean for whether or not to floor the result. Defaults to \code{TRUE}.
#' @return Age in \code{units}. Will be an integer if \code{floor = TRUE}.
#' @examples
#' my.dob <- as.Date('1983-10-20')
#' age(my.dob)
#' age(my.dob, units = "minutes")
#' age(my.dob, floor = FALSE)
age <- function(dob, age.day = today(), units = "years", floor = TRUE) {
    calc.age = interval(dob, age.day) / duration(num = 1, units = units)
    if (floor) return(as.integer(floor(calc.age)))
    return(calc.age)
}

Usage examples:

my.dob <- as.Date('1983-10-20')

age(my.dob)
# [1] 31

age(my.dob, floor = FALSE)
# [1] 31.15616

age(my.dob, units = "minutes")
# [1] 16375680

age(seq(my.dob, length.out = 6, by = "years"))
# [1] 31 30 29 28 27 26

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

When should iteritems() be used instead of items()?

As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items returns a list, while iteritems returns a iterator.

In python 3, items returns a view, which is pretty much the same as an iterator.

If you are using python 2, you may want to user iteritems if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

good example of Javadoc

The page How to Write Doc Coments for the Javadoc Tool contains a good number of good examples. One section is called Examples of Doc Comments and contains quite a few usages.

Also, the Javadoc FAQ contains some more examples to illustrate the answers.

Convert an image (selected by path) to base64 string

That way it's simpler, where you pass the image and then pass the format.

private static string ImageToBase64(Image image)
{
    var imageStream = new MemoryStream();
    try
    {           
        image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
        imageStream.Position = 0;
        var imageBytes = imageStream.ToArray();
        var ImageBase64 = Convert.ToBase64String(imageBytes);
        return ImageBase64;
    }
    catch (Exception ex)
    {
        return "Error converting image to base64!";
    }
    finally
    {
      imageStream.Dispose;
    }
}

How to iterate over arguments in a Bash script

For simple cases you can also use shift. It treats the argument list like a queue. Each shift throws the first argument out and the index of each of the remaining arguments is decremented.

#this prints all arguments
while test $# -gt 0
do
    echo "$1"
    shift
done

What's the difference between isset() and array_key_exists()?

The PHP function array_key_exists() determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset() can tell you that (and that the value is not null). array_key_exists()cannot return information about the value of a key/index.

How to import CSV file data into a PostgreSQL table?

In Python, you can use this code for automatic PostgreSQL table creation with column names:

import pandas, csv

from io import StringIO
from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)
        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name
        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

engine = create_engine('postgresql://user:password@localhost:5432/my_db')

df = pandas.read_csv("my.csv")
df.to_sql('my_table', engine, schema='my_schema', method=psql_insert_copy)

It's also relatively fast, I can import more than 3.3 million rows in about 4 minutes.

App not setup: This app is still in development mode

I had the same problem and it took me around one hour to figure out where i went wrong only to note that i had used a wrong app id....just go to your code and used a correct id here

window.fbAsyncInit = function() {
    FB.init({
        appId      : '1740077446229063',//your app id
        cookie     : true,  // enable cookies to allow the server to access
        // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

Bulk package updates using Conda

You want conda update --all.

conda search --outdated will show outdated packages, and conda update --all will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2).

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

postgreSQL - psql \i : how to execute script in a given path

Have you tried using Unix style slashes (/ instead of \)?

\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.

Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.

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

I had the same issue and was not satisfied with any of the answers so far since none of them guaranteed unique IDs.

I too wanted to print object IDs for debugging purposed. I knew there must be some way to do it, because in the Eclipse debugger, it specifies unique IDs for each object.

I came up with a solution based on the fact that the "==" operator for objects only returns true if the two objects are actually the same instance.

import java.util.HashMap;
import java.util.Map;

/**
 *  Utility for assigning a unique ID to objects and fetching objects given
 *  a specified ID
 */
public class ObjectIDBank {

    /**Singleton instance*/
    private static ObjectIDBank instance;

    /**Counting value to ensure unique incrementing IDs*/
    private long nextId = 1;

    /** Map from ObjectEntry to the objects corresponding ID*/
    private Map<ObjectEntry, Long> ids = new HashMap<ObjectEntry, Long>();

    /** Map from assigned IDs to their corresponding objects */
    private Map<Long, Object> objects = new HashMap<Long, Object>();

    /**Private constructor to ensure it is only instantiated by the singleton pattern*/
    private ObjectIDBank(){}

    /**Fetches the singleton instance of ObjectIDBank */
    public static ObjectIDBank instance() {
        if(instance == null)
            instance = new ObjectIDBank();

        return instance;
    }

    /** Fetches a unique ID for the specified object. If this method is called multiple
     * times with the same object, it is guaranteed to return the same value. It is also guaranteed
     * to never return the same value for different object instances (until we run out of IDs that can
     * be represented by a long of course)
     * @param obj The object instance for which we want to fetch an ID
     * @return Non zero unique ID or 0 if obj == null
     */
    public long getId(Object obj) {

        if(obj == null)
            return 0;

        ObjectEntry objEntry = new ObjectEntry(obj);

        if(!ids.containsKey(objEntry)) {
            ids.put(objEntry, nextId);
            objects.put(nextId++, obj);
        }

        return ids.get(objEntry);
    }

    /**
     * Fetches the object that has been assigned the specified ID, or null if no object is
     * assigned the given id
     * @param id Id of the object
     * @return The corresponding object or null
     */
    public Object getObject(long id) {
        return objects.get(id);
    }


    /**
     * Wrapper around an Object used as the key for the ids map. The wrapper is needed to
     * ensure that the equals method only returns true if the two objects are the same instance
     * and to ensure that the hash code is always the same for the same instance.
     */
    private class ObjectEntry {
        private Object obj;

        /** Instantiates an ObjectEntry wrapper around the specified object*/
        public ObjectEntry(Object obj) {
            this.obj = obj;
        }


        /** Returns true if and only if the objects contained in this wrapper and the other
         * wrapper are the exact same object (same instance, not just equivalent)*/
        @Override
        public boolean equals(Object other) {
            return obj == ((ObjectEntry)other).obj;
        }


        /**
         * Returns the contained object's identityHashCode. Note that identityHashCode values
         * are not guaranteed to be unique from object to object, but the hash code is guaranteed to
         * not change over time for a given instance of an Object.
         */
        @Override
        public int hashCode() {
            return System.identityHashCode(obj);
        }
    }
}

I believe that this should ensure unique IDs throughout the lifetime of the program. Note, however, that you probably don't want to use this in a production application because it maintains references to all of the objects for which you generate IDs. This means that any objects for which you create an ID will never be garbage collected.

Since I'm using this for debug purposes, I'm not too concerned with the memory being freed.

You could modify this to allow clearing Objects or removing individual objects if freeing memory is a concern.

Detecting input change in jQuery?

With HTML5 and without using jQuery, you can using the input event:

var input = document.querySelector('input');

input.addEventListener('input', function()
{
    console.log('input changed to: ', input.value);
});

This will fire each time the input's text changes.

Supported in IE9+ and other browsers.

Try it live in a jsFiddle here.

What characters do I need to escape in XML documents?

According to the specifications of the World Wide Web Consortium (w3C), there are 5 characters that must not appear in their literal form in an XML document, except when used as markup delimiters or within a comment, a processing instruction, or a CDATA section. In all the other cases, these characters must be replaced either using the corresponding entity or the numeric reference according to the following table:

Original CharacterXML entity replacementXML numeric replacement
<                              &lt;                                    &#60;                                    
>                              &gt;                                   &#62;                                    
"                               &quot;                               &#34;                                    
&                              &amp;                               &#38;                                    
'                               &apos;                               &#39;                                    

Notice that the aforementioned entities can be used also in HTML, with the exception of &apos;, that was introduced with XHTML 1.0 and is not declared in HTML 4. For this reason, and to ensure retro-compatibility, the XHTML specification recommends the use of &#39; instead.