Programs & Examples On #Minesweeper

Minesweeper game is an abstract puzzle, quite popular as a target of sample programs in different laguages.

Working with select using AngularJS's ng-options

One thing to note is that ngModel is required for ngOptions to work... note the ng-model="blah" which is saying "set $scope.blah to the selected value".

Try this:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

Here's more from AngularJS's documentation (if you haven't seen it):

for array data sources:

  • label for value in array
  • select as label for value in array
  • label group by group for value in array = select as label group by group for value in array

for object data sources:

  • label for (key , value) in object
  • select as label for (key , value) in object
  • label group by group for (key, value) in object
  • select as label group by group for (key, value) in object

For some clarification on option tag values in AngularJS:

When you use ng-options, the values of option tags written out by ng-options will always be the index of the array item the option tag relates to. This is because AngularJS actually allows you to select entire objects with select controls, and not just primitive types. For example:

app.controller('MainCtrl', function($scope) {
   $scope.items = [
     { id: 1, name: 'foo' },
     { id: 2, name: 'bar' },
     { id: 3, name: 'blah' }
   ];
});
<div ng-controller="MainCtrl">
   <select ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
   <pre>{{selectedItem | json}}</pre>
</div>

The above will allow you to select an entire object into $scope.selectedItem directly. The point is, with AngularJS, you don't need to worry about what's in your option tag. Let AngularJS handle that; you should only care about what's in your model in your scope.

Here is a plunker demonstrating the behavior above, and showing the HTML written out


Dealing with the default option:

There are a few things I've failed to mention above relating to the default option.

Selecting the first option and removing the empty option:

You can do this by adding a simple ng-init that sets the model (from ng-model) to the first element in the items your repeating in ng-options:

<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.name for item in items"></select>

Note: This could get a little crazy if foo happens to be initialized properly to something "falsy". In that case, you'll want to handle the initialization of foo in your controller, most likely.

Customizing the default option:

This is a little different; here all you need to do is add an option tag as a child of your select, with an empty value attribute, then customize its inner text:

<select ng-model="foo" ng-options="item as item.name for item in items">
   <option value="">Nothing selected</option>
</select>

Note: In this case the "empty" option will stay there even after you select a different option. This isn't the case for the default behavior of selects under AngularJS.

A customized default option that hides after a selection is made:

If you wanted your customized default option to go away after you select a value, you can add an ng-hide attribute to your default option:

<select ng-model="foo" ng-options="item as item.name for item in items">
   <option value="" ng-if="foo">Select something to remove me.</option>
</select>

HashMap - getting First Key value

To get the "first" value:

map.values().toArray()[0]

To get the value of the "first" key:

map.get(map.keySet().toArray()[0])

Note: Above code tested and works.

I say "first" because HashMap entries are not ordered.

However, a LinkedHashMap iterates its entries in the same order as they were inserted - you could use that for your map implementation if insertion order is important.

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)

 $.ajax({
            type: "POST",
            url: url,
            data: '{"name" :"sheo"}',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false
            }).done(function (Response) {
                  //do something when get response            })
           .fail(function (Response) {
                    //do something when any error occurs.
                });

How to get the error message from the error code returned by GetLastError()?

In general, you need to use FormatMessage to convert from a Win32 error code to text.

From the MSDN documentation:

Formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.

The declaration of FormatMessage:

DWORD WINAPI FormatMessage(
  __in      DWORD dwFlags,
  __in_opt  LPCVOID lpSource,
  __in      DWORD dwMessageId, // your error code
  __in      DWORD dwLanguageId,
  __out     LPTSTR lpBuffer,
  __in      DWORD nSize,
  __in_opt  va_list *Arguments
);

How to get row number from selected rows in Oracle

There is no inherent ordering to a table. So, the row number itself is a meaningless metric.

However, you can get the row number of a result set by using the ROWNUM psuedocolumn or the ROW_NUMBER() analytic function, which is more powerful.

As there is no ordering to a table both require an explicit ORDER BY clause in order to work.

select rownum, a.*
  from ( select *
           from student
          where name like '%ram%'
          order by branch
                ) a

or using the analytic query

select row_number() over ( order by branch ) as rnum, a.*
  from student
 where name like '%ram%'

Your syntax where name is like ... is incorrect, there's no need for the IS, so I've removed it.

The ORDER BY here relies on a binary sort, so if a branch starts with anything other than B the results may be different, for instance b is greater than B.

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I accidentally left in the '.py' at the end of the name of my program. And I forgot to capitalize the name of the folder it was in ('Apps').

How to place the ~/.composer/vendor/bin directory in your PATH?

For Ubuntu 16.04

echo 'export PATH="$PATH:$HOME/.config/composer/vendor/bin"' >> ~/.bashrc

source ~/.bashrc

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

Here it is! - SP 25 works on Visual Studio 2019, SP 21 on Visual Studio 2017

SAP released SAP Crystal Reports, developer version for Microsoft Visual Studio

You can get it here (click "Installation package for Visual Studio IDE")

To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.

New In SP25 Release

Visual Studio 2019, Addressed incidents, Win10 1809, Security update

Shell script not running, command not found

Also try to dos2unix the shell script, because sometimes it has Windows line endings and the shell does not recognize it.

$ dos2unix MigrateNshell.sh

This helps sometimes.

HTML embedded PDF iframe

It's downloaded probably because there is not Adobe Reader plug-in installed. In this case, IE (it doesn't matter which version) doesn't know how to render it, and it'll simply download the file (Chrome, for example, has its own embedded PDF renderer).

That said. <iframe> is not best way to display a PDF (do not forget compatibility with mobile browsers, for example Safari). Some browsers will always open that file inside an external application (or in another browser window). Best and most compatible way I found is a little bit tricky but works on all browsers I tried (even pretty outdated):

Keep your <iframe> but do not display a PDF inside it, it'll be filled with an HTML page that consists of an <object> tag. Create an HTML wrapping page for your PDF, it should look like this:

<html>
<body>
    <object data="your_url_to_pdf" type="application/pdf">
        <embed src="your_url_to_pdf" type="application/pdf" />
    </object>
</body>
</html>

Of course, you still need the appropriate plug-in installed in the browser. Also, look at this post if you need to support Safari on mobile devices.

1st. Why nesting <embed> inside <object>? You'll find the answer here on SO. Instead of a nested <embed> tag, you may (should!) provide a custom message for your users (or a built-in viewer, see next paragraph). Nowadays, <object> can be used without worries, and <embed> is useless.

2nd. Why an HTML page? So you can provide a fallback if PDF viewer isn't supported. Internal viewer, plain HTML error messages/options, and so on...

It's tricky to check PDF support so that you may provide an alternate viewer for your customers, take a look at PDF.JS project; it's pretty good but rendering quality - for desktop browsers - isn't as good as a native PDF renderer (I didn't see any difference in mobile browsers because of screen size, I suppose).

Convert string to decimal, keeping fractions

The below code prints the value as 1200.00.

var convertDecimal = Convert.ToDecimal("1200.00");
Console.WriteLine(convertDecimal);

Not sure what you are expecting?

application/x-www-form-urlencoded or multipart/form-data?

If you need to use Content-Type=x-www-urlencoded-form then DO NOT use FormDataCollection as parameter: In asp.net Core 2+ FormDataCollection has no default constructors which is required by Formatters. Use IFormCollection instead:

 public IActionResult Search([FromForm]IFormCollection type)
    {
        return Ok();
    }

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

Footnotes for tables in LaTeX

In tables I have used \footnotetext.

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

How to pass multiple parameters to a get method in ASP.NET Core

You can simply do the following:

    [HttpGet]
    public async Task<IActionResult> GetAsync()
    {
        string queryString = Request.QueryString.ToString().ToLower();

        return Ok(await DoMagic.GetAuthorizationTokenAsync(new Uri($"https://someurl.com/token-endpoint{queryString}")));
    }

If you need to access each element separately, simply refer to Request.Query.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

How do I pass environment variables to Docker containers?

There is a nice hack how to pipe host machine environment variables to a docker container:

env > env_file && docker run --env-file env_file image_name

Use this technique very carefully, because env > env_file will dump ALL host machine ENV variables to env_file and make them accessible in the running container.

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.

<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>


<script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
$(document).ready(function () { 

    $('#nav li').hover(
        function () {
            //show its submenu
            $('ul', this).slideDown(100);

        }, 
        function () {
            //hide its submenu
            $('ul', this).slideUp(100);         
        }
    );

});
    </script>

</head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class="header">&nbsp;</td>
  </tr>
  <tr>
    <td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
    <tr>
    <td>

    <ul id="nav">
    <li><a href="#">Catalog</a>
    <ul><li><a href="#">Products</a></li>
        <li><a href="#">Bulk Upload</a></li>
        </ul>
        <div class="clear"></div>
        </li>


    <li><a href="#">Purchase  </a>

    </li>
    <li><a href="#">Customer Service</a>
    <ul>
        <li><a href="#">Contact Us</a></li>
        <li><a href="#">CS Panel</a></li>

    </ul>           
        <div class="clear"></div>
    </li>
    <li><a href="#">All Reports</a></li>
    <li><a href="#">Configuration</a>
    <ul> <li><a href="#">Look and Feel </a></li>
         <li><a href="#">Business Details</a></li>
         <li><a href="#">CS Details</a></li>
         <li><a href="#">Emaqil Template</a></li>
         <li><a href="#">Domain and Analytics</a></li>
         <li><a href="#">Courier</a></li>
         </ul>
    <div class="clear"></div>
    </li>
    <li><a href="#">Accounts</a>
    <ul><li><a href="#">Ledgers</a></li>
        <li><a href="#">Account Details</a></li>
        </ul>
         <div class="clear"></div></li>

</ul></td></tr></table></td>
  </tr>
  <tr>
    <td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
          <tr>
            <td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
              <tr>
                <td>&nbsp;</td>
                </tr>
              <tr>
                <td height="45"><strong>-&gt; Products</strong></td>
                </tr>
              <tr>
                <td height="61"><strong>-&gt; Categories</strong></td>
                </tr>
              <tr>
                <td height="48"><strong>-&gt; Sub Categories</strong></td>
                </tr>
            </table></td>
            <td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td>&nbsp;</td>
                </tr>
              <tr>
                <td>
                  <table width="90%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="26%">&nbsp;</td>
                      <td width="74%"><h2>Manage Categories</h2></td>
                    </tr>
                  </table></td>
                </tr>
              <tr>
                <td height="30">&nbsp;

                </td>
                </tr>
              <tr>
                <td>


</td>
                </tr>

                <tr>
                <td>
                <table width="49%" align="center" cellpadding="0" cellspacing="0">
                <tr><td>




<?php


                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php


require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

I was experiencing the same issue so just added the @Transactional annotation from where I was calling the DAO method. It just works. I think the problem was Hibernate doesn't allow to retrieve sub-objects from the database unless specifically all the required objects at the time of calling.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Updated for Xcode 7. Adds String extension:

Use:

var chuck: String = "Hello Chuck Norris"
chuck[6...11] // => Chuck

Implementation:

extension String {

    /**
     Subscript to allow for quick String substrings ["Hello"][0...1] = "He"
     */
    subscript (r: Range<Int>) -> String {
        get {
            let start = self.startIndex.advancedBy(r.startIndex)
            let end = self.startIndex.advancedBy(r.endIndex - 1)
            return self.substringWithRange(start..<end)
        }
    }

}

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

How to read files and stdout from a running Docker container

Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.

Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!

Add days Oracle SQL

You can use the plus operator to add days to a date.

order_date + 20

How to change Status Bar text color in iOS

change the status bar text color for all ViewControllers

swift 3

if View controller-based status bar appearance = YES in Info.plist

then use this extension for all NavigationController

extension UINavigationController
{
    override open var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
     }
 }

if there is no UINavigationController and only have UIViewController then use Below code:

extension UIViewController
{
    override open var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
     }
 }

objective c

create category class

For UIViewController

In UIViewController+StatusBarStyle.h

 @interface UIViewController (StatusBarStyle)
 @end

In UIViewController+StatusBarStyle.m

 #import "UIViewController+StatusBarStyle.h"

 @implementation UIViewController (StatusBarStyle)
 -(UIStatusBarStyle)preferredStatusBarStyle
 {
  return UIStatusBarStyleLightContent;
 }
 @end 

For UINavigationController

In UINavigationController+StatusBarStyle.h

 @interface UINavigationController (StatusBarStyle)
 @end

In UINavigationController+StatusBarStyle.m

 #import "UINavigationController+StatusBarStyle.h"

 @implementation UINavigationController (StatusBarStyle)
 -(UIStatusBarStyle)preferredStatusBarStyle
 {
  return UIStatusBarStyleLightContent;
 }
 @end  

What is the exact meaning of Git Bash?

git bash is a shell where:

See "Fix msysGit Portable $HOME location":

On a Windows 64:

C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"

This differs from git-cmd.bat, which provides git commands in a plain DOS command prompt.

A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)


Update April 2015:

Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:

GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.

But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2 comes with its own installer too.

The git bash is now (with the new Git For Windows):

GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.

Original answer (June 2013) More precisely, from msygit wiki:

Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.

To make the milky 'soup' of project names more clear, we say like this:

  • msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
  • MinGW - is a minimalist development environment for native Microsoft Windows applications.
    It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as a fork() call
  • MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
  • Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit

So, your two lines description about "git bash" are:

"Git bash" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.


Reminder:

msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.

msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.

See more in "Difference between msysgit and Cygwin + git?".

Node.js: Gzip compression?

Although you can gzip using a reverse proxy such as nginx, lighttpd or in varnish. It can be beneficial to have most http optimisations such as gzipping at the application level so that you can have a much granular approach on what asset's to gzip.

I have actually created my own gzip module for expressjs / connect called gzippo https://github.com/tomgco/gzippo although new it does do the job. Plus it uses node-compress instead of spawning the unix gzip command.

What are intent-filters in Android?

Keep the first intent filter with keys MAIN and LAUNCHER and add another as ANY_NAME and DEFAULT.

Your LAUNCHER will be activity A and DEFAULT will be your activity B.

How to determine the longest increasing subsequence using dynamic programming?

This can be solved in O(n^2) using Dynamic Programming. Python code for the same would be like:-

def LIS(numlist):
    LS = [1]
    for i in range(1, len(numlist)):
        LS.append(1)
        for j in range(0, i):
            if numlist[i] > numlist[j] and LS[i]<=LS[j]:
                LS[i] = 1 + LS[j]
    print LS
    return max(LS)

numlist = map(int, raw_input().split(' '))
print LIS(numlist)

For input:5 19 5 81 50 28 29 1 83 23

output would be:[1, 2, 1, 3, 3, 3, 4, 1, 5, 3] 5

The list_index of output list is the list_index of input list. The value at a given list_index in output list denotes the Longest increasing subsequence length for that list_index.

tell pip to install the dependencies of packages listed in a requirement file

As @Ming mentioned:

pip install -r file.txt

Here's a simple line to force update all dependencies:

while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt

Default SecurityProtocol in .NET 4.5

The registry change mechanism worked for me after a struggle. Actually my application was running as 32bit. So I had to change the value under path.

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319

The value type needs to be DWORD and value above 0 .Better use 1.Registry settings to get .Net 4.0 app use TLS 1.2 provided .Net 4.5 is installed in the machine.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

How to find file accessed/created just few minutes ago

If you have GNU find you can also say

find . -newermt '1 minute ago'

The t options makes the reference "file" for newer become a reference date string of the sort that you could pass to GNU date -d, which understands complex date specifications like the one given above.

What is the difference between URI, URL and URN?

Uniform Resource Identifier (URI) is a string of characters used to identify a name or a resource on the Internet

A URI identifies a resource either by location, or a name, or both. A URI has two specializations known as URL and URN.

A Uniform Resource Locator (URL) is a subset of the Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it. A URL defines how the resource can be obtained. It does not have to be HTTP URL (http://), a URL can also be (ftp://) or (smb://).

A Uniform Resource Name (URN) is a Uniform Resource Identifier (URI) that uses the URN scheme, and does not imply availability of the identified resource. Both URNs (names) and URLs (locators) are URIs, and a particular URI may be both a name and a locator at the same time.

The URNs are part of a larger Internet information architecture which is composed of URNs, URCs and URLs.

bar.html is not a URN. A URN is similar to a person's name, while a URL is like a street address. The URN defines something's identity, while the URL provides a location. Essentially, "what" vs. "where". A URN has to be of this form <URN> ::= "urn:" <NID> ":" <NSS> where <NID> is the Namespace Identifier, and <NSS> is the Namespace Specific String.

To put it differently:

  • A URL is a URI that identifies a resource and also provides the means of locating the resource by describing the way to access it
  • A URL is a URI
  • A URI is not necessarily a URL

I'd say the only thing left to make it 100% clear would be to have an example of an URI that is not an URL. We can use the examples in the RFC3986:

URL: ftp://ftp.is.co.za/rfc/rfc1808.txt
URL: http://www.ietf.org/rfc/rfc2396.txt
URL: ldap://[2001:db8::7]/c=GB?objectClass?one
URL: mailto:[email protected]
URL: news:comp.infosystems.www.servers.unix
URL: telnet://192.0.2.16:80/
URN (not URL): urn:oasis:names:specification:docbook:dtd:xml:4.1.2
URN (not URL): tel:+1-816-555-1212 (?)

Also check this out - https://quintupledev.wordpress.com/2016/02/29/difference-between-uri-url-and-urn/

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

This works for me:

1) Stop the ng server

2) Reinstall your package

npm install your-package-name

3) Run all again

ng serve

Change language of Visual Studio 2017 RC

You need reinstall VS.

Language Pack Support in Visual Studio 2017 RC

Issue:

This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.

Workaround:

These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.

Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016

Sort an ArrayList based on an object field

Modify the DataNode class so that it implements Comparable interface.

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

then just use

Collections.sort(nodeList);

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Check if element found in array c++

If you were originally looking for the answer to this question (int value in sorted (Ascending) int array), then you can use the following code that performs a binary search (fastest result):

static inline bool exists(int ints[], int size, int k) // array, array's size, searched value
{
    if (size <= 0)      // check that array size is not null or negative
         return false;
    // sort(ints, ints + size); // uncomment this line if array wasn't previously sorted
    return (std::binary_search(ints, ints + size, k));
}

edit: Also works for unsorted int array if uncommenting sort.

Import and Export Excel - What is the best library?

We have just identified a similar need. And I think it's important to consider the user experience.

We nearly got sidetracked along the same:

  1. Prepare/work in spreadsheet file
  2. Save file
  3. Import file
  4. Work with data in system

... workflow

Add-in Express allows you to create a button within Excel without all that tedious mucking about with VSTO. Then the workflow becomes:

  1. Prepare/work in spreadsheet file
  2. Import file (using button inside Excel)
  3. Work with data in system

Have the code behind the button use the "native" Excel API (via Add-in Express) and push direct into the recipient system. You can't get much more transparent for the developer or the user. Worth considering.

Abort a Git Merge

as long as you did not commit you can type

git merge --abort

just as the command line suggested.

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

What's the difference between implementation and compile in Gradle?

The brief difference in layman's term is:

  • If you are working on an interface or module that provides support to other modules by exposing the members of the stated dependency you should be using 'api'.
  • If you are making an application or module that is going to implement or use the stated dependency internally, use 'implementation'.
  • 'compile' worked same as 'api', however, if you are only implementing or using any library, 'implementation' will work better and save you resources.

read the answer by @aldok for a comprehensive example.

Install .ipa to iPad with or without iTunes

All of the other answers are either out of date or too much work where it doesn't need to be. Upload your .IPA file to diawi.com then either scan the QR-Code and install, or email the link to the device you want to install the app to, or type the shortened URL into your Safari browser and install that way.

I needed to get an app installed into an older iOS device today and this method took me less than 2 minutes to complete start to finish.

 https://www.diawi.com/

Decompile Python 2.7 .pyc

UPDATE (2019-04-22) - It sounds like you want to use uncompyle6 nowadays rather than the answers I had mentioned originally.

This sounds like it works: http://code.google.com/p/unpyc/

Issue 8 says it supports 2.7: http://code.google.com/p/unpyc/updates/list

UPDATE (2013-09-03) - As noted in the comments and in other answers, you should look at https://github.com/wibiti/uncompyle2 or https://github.com/gstarnberger/uncompyle instead of unpyc.

How to set css style to asp.net button?

<asp:LinkButton ID="mybutton" Text="Link Button" runat="server"></asp:LinkButton>

With Hover effects :

 #mybutton
        {
            background-color: #000;
            color: #fff;
            font-size: 20px;
            width: 150px;
            font-weight: bold;
        }
        #mybutton:hover
        {
            background-color: #fff;
            color: #000;
        }

http://www.parallelcodes.com/asp-net-button-css/

How can I update the current line in a C# Windows Console App?

So far we have three competing alternatives for how to do this:

Console.Write("\r{0}   ", value);                      // Option 1: carriage return
Console.Write("\b\b\b\b\b{0}", value);                 // Option 2: backspace
{                                                      // Option 3 in two parts:
    Console.SetCursorPosition(0, Console.CursorTop);   // - Move cursor
    Console.Write(value);                              // - Rewrite
}

I've always used Console.CursorLeft = 0, a variation on the third option, so I decided to do some tests. Here's the code I used:

public static void CursorTest()
{
    int testsize = 1000000;

    Console.WriteLine("Testing cursor position");
    Stopwatch sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < testsize; i++)
    {
        Console.Write("\rCounting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using \\r: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    int top = Console.CursorTop;
    for (int i = 0; i < testsize; i++)
    {
        Console.SetCursorPosition(0, top);        
        Console.Write("Counting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using CursorLeft: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    Console.Write("Counting:          ");
    for (int i = 0; i < testsize; i++)
    {        
        Console.Write("\b\b\b\b\b\b\b\b{0,8}", i);
    }

    sw.Stop();
    Console.WriteLine("\nTime using \\b: {0}", sw.ElapsedMilliseconds);
}

On my machine, I get the following results:

  • Backspaces: 25.0 seconds
  • Carriage Returns: 28.7 seconds
  • SetCursorPosition: 49.7 seconds

Additionally, SetCursorPosition caused noticeable flicker that I didn't observe with either of the alternatives. So, the moral is to use backspaces or carriage returns when possible, and thanks for teaching me a faster way to do this, SO!


Update: In the comments, Joel suggests that SetCursorPosition is constant with respect to the distance moved while the other methods are linear. Further testing confirms that this is the case, however constant time and slow is still slow. In my tests, writing a long string of backspaces to the console is faster than SetCursorPosition until somewhere around 60 characters. So backspace is faster for replacing portions of the line shorter than 60 characters (or so), and it doesn't flicker, so I'm going to stand by my initial endorsement of \b over \r and SetCursorPosition.

How to get the seconds since epoch from the time + date output of gmtime()?

There are two ways, depending on your original timestamp:

mktime() and timegm()

http://docs.python.org/library/time.html

How can I show and hide elements based on selected option with jQuery?

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

Difference between using Makefile and CMake to compile the code

The statement about CMake being a "build generator" is a common misconception.

It's not technically wrong; it just describes HOW it works, but not WHAT it does.

In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.

So, what is the real difference?

  • CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make has some built-in C/C++ rules as well, but they are useless at best.

  • CMake does a two-step build: it generates a low-level build script in ninja or make or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile are only executed at the generation stage. Thus, CMake build can be orders of magnitude faster.

  • The grammar of CMake is much easier to support for external tools than make's.

  • Once make builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake tracks it, make leaves it up to you. If one of library sources was removed since the previous version of Makefile, make won't rebuild it.

  • Modern CMake (starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies. These transitive dependencies can be exposed to or hidden from the dependent packages. CMake will manage directories for you. With make, you're stuck on a file-by-file and manage-directories-by-hand level.

You could code up something in make using intermediate files to cover the last two gaps, but you're on your own. make does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.

To be honest, this is what CMake and make have in common -- their languages are pretty horrible. Here's what comes to mind:

  • They have no user-defined types;
  • CMake has three data types: string, list, and a target with properties. make has one: string;
  • you normally pass arguments to functions by setting global variables.
    • This is partially dealt with in modern CMake - you can set a target's properties: set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}");
  • referring to an undefined variable is silently ignored by default;

How do you overcome the svn 'out of date' error?

Are you moving it using svn mv, or just mv? I think using just mv may cause this issue.

How do you Sort a DataTable given column and direction?

If you've only got one DataView, you can sort using that instead:

table.DefaultView.Sort = "columnName asc";

Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

Retrieve column names from java.sql.ResultSet

When you need the column names, but do not want to grab entries:

PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");

ResultSet set = stmt.executeQuery();

//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }

NOTE: Only works with MySQL

Where can I download Eclipse Android bundle?

Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3

Add a dependency in Maven

You'll have to do this in two steps:

1. Give your JAR a groupId, artifactId and version and add it to your repository.

If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:

mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile

You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ....

2. Update dependent projects to reference this JAR.

Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:

<dependencies>
    ...
    <dependency>
        <groupId>com.stackoverflow...</groupId>
        <artifactId>artifactId...</artifactId>
        <version>1.0</version>
    </dependency>
    ...
</dependencies>

Facebook key hash does not match any stored key hashes

On Debug

Copy Paste This code inside OnCreate method

       try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getApplication().getPackageName(),
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.d("KeyHash e1",e.getLocalizedMessage() +"");
        } catch (NoSuchAlgorithmException e) {
            Log.d("KeyHash e2", e.getLocalizedMessage() +"");
        }

Open Logcat and Filter/find 'D/KeyHash:'

D/KeyHash: D5uFR+65hafzotdih/dOfp14FpE=

Then Open https://developers.facebook.com/ and Open YourApp/Setting/Basic
Scroll down to Android Section Then Paste the Key Hashes and Save

Type Checking: typeof, GetType, or is?

Performance test typeof() vs GetType():

using System;
namespace ConsoleApplication1
    {
    class Program
    {
        enum TestEnum { E1, E2, E3 }
        static void Main(string[] args)
        {
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test1(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test2(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            Console.ReadLine();
        }
        static Type Test1<T>(T value) => typeof(T);
        static Type Test2(object value) => value.GetType();
    }
}

Results in debug mode:

00:00:08.4096636
00:00:10.8570657

Results in release mode:

00:00:02.3799048
00:00:07.1797128

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

Your code can simplified a lot to

$('img', resp).attr('src', function(idx, urlRelative ) {
    return self.config.proxy_server + self.config.location_images + urlRelative;
});

Keep SSH session alive

The ssh daemon (sshd), which runs server-side, closes the connection from the server-side if the client goes silent (i.e., does not send information). To prevent connection loss, instruct the ssh client to send a sign-of-life signal to the server once in a while.

The configuration for this is in the file $HOME/.ssh/config, create the file if it does not exist (the config file must not be world-readable, so run chmod 600 ~/.ssh/config after creating the file). To send the signal every e.g. four minutes (240 seconds) to the remote host, put the following in that configuration file:

Host remotehost
    HostName remotehost.com
    ServerAliveInterval 240

To enable sending a keep-alive signal for all hosts, place the following contents in the configuration file:

Host *
    ServerAliveInterval 240

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

A simpler version of your code would be:

dict(zip(names, d.values()))

If you want to keep the same structure, you can change it to:

vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}

(You can just as easily put list(d.values()) inside the comprehension instead of vlst; it's just wasteful to do so since it would be re-generating the list every time).

what does "dead beef" mean?

http://en.wikipedia.org/wiki/Hexspeak
http://www.urbandictionary.com/define.php?term=dead%3Abeef

"Dead beef" is a very popular sentence in programming, because it is built only from letters a-f, which are used in hexadecimal notation. Colons in the beginning and in the middle of the sentence make this sentence a (theoretically) valid IPv6 address.

jquery variable syntax

No, it certainly is not. It is just another variable name. The $() you're talking about is actually the jQuery core function. The $self is just a variable. You can even rename it to foo if you want, this doesn't change things. The $ (and _) are legal characters in a Javascript identifier.

Why this is done so is often just some code convention or to avoid clashes with reversed keywords. I often use it for $this as follows:

var $this = $(this);

Python Error: "ValueError: need more than 1 value to unpack"

youre getting ''ValueError: need more than 1 value to unpack'', because you only gave one value, the script (which is ex14.py in this case)

the problem is, that you forgot to add a name after you ran the .py file.

line 3 of your code is

script, user_name = argv

the script is ex14.py, you forgot to add a name after

so if your name was michael,so what you enter into the terminal should look something like:

> python ex14.py michael

make this change and the code runs perfectly

input type="submit" Vs button tag are they interchangeable?

http://www.w3.org/TR/html4/interact/forms.html#h-17.5

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

So for functionality only they're interchangeable!

(Don't forget, type="submit" is the default with button, so leave it off!)

How to clear/delete the contents of a Tkinter Text widget?

this works

import tkinter as tk
inputEdit.delete("1.0",tk.END)

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

How do I write a bash script to restart a process if it dies?

Have a look at monit (http://mmonit.com/monit/). It handles start, stop and restart of your script and can do health checks plus restarts if necessary.

Or do a simple script:

while true
do
/your/script
sleep 1
done

How do I assert equality on two classes without an equals method?

In common case with AssertJ you can create custom comparator strategy:

assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam)
assertThat(fellowshipOfTheRing).usingElementComparator(raceComparator).contains(sauron);

Using a custom comparison strategy in assertions

AssertJ examples

Questions every good PHP Developer should be able to answer

Is php cross-browser?

(i know, this will make laught many people, but is the more-asked question on php forums!)

What is the difference between `sorted(list)` vs `list.sort()`?

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() because it doesn't have to create a copy. For any other iterable, you have no choice.

  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

gradient descent using python and numpy

Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.

Data comes from a txt file with the following rows:

1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200

think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.

Here is the Octave implementation:

%
% Linear Regression with multiple variables
%

% Alpha for learning curve
alphaNum = 0.0005;

% Number of features
n = 2;

% Number of iterations for Gradient Descent algorithm
iterations = 10000

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% No need to update after here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DATA = load('CHANGE_WITH_DATA_FILE_PATH');

% Initial theta values
theta = ones(n + 1, 1);

% Number of training samples
m = length(DATA(:, 1));

% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
  X = [X, DATA(:,i)];
endfor

% Expected data must go always in the last column  
y = DATA(:, n + 1)

function gradientDescent(x, y, theta, alphaNum, iterations)
  iterations = [];
  costs = [];

  m = length(y);

  for iteration = 1:10000
    hypothesis = x * theta;

    loss = hypothesis - y;

    % J(theta)    
    cost = sum(loss.^2) / (2 * m);

    % Save for the graphic to see if the algorithm did work
    iterations = [iterations, iteration];
    costs = [costs, cost];

    gradient = (x' * loss) / m; % /m is for the average

    theta = theta - (alphaNum * gradient);
  endfor    

  % Show final theta values
  display(theta)

  % Show J(theta) graphic evolution to check it worked, tendency must be zero
  plot(iterations, costs);

endfunction

% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);

How do I get a Date without time in Java?

Definitely not the most correct way, but if you just need a quick solution to get the date without the time and you do not wish to use a third party library this should do

    Date db = db.substring(0, 10) + db.substring(23,28);

I only needed the date for visual purposes and couldn't Joda so I substringed.

document.getElementById("test").style.display="hidden" not working

There are two ways of doing this.

Most of the answers have correctly pointed out that style.display has no value called "hidden". It should be none.

If you want to use "hidden" the syntax should be as follows.

object.style.visibility="hidden"

The difference between the two is the visibility="hidden" property will only hide the contents of you element but retain it position on the page. Whereas the display ="none" will hide your complete element and the rest of the elements on the page will fill that void created by it.

Check this illustration

Receiving login prompt using integrated windows authentication

Add permission [Domain Users] to your web security.

  • Right click on your site in IIS under the Sites folder
  • Click Edit Permissions...
  • Select the Security tab
  • Under the Group or usernames section click the Edit... button
  • In the Permissions pop up, under the Group or user names click Add...
  • Enter [Domain Users] in the object names to select text area and click OK to apply the change
  • Click OK to close the Permissions pop up
  • Click OK to close the Properties pop up and apply your new settings

OS specific instructions in CMAKE: How to?

Try that:

if(WIN32)
    set(ADDITIONAL_LIBRARIES wsock32)
else()
    set(ADDITIONAL_LIBRARIES "")
endif()

target_link_libraries(${PROJECT_NAME} bioutils ${ADDITIONAL_LIBRARIES})

You can find other useful variables here.

IOS - How to segue programmatically using swift

This worked for me.

First of all give the view controller in your storyboard a Storyboard ID inside the identity inspector. Then use the following example code (ensuring the class, storyboard name and story board ID match those that you are using):

let viewController:
UIViewController = UIStoryboard(
    name: "Main", bundle: nil
).instantiateViewControllerWithIdentifier("ViewController") as UIViewController
// .instantiatViewControllerWithIdentifier() returns AnyObject!
// this must be downcast to utilize it

self.presentViewController(viewController, animated: false, completion: nil)

For more details see http://sketchytech.blogspot.com/2012/11/instantiate-view-controller-using.html best wishes

c++ compile error: ISO C++ forbids comparison between pointer and integer

You have two ways to fix this. The preferred way is to use:

string answer;

(instead of char). The other possible way to fix it is:

if (answer == 'y') ...

(note single quotes instead of double, representing a char constant).

What is it exactly a BLOB in a DBMS context

any large single block of data stored in a database, such as a picture or sound file, which does not include record fields, and cannot be directly searched by the database's search engine.

Angular ng-repeat add bootstrap row every 3 or 4 cols

I did it only using boostrap, you must be very careful in the location of the row and the column, here is my example.

_x000D_
_x000D_
<section>_x000D_
<div class="container">_x000D_
        <div ng-app="myApp">_x000D_
        _x000D_
                <div ng-controller="SubregionController">_x000D_
                    <div class="row text-center">_x000D_
                        <div class="col-md-4" ng-repeat="post in posts">_x000D_
                            <div >_x000D_
                                <div>{{post.title}}</div>_x000D_
                            </div>_x000D_
                        </div>_x000D_
                    _x000D_
                    </div>_x000D_
                </div>        _x000D_
        </div>_x000D_
    </div>_x000D_
</div> _x000D_
_x000D_
</section>
_x000D_
_x000D_
_x000D_

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

Update and left outer join statements

In mysql the SET clause needs to come after the JOIN. Example:

UPDATE e
    LEFT JOIN a ON a.id = e.aid
    SET e.id = 2
    WHERE  
        e.type = 'user' AND
        a.country = 'US';

The transaction manager has disabled its support for remote/network transactions

I was having this issue with a linked server in SSMS while trying to create a stored procedure.

On the linked server, I changed the server option "Enable Promotion on Distributed Transaction" to False.

Screenshot of Server Options

Convert seconds to Hour:Minute:Second

Solution from: https://gist.github.com/SteveJobzniak/c91a8e2426bac5cb9b0cbc1bdbc45e4b

Here is a very clean and short method!

This code avoids as much as possible of the tedious function calls and piece-by-piece string-building, and the big and bulky functions people are making for this.

It produces "1h05m00s" format and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.

And it skips all empty leading components to avoid giving you useless info like "0h00m01s" (instead that will show up as "1s").

Example results: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".

$duration = 1; // values 0 and higher are supported!
$converted = [
    'hours' => floor( $duration / 3600 ),
    'minutes' => floor( ( $duration / 60 ) % 60 ),
    'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }

If you want to make the code even shorter (but less readable), you can avoid the $converted array and instead put the values directly in the sprintf() call, as follows:

$duration = 1; // values 0 and higher are supported!
$result = ltrim( sprintf( '%02dh%02dm%02ds', floor( $duration / 3600 ), floor( ( $duration / 60 ) % 60 ), ( $duration % 60 ) ), '0hm' );
if( $result == 's' ) { $result = '0s'; }

Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead:

$duration = -493; // negative values are supported!
$wasNegative = FALSE;
if( $duration < 0 ) { $wasNegative = TRUE; $duration = abs( $duration ); }
$converted = [
    'hours' => floor( $duration / 3600 ),
    'minutes' => floor( ( $duration / 60 ) % 60 ),
    'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
if( $wasNegative ) { $result = "-{$result}"; }
// $result is now "-8m13s"

Difference between return and exit in Bash functions

Sometimes, you run a script using . or source.

. a.sh

If you include an exit in the a.sh, it will not just terminate the script, but end your shell session.

If you include a return in the a.sh, it simply stops processing the script.

Try-catch speeding up my code?

Jon's disassemblies show, that the difference between the two versions is that the fast version uses a pair of registers (esi,edi) to store one of the local variables where the slow version doesn't.

The JIT compiler makes different assumptions regarding register use for code that contains a try-catch block vs. code which doesn't. This causes it to make different register allocation choices. In this case, this favors the code with the try-catch block. Different code may lead to the opposite effect, so I would not count this as a general-purpose speed-up technique.

In the end, it's very hard to tell which code will end up running the fastest. Something like register allocation and the factors that influence it are such low-level implementation details that I don't see how any specific technique could reliably produce faster code.

For example, consider the following two methods. They were adapted from a real-life example:

interface IIndexed { int this[int index] { get; set; } }
struct StructArray : IIndexed { 
    public int[] Array;
    public int this[int index] {
        get { return Array[index]; }
        set { Array[index] = value; }
    }
}

static int Generic<T>(int length, T a, T b) where T : IIndexed {
    int sum = 0;
    for (int i = 0; i < length; i++)
        sum += a[i] * b[i];
    return sum;
}
static int Specialized(int length, StructArray a, StructArray b) {
    int sum = 0;
    for (int i = 0; i < length; i++)
        sum += a[i] * b[i];
    return sum;
}

One is a generic version of the other. Replacing the generic type with StructArray would make the methods identical. Because StructArray is a value type, it gets its own compiled version of the generic method. Yet the actual running time is significantly longer than the specialized method's, but only for x86. For x64, the timings are pretty much identical. In other cases, I've observed differences for x64 as well.

How do I disable the resizable property of a textarea?

I have created a small demo to show how resize properties work. I hope it will help you and others as well.

_x000D_
_x000D_
.resizeable {_x000D_
  resize: both;_x000D_
}_x000D_
_x000D_
.noResizeable {_x000D_
  resize: none;_x000D_
}_x000D_
_x000D_
.resizeable_V {_x000D_
  resize: vertical;_x000D_
}_x000D_
_x000D_
.resizeable_H {_x000D_
  resize: horizontal;_x000D_
}
_x000D_
<textarea class="resizeable" rows="5" cols="20" name="resizeable" title="This is Resizable.">_x000D_
This is Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="noResizeable" rows="5" title="This will not Resizable. " cols="20" name="resizeable">_x000D_
This will not Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="resizeable_V" title="This is Vertically Resizable." rows="5" cols="20" name="resizeable">_x000D_
This is Vertically Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="resizeable_H" title="This is Horizontally Resizable." rows="5" cols="20" name="resizeable">_x000D_
This is Horizontally Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>
_x000D_
_x000D_
_x000D_

Replace negative values in an numpy array

Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.

>>> a = [1, 2, 3, -4, 5]

>>> def zero_if_negative(x):
...   if x < 0:
...     return 0
...   return x
...

>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]

>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]

Remote JMX connection

I know this thread is pretty old, but there's an additional option that will help greatly. See here: https://realjenius.com/2012/11/21/java7-jmx-tunneling-freedom/

-Dcom.sun.management.jmxremote.rmi.port=1099

How do I check if an element is hidden in jQuery?

A jQuery solution, but it is still a bit better for those who want to change the button text as well:

_x000D_
_x000D_
$(function(){_x000D_
  $("#showHide").click(function(){_x000D_
    var btn = $(this);_x000D_
    $("#content").toggle(function () {_x000D_
      btn.text($(this).css("display") === 'none' ? "Show" : "Hide");_x000D_
    });_x000D_
   });_x000D_
 });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button id="showHide">Hide</button>_x000D_
<div id="content">_x000D_
  <h2>Some content</h2>_x000D_
  <p>_x000D_
  What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Add Whatsapp function to website, like sms, tel

This is possible by creating the following link:

whatsapp://send?text=Hello this has been opened from the browser&phone=+PHONENUMBER&abid=+PHONENUMBER

Thanks to:

https://forum.ionicframework.com/t/open-whatsapp-intent-with-msg-specific-contact/73903/4

I have tested this on iOS, Windows Phone and Android

Wordpress keeps redirecting to install-php after migration

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

This situation means that:

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

AND

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

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

Possible causes:

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

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

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

LINQ: Select where object does not contain items from list

dump this into a more specific collection of just the ids you don't want

var notTheseBarIds = filterBars.Select(fb => fb.BarId);

then try this:

fooSelect = (from f in fooBunch
             where !notTheseBarIds.Contains(f.BarId)
             select f).ToList();

or this:

fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();

Show history of a file?

The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?

You can use git blame for this, it will anotate each line with a SHA1 and a date when it was changed. git blame can also tell you when a certain line was deleted or where it was moved if you are interested in that.

If you are trying to find out, when a certain bug was introduced, git bisect is a very powerfull tool. git bisect will do a binary search on your history. You can use git bisect start to start bisecting, then git bisect bad to mark a commit where the bug is present and git bisect good to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.

Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.

If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.

How can you speed up Eclipse?

Go to Windows -> Preferences -> Validation and uncheck any validators you don't want or need.

For Eclipse 3.7, you use Windows -> Preferences -> General -> Startup and Shutdown.

Easy way to get a test file into JUnit

I know you said you didn't want to read the file in by hand, but this is pretty easy

public class FooTest
{
    private BufferedReader in = null;

    @Before
    public void setup()
        throws IOException
    {
        in = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("/data.txt")));
    }

    @After
    public void teardown()
        throws IOException
    {
        if (in != null)
        {
            in.close();
        }

        in = null;
    }

    @Test
    public void testFoo()
        throws IOException
    {
        String line = in.readLine();

        assertThat(line, notNullValue());
    }
}

All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

Top answers don't point to an even simpler and more flexible solution.

just place a

@TestPropertySource(properties=
{"spring.autoconfigure.exclude=comma.seperated.ClassNames,com.example.FooAutoConfiguration"})
@SpringBootTest
public class MySpringTest {...}

annotation above your test class. This means other tests aren't affected by the current test's special case. If there is a configuration affecting most of your tests, then consider using the spring profile instead as the current top answer suggests.

Thanks to @skirsch for encouraging me to upgrade this from a comment to an answer.

How to list all AWS S3 objects in a bucket using Java

I am processing a large collection of objects generated by our system; we changed the format of the stored data and needed to check each file, determine which ones were in the old format, and convert them. There are other ways to do this, but this one relates to your question.

    ObjectListing list = amazonS3Client.listObjects(contentBucketName, contentKeyPrefix);

    do {                

        List<S3ObjectSummary> summaries = list.getObjectSummaries();

        for (S3ObjectSummary summary : summaries) {

            String summaryKey = summary.getKey();               

            /* Retrieve object */

            /* Process it */

        }

        list = amazonS3Client.listNextBatchOfObjects(list);

    }while (list.isTruncated());

Escape double quotes for JSON in Python

Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}

Generate full SQL script from EF 5 Code First Migrations

The API appears to have changed (or at least, it doesn't work for me).

Running the following in the Package Manager Console works as expected:

Update-Database -Script -SourceMigration:0

How do I exit the Vim editor?

Hit the Esc key to enter "Normal mode". Then you can type : to enter "Command-line mode". A colon (:) will appear at the bottom of the screen and you can type in one of the following commands. To execute a command, press the Enter key.

  • :q to quit (short for :quit)
  • :q! to quit without saving (short for :quit!)
  • :wq to write and quit
  • :wq! to write and quit even if file has only read permission (if file does not have write permission: force write)
  • :x to write and quit (similar to :wq, but only write if there are changes)
  • :exit to write and exit (same as :x)
  • :qa to quit all (short for :quitall)
  • :cq to quit without saving and make Vim return non-zero error (i.e. exit with error)

You can also exit Vim directly from "Normal mode" by typing ZZ to save and quit (same as :x) or ZQ to just quit (same as :q!). (Note that case is important here. ZZ and zz do not mean the same thing.)

Vim has extensive help - that you can access with the :help command - where you can find answers to all your questions and a tutorial for beginners.

How to import a bak file into SQL Server Express

There is a step by step explanation (with pictures) available @ Restore DataBase

  1. Click Start, select All Programs, click Microsoft SQL Server 2008 and select SQL Server Management Studio.
    This will bring up the Connect to Server dialog box.
    Ensure that the Server name YourServerName and that Authentication is set to Windows Authentication.
    Click Connect.

  2. On the right, right-click Databases and select Restore Database.
    This will bring up the Restore Database window.

  3. On the Restore Database screen, select the From Device radio button and click the "..." box.
    This will bring up the Specify Backup screen.

  4. On the Specify Backup screen, click Add.
    This will bring up the Locate Backup File.

  5. Select the DBBackup folder and chose your BackUp File(s).

  6. On the Restore Database screen, under Select the backup sets to restore: place a check in the Restore box, next to your data and in the drop-down next to To database: select DbName.

  7. You're done.

Selecting text in an element (akin to highlighting with your mouse)

here is another simple solution to get the selected the text in the form of string, you can use this string easily to append a div element child into your code:

var text = '';

if (window.getSelection) {
    text = window.getSelection();

} else if (document.getSelection) {
    text = document.getSelection();

} else if (document.selection) {
    text = document.selection.createRange().text;
}

text = text.toString();

Why do abstract classes in Java have constructors?

Implementation wise you will often see inside super() statement in subclasses constructors, something like:


public class A extends AbstractB{

  public A(...){
     super(String constructorArgForB, ...);
     ...
  }
}


Code for download video from Youtube on Java, Android

METHOD 1 ( Recommanded )

Library YouTubeExtractor

Add into your gradle file

 allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }

And dependencies

 compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'

Add this small code and you done. Demo HERE

public class MainActivity extends AppCompatActivity {

    private static final String YOUTUBE_ID = "ea4-5mrpGfE";

    private final YouTubeExtractor mExtractor = YouTubeExtractor.create();


    private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
        @Override
        public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
            bindVideoResult(response.body());
        }

        @Override
        public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
            onError(t);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//        For android youtube extractor library  com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
        mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);

    }


    private void onError(Throwable t) {
        t.printStackTrace();
        Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
    }


    private void bindVideoResult(YouTubeExtractionResult result) {

//        Here you can get download url link
        Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());

        Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
    }
}

You can get download link in bindVideoResult() method.

METHOD 2

Using this library android-youtubeExtractor

Add into gradle file

repositories {
    maven { url "https://jitpack.io" }
}

compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'

Here is the code for getting download url.

       String youtubeLink = "http://youtube.com/watch?v=xxxx";

    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
        @Override
        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
            if (ytFiles != null) {
                int itag = 22;
// Here you can get download url
                String downloadUrl = ytFiles.get(itag).getUrl();
            }
        }
    };

    ytEx.execute(youtubeLink);

Can't push to remote branch, cannot be resolved to branch

Had the same problem with different casing.

Did a checkout to development (or master) then changed the name (the wrong name) to something else like test.

  • git checkout development
  • git branch -m wrong-name test

then change the name back to the right name

  • git branch -m test right-name

then checkout to the right-name branch

  • git checkout right-name

then it worked to push to the remote branch

  • git push origin right-name

indexOf and lastIndexOf in PHP?

In php:

  • stripos() function is used to find the position of the first occurrence of a case-insensitive substring in a string.

  • strripos() function is used to find the position of the last occurrence of a case-insensitive substring in a string.

Sample code:

$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);

echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;

Output: Fist index = 2 Last index = 13

How much should a function trust another function

The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.

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

In short it is much simple compared to html, the long doctype is removed and also center and font tag is removed. I also answered this difference in my blog : http://ravisinghblog.in/key-difference-between-html-and-html-5/

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

Issue has been resolved after updating Android studio version to 3.3-rc2 or latest released version.

cr: @shadowsheep

have to change version under /gradle/wrapper/gradle-wrapper.properties. refer below url https://stackoverflow.com/a/56412795/7532946

Eclipse won't compile/run java file

Your project has to have a builder set for it. If there is not one Eclipse will default to Ant. Which you can use you have to create an Ant build file, which you can Google how to do. It is rather involved though. This is not required to run locally in Eclipse though. If your class is run-able. It looks like yours is, but we can not see all of it.

If you look at your project build path do you have an output folder selected? If you check that folder have the compiled class files been put there? If not the something is not set in Eclpise for it to know to compile. You might check to see if auto build is set for your project.

Getting Chrome to accept self-signed localhost certificate

  1. Add the CA certificate in the trusted root CA Store.

  2. Go to chrome and enable this flag!

chrome://flags/#allow-insecure-localhost

At last, simply use the *.me domain or any valid domains like *.com and *.net and maintain them in the host file. For my local devs, I use *.me or *.com with a host file maintained as follows:

  1. Add to host. C:/windows/system32/drivers/etc/hosts

    127.0.0.1 nextwebapp.me

Note: If the browser is already opened when doing this, the error will keep on showing. So, please close the browser and start again. Better yet, go incognito or start a new session for immediate effect.

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

in laravel used decimal column type for migration

$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);

for more information see available column type

CSS to hide INPUT BUTTON value text

This works in Firefox 3, Internet Explorer 8, Internet Explorer 8 compatibility mode, Opera, and Safari.

*Note: table cell containing this has padding:0 and text-align:center.

background: none;
background-image: url(../images/image.gif);
background-repeat:no-repeat;
overflow:hidden;
border: NONE;
width: 41px; /*width of image*/
height: 19px; /*height of image*/
font-size: 0;
padding: 0 0 0 41px;
cursor:pointer;

What's the best visual merge tool for Git?

Diffuse is my favourite but of course I am biased. :-) It is very easy to use:

$ diffuse "mine" "output" "theirs"

Diffuse is a small and simple text merge tool written in Python. With Diffuse, you can easily merge, edit, and review changes to your code. Diffuse is free software.

How do I modify the URL without reloading the page?

Here is my solution (newUrl is your new URL which you want to replace with the current one):

history.pushState({}, null, newUrl);

SQL update from one Table to another based on a ID match

This will allow you to update a table based on the column value not being found in another table.

    UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (
            SELECT * 
            FROM (
                    SELECT table1.id
                    FROM  table1 
                    LEFT JOIN table2 ON ( table2.column = table1.column ) 
                    WHERE table1.column = 'some_expected_val'
                    AND table12.column IS NULL
            ) AS Xalias
    )

This will update a table based on the column value being found in both tables.

    UPDATE table1 SET table1.column = 'some_new_val' WHERE table1.id IN (
            SELECT * 
            FROM (
                    SELECT table1.id
                    FROM  table1 
                    JOIN table2 ON ( table2.column = table1.column ) 
                    WHERE table1.column = 'some_expected_val'
            ) AS Xalias
    )

How to add the JDBC mysql driver to an Eclipse project?

you haven't loaded driver into memory. use this following in init()

Class.forName("com.mysql.jdbc.Driver");

Also, you missed a colon (:) in url, use this

String mySqlUrl = "jdbc:mysql://localhost:3306/mysql";

How many characters in varchar(max)

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

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.

Vertically align text within a div

This is the simplest way to do it if you need multiple lines. Wrap you span'd text in another span and specify its height with line-height. The trick to multiple lines is resetting the inner span's line-height.

<span class="textvalignmiddle"><span>YOUR TEXT HERE</span></span>
.textvalignmiddle {
    line-height: /* Set height */;
}

.textvalignmiddle > span {
    display: inline-block;
    vertical-align: middle;
    line-height: 1em; /* Set line height back to normal */
}

DEMO

Of course the outer span could be a div or what have you.

How to terminate a window in tmux?

By default
<Prefix> & for killing a window
<Prefix> x for killing a pane
And you can add config info

vi ~/.tmux.conf
bind-key X kill-session

then
<Prefix> X for killing a session

sql query to get earliest date

While using TOP or a sub-query both work, I would break the problem into steps:

Find target record

SELECT MIN( date ) AS date, id
FROM myTable
WHERE id = 2
GROUP BY id

Join to get other fields

SELECT mt.id, mt.name, mt.score, mt.date
FROM myTable mt
INNER JOIN
( 
   SELECT MIN( date ) AS date, id
   FROM myTable
   WHERE id = 2
   GROUP BY id
) x ON x.date = mt.date AND x.id = mt.id

While this solution, using derived tables, is longer, it is:

  • Easier to test
  • Self documenting
  • Extendable

It is easier to test as parts of the query can be run standalone.

It is self documenting as the query directly reflects the requirement ie the derived table lists the row where id = 2 with the earliest date.

It is extendable as if another condition is required, this can be easily added to the derived table.

What's the best way to check if a String represents an integer in Java?

If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using Integer.parseInt().

public static boolean isInteger(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    if (length == 0) {
        return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
        if (length == 1) {
            return false;
        }
        i = 1;
    }
    for (; i < length; i++) {
        char c = str.charAt(i);
        if (c < '0' || c > '9') {
            return false;
        }
    }
    return true;
}

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.

I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.

i hope this will help.

Adding three months to a date in PHP

Add nth Days, months and years

$n = 2;
for ($i = 0; $i <= $n; $i++){
    $d = strtotime("$i days");
    $x = strtotime("$i month");
    $y = strtotime("$i year");
    echo "Dates : ".$dates = date('d M Y', "+$d days");
    echo "<br>";
    echo "Months : ".$months = date('M Y', "+$x months");
    echo '<br>';
    echo "Years : ".$years = date('Y', "+$y years");
    echo '<br>';
}

ImportError: No module named google.protobuf

I got the same error message as in the title, but in my case import google was working and import google.protobuf wasn't (on python3.5, ubuntu 16.04).

It turned out that I've installed python3-google-apputils package (using apt) and it was installed to '/usr/lib/python3/dist-packages/google/apputils/', while protobuf (which was installed using pip) was in "/usr/lib/python3.5/dist-packages/google/protobuf/" - and it was a "google" namespace collapse.

Uninstalling google-apputils (from apt, and reinstalling it using pip) solved the problem.

sudo apt remove python3-google-apputils
sudo pip3 install google-apputils

PadLeft function in T-SQL

This is what I normally use when I need to pad a value.

SET @PaddedValue = REPLICATE('0', @Length - LEN(@OrigValue)) + CAST(@OrigValue as VARCHAR)

if var == False

I think what you are looking for is the 'not' operator?

if not var

Reference page: http://www.tutorialspoint.com/python/logical_operators_example.htm

SQL: set existing column as Primary Key in MySQL

Either run in SQL:

ALTER TABLE tableName
  ADD PRIMARY KEY (id)           ---or Drugid, whichever you want it to be PK

or use the PHPMyAdmin interface (Table Structure)

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

One more idea for anyone else getting this...

I had some gzipped svg, but it had a php error in the output, which caused this error message. (Because there was text in the middle of gzip binary.) Fixing the php error solved it.

jQuery DIV click, with anchors

<div class="info">
   <h2>Takvim</h2>
   <a href="item-list.php"> Click Me !</a>
</div>


$(document).delegate("div.info", "click", function() {
   window.location = $(this).find("a").attr("href");
});

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

How to scroll to top of long ScrollView layout?

This is force scroll for scrollview :

            scrollView.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.scrollTo(0, 0);
                    scrollView.pageScroll(View.FOCUS_UP);
                    scrollView.smoothScrollTo(0,0);
                }
            });

How can you find out which process is listening on a TCP or UDP port on Windows?

netstat -ao and netstat -ab tell you the application, but if you're not a system administrator you'll get "The requested operation requires elevation".

It's not ideal, but if you use Sysinternals' Process Explorer you can go to specific processes' properties and look at the TCP tab to see if they're using the port you're interested in. It is a bit of a needle and haystack thing, but maybe it'll help someone...

Error: Argument is not a function, got undefined

Turns out it's the Cache of the browser, using Chrome here. Simply check the "Disable cache" under Inspect (Element) solved my problem.

Android Studio drawable folders

Just to make complete all answers, 'drawable' is, literally, a drawable image, not a complete and ready set of pixels, as .png

In other word words, drawable is only for vectorial images, just try right-click on 'drawable' and go New > Vector Asset, it will accept it, while Image Asset won't be added.

The data for 'drawing', generating the image is recorded on a XML file like this:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="#FF000000"
    android:pathData="M6,18c0,0.55 0.45,1 1,1h1v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,
    -0.67 1.5,-1.5L11,19h2v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5L16,
    19h1c0.55,0 1,-0.45 1,-1L18,8L6,8v10zM3.5,8C2.67,8 2,8.67 2,9.5v7c0,0.83 0.67,
    1.5 1.5,1.5S5,17.33 5,16.5v-7C5,8.67 4.33,8 3.5,8zM20.5,8c-0.83,0 -1.5,0.67 -1.5,
    1.5v7c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5v-7c0,-0.83 -0.67,-1.5 -1.5,-1.5zM15.53,
    2.16l1.3,-1.3c0.2,-0.2 0.2,-0.51 0,-0.71 -0.2,-0.2 -0.51,-0.2 -0.71,0l-1.48,1.48C13.85,
    1.23 12.95,1 12,1c-0.96,0 -1.86,0.23 -2.66,0.63L7.85,0.15c-0.2,-0.2 -0.51,-0.2 -0.71,0 -0.2,
    0.2 -0.2,0.51 0,0.71l1.31,1.31C6.97,3.26 6,5.01 6,7h12c0,-1.99 -0.97,-3.75 -2.47,-4.84zM10,
    5L9,5L9,4h1v1zM15,5h-1L14,4h1v1z"/>
  </vector>

That's the code for ic_android_black_24dp

Python set to list

This will work:

>>> t = [1,1,2,2,3,3,4,5]
>>> print list(set(t))
[1,2,3,4,5]

However, if you have used "list" or "set" as a variable name you will get the:

TypeError: 'set' object is not callable

eg:

>>> set = [1,1,2,2,3,3,4,5]
>>> print list(set(set))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

Same error will occur if you have used "list" as a variable name.

How do you find out which version of GTK+ is installed on Ubuntu?

To make the answer more general than Ubuntu (I have Redhat):

gtk is usually installed under /usr, but possibly in other locations. This should be visible in environment variables. Check with

env | grep gtk

Then try to find where your gtk files are stored. For example, use locate and grep.

locate gtk | grep /usr/lib

In this way, I found /usr/lib64/gtk-2.0, which contains the subdirectory 2.10.0, which contains many .so library files. My conclusion is that I have gtk+ version 2.10. This is rather consistent with the rpm command on Redhat: rpm -qa | grep gtk2, so I think my conclusion is right.

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

How to convert Calendar to java.sql.Date in Java?

There is a getTime() method (unsure why it's not called getDate).

Edit: Just realized you need a java.sql.Date. One of the answers which use cal.getTimeInMillis() is what you need.

Testing socket connection in Python

It seems that you catch not the exception you wanna catch out there :)

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you're catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

I am using this method to avoid the popup blocker in my React code. it will work in all other javascript codes also.

When you are making an async call on click event, just open a blank window first and then write the URL in that later when an async call will complete.

const popupWindow = window.open("", "_blank");
popupWindow.document.write("<div>Loading, Plesae wait...</div>")

on async call's success, write the following

popupWindow.document.write(resonse.url)

How should I validate an e-mail address?

You can use regular expression to do so. Something like the following.

Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");

String email = "[email protected]";

Matcher matcher = pattern.matcher(email);

boolean matchFound = matcher.matches();

Note: Check the regular expression given above, don't use it as it is.

Why can't Python find shared objects that are in directories in sys.path?

I use python setup.py build_ext -R/usr/local/lib -I/usr/local/include/libcalg-1.0 and the compiled .so file is under the build folder. you can type python setup.py --help build_ext to see the explanations of -R and -I

How to remove part of a string?

The following snippet will print "REGISTER here"

$string = "REGISTER 11223344 here";

$result = preg_replace(
   array('/(\d+)/'),
   array(''),
   $string
);

print_r($result);

The preg_replace() API usage us as given below.

$result = preg_replace(
    array('/pattern1/', '/pattern2/'),
    array('replace1', 'replace2'),
    $input_string
);

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

try put cd before the file path

example:

C:\Users\user>cd C:\Program Files\MongoDB\Server\4.4\bin

Conda command is not recognized on Windows 10

The newest version of the Anaconda installer for Windows will also install a windows launcher for "Anaconda Prompt" and "Anaconda Powershell Prompt". If you use one of those instead of the regular windows cmd shell, the conda command, python etc. should be available by default in this shell.

enter image description here

Adding values to specific DataTable cells

Try this:

dt.Rows[RowNumber]["ColumnName"] = "Your value"

For example: if you want to add value 5 (number 5) to 1st row and column name "index" you would do this

dt.Rows[0]["index"] = 5;

I believe DataTable row starts with 0

How to set the 'selected option' of a select dropdown list with jquery

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

jQuery add class .active on menu

this work for me :D

    function setActive() {
      aObj = document.getElementById('menu').getElementsByTagName('a');
      for(i=0;i<aObj.length;i++) {
        if(document.location.href.indexOf(aObj[i].href)>=0) {
          var activeurl = window.location;
          $('a[href="'+activeurl+'"]').parent('li').addClass('active');
        }
      }
    }

    window.onload = setActive;

How to delete all files from a specific folder?

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);

Or in a single line:

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

You said programmatically, right? I hope C# is ok. I know you said that you tried SMO and it didn't quite do what you wanted, so this probably won't be perfect for your request, but it will programmatically read out legit SQL statements that you could run to recreate the stored procedure. If it doesn't have the GO statements that you want, you can probably assume that each of the strings in the StringCollection could have a GO after it. You may not get that comment with the date and time in it, but in my similar sounding project (big-ass deployment tool that has to back up everything individually), this has done rather nicely. If you have a prior base that you wanted to work from, and you still have the original database to run this on, I'd consider tossing the initial effort and restandardizing on this output.

using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
…
string connectionString = … /* some connection string */;
ServerConnection sc = new ServerConnection(connectionString);
Server s = new Server(connection);
Database db = new Database(s, … /* database name */);
StoredProcedure sp = new StoredProcedure(db, … /* stored procedure name */);
StringCollection statements = sp.Script;

What is the native keyword in Java for?

functions that implement native code are declared native.

The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be called by, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

http://en.wikipedia.org/wiki/Java_Native_Interface

Multi-Column Join in Hibernate/JPA Annotations

This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key

i.e., one to one mapping based on 3 different columns

@Entity
@Table(name = "foo")
public class foo implements Serializable
{
    @Column(name="foocol1")
    private String foocol1;
    //add getter setter
    @Column(name="foocol2")
    private String foocol2;
    //add getter setter
    @Column(name="foocol3")
    private String foocol3;
    //add getter setter
    private Boo boo;
    private int id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "brsitem_id", updatable = false)
    public int getId()
    {
        return this.id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @OneToOne
    @JoinColumns(
    {
        @JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
        @JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
        @JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
    }
    )
    public Boo getBoo()
    {
        return boo;
    }
    public void setBoo(Boo boo)
    {
        this.boo = boo;
    }
}





@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
    private int id;
    @Column(name="boocol1")
    private String boocol1;
    //add getter setter
    @Column(name="boocol2")
    private String boocol2;
    //add getter setter
    @Column(name="boocol3")
    private String boocol3;
    //add getter setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id", updatable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
}

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

Try changing server name to "localhost"

pymssql.connect(server="localhost", user="myusername", password="mypwd", database="temp",port="1433")

loop through json array jquery

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I had similar issue, I was able to solve it using -U option along with mvn command as

mvn clean install -U

This worked for me, hope it helps.

How do I set the visibility of a text box in SSRS using an expression?

Switch your false and true returns? I think if you put those as a function in the visibility area, then false will show it and true will not show it.

Sending email in .NET through Gmail

How to Set App-specific password for gmail

If your Google password doesn't work, you may need to create an app-specific password for Gmail on Google. https://support.google.com/accounts/answer/185833?hl=en

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

How to delete a workspace in Eclipse?

It's possible to remove the workspace in Eclipse without much complications. The options are available under Preferences->General->Startup and Shutdown->Workspaces.

Note that this does not actually delete the files from the system, it simply removes it from the list of suggested workspaces. It changes the org.eclipse.ui.ide.prefs file in Jon's answer from within Eclipse.

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

React Native Error: ENOSPC: System limit for number of file watchers reached

The meaning of this error is that the number of files monitored by the system has reached the limit!!

Result: The command executed failed! Or throw a warning (such as executing a react-native start VSCode)

Solution:

Modify the number of system monitoring files

Ubuntu

sudo gedit /etc/sysctl.conf

Add a line at the bottom

fs.inotify.max_user_watches=524288

Then save and exit!

sudo sysctl -p

to check it

Then it is solved!

Converting JSON String to Dictionary Not List

You can use the following:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

FlutterError: Unable to load asset

You should consider the indentation for assets

flutter:

  assets:
    - images/pizza1.png
    - images/pizza0.png

More details:

flutter:

[2 whitespaces or 1 tab]assets:
[4 whitespaces or 2 tabs]- images/pizza1.png
[4 whitespaces or 2 tabs]- images/pizza0.png

Box-Shadow on the left side of the element only

box-shadow: inset 10px 0 0 0 red;

How to get the indexpath.row when an element is activated?

USING A SINGLE TAG FOR ROWS AND SECTIONS

There is a simple way to use tags for transmitting the row/item AND the section of a TableView/CollectionView at the same time.

Encode the IndexPath for your UIView.tag in cellForRowAtIndexPath :

buttonForCell.tag = convertIndexPathToTag(with: indexPath)

Decode the IndexPath from your sender in your target selector:

    @IBAction func touchUpInsideButton(sender: UIButton, forEvent event: UIEvent) {

        var indexPathForButton = convertTagToIndexPath(from: sender)

    }

Encoder and Decoder:

func convertIndexPathToTag(indexPath: IndexPath) -> Int {
    var tag: Int = indexPath.row + (1_000_000 * indexPath.section)
    
    return tag
}

func convertTagToIndexPath(from sender: UIButton) -> IndexPath {
    var section: Int = Int((Float(sender.tag) / 1_000_000).rounded(.down))
    var row: Int = sender.tag - (1_000_000 * section)

    return IndexPath(row: row, section: section)
}

Provided that you don’t need more than 4294967296 rows/items on a 32bit device ;-) e.g.

  • 42949 sections with 100_000 items/rows
  • 4294 sections with 1_000_000 items/rows - (like in the example above)
  • 429 sections with 10_000_000 items/rows

—-

WARNING: Keep in mind that when deleting or inserting rows/items in your TableView/CollectionView you have to reload all rows/items after your insertion/deletion point in order to keep the tag numbers of your buttons in sync with your model.

—-

Doctrine findBy 'does not equal'

There is now a an approach to do this, using Doctrine's Criteria.

A full example can be seen in How to use a findBy method with comparative criteria, but a brief answer follows.

use \Doctrine\Common\Collections\Criteria;

// Add a not equals parameter to your criteria
$criteria = new Criteria();
$criteria->where(Criteria::expr()->neq('prize', 200));

// Find all from the repository matching your criteria
$result = $entityRepository->matching($criteria);

How to increase font size in the Xcode editor?

For Xcode 12: (beta 3)

For the code editing windows, use the new

Editor -> Font Size -> Increase

or

Editor -> Font Size -> Decrease

menu items. This globally increases or decreases the font sizes for all editing windows. There is also an

Editor -> Font Size -> Reset

option. These also respond to the ?+ or ?- keyboard shortcuts.

By default, the file navigator on the left side corresponds to the

System Preferences -> General -> Sidebar icon size

You can also override the system size inside Xcode using the

Xcode -> Preferences -> General -> Navigator Size

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

Convert base-2 binary number string to int

If you wanna know what is happening behind the scene, then here you go.

class Binary():
def __init__(self, binNumber):
    self._binNumber = binNumber
    self._binNumber = self._binNumber[::-1]
    self._binNumber = list(self._binNumber)
    self._x = [1]
    self._count = 1
    self._change = 2
    self._amount = 0
    print(self._ToNumber(self._binNumber))
def _ToNumber(self, number):
    self._number = number
    for i in range (1, len (self._number)):
        self._total = self._count * self._change
        self._count = self._total
        self._x.append(self._count)
    self._deep = zip(self._number, self._x)
    for self._k, self._v in self._deep:
        if self._k == '1':
            self._amount += self._v
    return self._amount
mo = Binary('101111110')

Not receiving Google OAuth refresh token

1. How to get 'refresh_token' ?

Solution: access_type='offline' option should be used when generating authURL. source : Using OAuth 2.0 for Web Server Applications

2. But even with 'access_type=offline', I am not getting the 'refresh_token' ?

Solution: Please note that you will get it only on the first request, so if you are storing it somewhere and there is a provision to overwrite this in your code when getting new access_token after previous expires, then make sure not to overwrite this value.

From Google Auth Doc : (this value = access_type)

This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.

If you need 'refresh_token' again, then you need to remove access for your app as by following the steps written in Rich Sutton's answer.

How to update Android Studio automatically?

If you go to help>>check for updates it will tell you if there's an update.

You don't have to change from the stable channel. If you aren't offered an update and restart button, kindly close the window and try again. After about 4 or 5 checks like this, it will eventually show you update and restart button.

Why? because google.

Set Matplotlib colorbar size to match graph

You can do this easily with a matplotlib AxisDivider.

The example from the linked page also works without using subplots:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

enter image description here

How to put text over images in html?

You can try this...

<div class="image">

      <img src="" alt="" />

      <h2>Text you want to display over the image</h2>

</div>

CSS

.image { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
   width: 100%; 
}

iPhone UITextField - Change placeholder text color

You can override drawPlaceholderInRect:(CGRect)rect as such to manually render the placeholder text:

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}

Java FileReader encoding issue

Since Java 11 you may use that:

public FileReader(String fileName, Charset charset) throws IOException;

Setting default value in select drop-down using Angularjs

You can do it with following code(track by),

<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>

Where IN clause in LINQ

This expression should do what you want to achieve.

dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))

How do I clone a specific Git branch?

git clone --single-branch --branch <branchname> <remote-repo>

The --single-branch option is valid from version 1.7.10 and later.

Please see also the other answer which many people prefer.

You may also want to make sure you understand the difference. And the difference is: by invoking git clone --branch <branchname> url you're fetching all the branches and checking out one. That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your frontpage, you may end up cloning 5GB of data.

Again, that is not to say git clone --branch is not the way to accomplish that, it's just that it's not always what you want to accomplish, when you're asking about cloning a specific branch.

What is an NP-complete in computer science?

What is NP?

NP is the set of all decision problems (questions with a yes-or-no answer) for which the 'yes'-answers can be verified in polynomial time (O(nk) where n is the problem size, and k is a constant) by a deterministic Turing machine. Polynomial time is sometimes used as the definition of fast or quickly.

What is P?

P is the set of all decision problems which can be solved in polynomial time by a deterministic Turing machine. Since they can be solved in polynomial time, they can also be verified in polynomial time. Therefore P is a subset of NP.

What is NP-Complete?

A problem x that is in NP is also in NP-Complete if and only if every other problem in NP can be quickly (ie. in polynomial time) transformed into x.

In other words:

  1. x is in NP, and
  2. Every problem in NP is reducible to x

So, what makes NP-Complete so interesting is that if any one of the NP-Complete problems was to be solved quickly, then all NP problems can be solved quickly.

See also the post What's "P=NP?", and why is it such a famous question?

What is NP-Hard?

NP-Hard are problems that are at least as hard as the hardest problems in NP. Note that NP-Complete problems are also NP-hard. However not all NP-hard problems are NP (or even a decision problem), despite having NP as a prefix. That is the NP in NP-hard does not mean non-deterministic polynomial time. Yes, this is confusing, but its usage is entrenched and unlikely to change.

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

C# difference between == and Equals()

I am a bit confused here. If the runtime type of Content is of type string, then both == and Equals should return true. However, since this does not appear to be the case, then runtime type of Content is not string and calling Equals on it is doing a referential equality and this explains why Equals("Energy Attack") fails. However, in the second case, the decision as to which overloaded == static operator should be called is made at compile time and this decision appears to be ==(string,string). this suggests to me that Content provides an implicit conversion to string.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

In a MVC application, I got this warning because I was opening a Kendo Window with a method that was returning a View(), instead of a PartialView(). The View() was trying to retrive again all the scripts of the page.

Visual Studio: ContextSwitchDeadlock

You can solve this by unchecking contextswitchdeadlock from

Debug->Exceptions ... -> Expand MDA node -> uncheck -> contextswitchdeadlock

Clean up a fork and restart it from the upstream

Love VonC's answer. Here's an easy version of it for beginners.

There is a git remote called origin which I am sure you are all aware of. Basically, you can add as many remotes to a git repo as you want. So, what we can do is introduce a new remote which is the original repo not the fork. I like to call it original

Let's add original repo's to our fork as a remote.

git remote add original https://git-repo/original/original.git

Now let's fetch the original repo to make sure we have the latest coded

git fetch original

As, VonC suggested, make sure we are on the master.

git checkout master

Now to bring our fork up to speed with the latest code on original repo, all we have to do is hard reset our master branch in accordance with the original remote.

git reset --hard original/master

And you are done :)

Getting the docstring from a function

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code

How to execute a command in a remote computer?

I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

execcmd \\yourremoteserver <your command here>

Doesn't get any simpler than this :)

Initialise numpy array of unknown length

For posterity, I think this is quicker:

a = np.array([np.array(list()) for _ in y])

You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.


Responding to comment below:

>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object)], dtype=object)

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

How to hide a <option> in a <select> menu with CSS?

Since you're already using JS, you could create a hidden SELECT element on the page, and for each item you are trying to hide in that list, move it to the hidden list. This way, they can be easily restored.

I don't know a way offhand of doing it in pure CSS... I would have thought that the display:none trick would have worked.

How to get the Google Map based on Latitude on Longitude?

Firstly add a div with id.

<div id="my_map_add" style="width:100%;height:300px;"></div>

<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>

What is the GAC in .NET?

The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system. Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). GAC is a machine wide a local cache of assemblies maintained by the .NET Framework.

Is it better to use "is" or "==" for number comparison in Python?

== is what you want, "is" just happens to work on your examples.

What is a typedef enum in Objective-C?

typedef is useful for redefining the name of an existing variable type. It provides short & meaningful way to call a datatype. e.g:

typedef unsigned long int TWOWORDS;

here, the type unsigned long int is redefined to be of the type TWOWORDS. Thus, we can now declare variables of type unsigned long int by writing,

TWOWORDS var1, var2;

instead of

unsigned long int var1, var2;

What is the difference/usage of homebrew, macports or other package installation tools?

Currently, Macports has many more packages (~18.6 K) than there are Homebrew formulae (~3.1K), owing to its maturity. Homebrew is slowly catching up though.

Macport packages tend to be maintained by a single person.

Macports can keep multiple versions of packages around, and you can enable or disable them to test things out. Sometimes this list can get corrupted and you have to manually edit it to get things back in order, although this is not too hard.

Both package managers will ask to be regularly updated. This can take some time.

Note: you can have both package managers on your system! It is not one or the other. Brew might complain but Macports won't.

Also, if you are dealing with python or ruby packages, use a virtual environment wherever possible.