Programs & Examples On #Site column

Installing mysql-python on Centos

I have Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503.

For me it worked with the following command:

# pip install mysql-python

Note pre-requisites here:

Install Python pip:

# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm

# yum -y update
Reboot the machine (if kernel is also updated)

# yum -y install python-pip

Install Python devel packages:

# yum install python-devel

Install MySQL devel packages:

# yum install mysql-devel

JavaScript string and number conversion

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'

Add column with number of days between dates in DataFrame pandas

To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html

So,

df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days

which returns:

             A          B   C
one 2014-01-01 2014-02-28  58
two 2014-02-03 2014-03-01  26

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

localhost refused to connect Error in visual studio

I've tried everything but nothing worked, but this did. If you can debug on local IIS instead of Express, change the configurations as shown in the image below. Do not forget to click on "Create virtual directory"

enter image description here

How do you convert an entire directory with ffmpeg?

Previous answer will only create 1 output file called out.mov. To make a separate output file for each old movie, try this.

for i in *.avi;
  do name=`echo "$i" | cut -d'.' -f1`
  echo "$name"
  ffmpeg -i "$i" "${name}.mov"
done

process.env.NODE_ENV is undefined

As early as possible in your application, require and configure dotenv.

require('dotenv').config()

How to return only the Date from a SQL Server DateTime datatype

On SQL Server 2008 and higher, you should CONVERT to date:

SELECT CONVERT(date, getdate())

On older versions, you can do the following:

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))

for example

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

gives me

2008-09-22 00:00:00.000

Pros:

  • No varchar<->datetime conversions required
  • No need to think about locale

As suggested by Michael

Use this variant: SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)

select getdate()

SELECT DATEADD(hh, DATEDIFF(hh, 0, getdate()), 0)
SELECT DATEADD(hh, 0, DATEDIFF(hh, 0, getdate()))

SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, getdate()))

SELECT DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
SELECT DATEADD(mm, 0, DATEDIFF(mm, 0, getdate()))

SELECT DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
SELECT DATEADD(yy, 0, DATEDIFF(yy, 0, getdate()))

Output:

2019-04-19 08:09:35.557

2019-04-19 08:00:00.000
4763-02-17 00:00:00.000

2019-04-19 00:00:00.000
2019-04-19 00:00:00.000

2019-04-01 00:00:00.000
1903-12-03 00:00:00.000

2019-01-01 00:00:00.000
1900-04-30 00:00:00.000

Copy Image from Remote Server Over HTTP

use

$imageString = file_get_contents("http://example.com/image.jpg");
$save = file_put_contents('Image/saveto/image.jpg',$imageString);

Change header background color of modal of twitter bootstrap

You can use the css below, put this in your custom css to override the bootstrap css.

.modal-header {
    padding:9px 15px;
    border-bottom:1px solid #eee;
    background-color: #0480be;
    -webkit-border-top-left-radius: 5px;
    -webkit-border-top-right-radius: 5px;
    -moz-border-radius-topleft: 5px;
    -moz-border-radius-topright: 5px;
     border-top-left-radius: 5px;
     border-top-right-radius: 5px;
 }

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

Delete element in a slice

Rather than thinking of the indices in the [a:]-, [:b]- and [a:b]-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0 before the element indexed as 0.

enter image description here

Looking at just the blue numbers, it's much easier to see what is going on: [0:3] encloses everything, [3:3] is empty and [1:2] would yield {"B"}. Then [a:] is just the short version of [a:len(arrayOrSlice)], [:b] the short version of [0:b] and [:] the short version of [0:len(arrayOrSlice)]. The latter is commonly used to turn an array into a slice when needed.

Filter LogCat to get only the messages from My Application in Android?

For me this works in mac Terminal
Got to the folder where you have adb then type below command in terminal

./adb logcat MyTAG:V AndroidRuntime:E *:S

Here it will filter all logs of MyTAG and AndroidRuntime

MySQLi count(*) always returns 1

You have to fetch that one record, it will contain the result of Count()

$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

clock() doesn't return milliseconds or seconds on linux. Usually clock() returns microseconds on a linux system. The proper way to interpret the value returned by clock() is to divide it by CLOCKS_PER_SEC to figure out how much time has passed.

How can I start PostgreSQL server on Mac OS X?

Homebrew is the way!!

To start the service:

brew services start postgresql

To list it:

brew services list | grep postgres

To stop the service:

brew services stop postgresql

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

I'm using following code (in C#) to change the color of the NavigationBar:

NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.Default);
NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.LandscapePhone);
NavigationController.NavigationBar.BackgroundColor = UIColor.Green;

The trick is that you need to get rid of the default background image and then the color will appear.

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Go to windows -> Preferences -> Java -> Installed JREs

may be jre is already added enter image description here

click on Add -> Standard VM -> Next -> Directory

and browse for the JDK in my case path was C:\Program Files\Java\jdk1.8.0_111

then Click on finish.

you will see window like thisenter image description here

select JDK -> Apply -> Ok

And You are done.

Select data between a date/time range

A simple way :

select  * from  hockey_stats 
where  game_date >= '2012-03-11' and game_date  <= '2012-05-11'

How do I animate constraint changes?

I was trying to animate Constraints and was not really easy to found a good explanation.

What other answers are saying is totally true: you need to call [self.view layoutIfNeeded]; inside animateWithDuration: animations:. However, the other important point is to have pointers for every NSLayoutConstraint you want to animate.

I created an example in GitHub.

Remove category & tag base from WordPress url - without a plugin

The dot trick will likely ruin your rss feeds and/or pagination. These work, though:

add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {
    $category_rewrite=array();
    $categories=get_categories(array('hide_empty'=>false));
    foreach($categories as $category) {
        $category_nicename = $category->slug;
        if ( $category->parent == $category->cat_ID )
            $category->parent = 0;
        elseif ($category->parent != 0 )
            $category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename;
        $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
        $category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
        $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';
    }
    global $wp_rewrite;
    $old_base = $wp_rewrite->get_category_permastruct();
    $old_base = str_replace( '%category%', '(.+)', $old_base );
    $old_base = trim($old_base, '/');
    $category_rewrite[$old_base.'$'] = 'index.php?category_redirect=$matches[1]';
    return $category_rewrite;
}

// remove tag base
add_filter('tag_rewrite_rules', 'no_tag_base_rewrite_rules');
function no_tag_base_rewrite_rules($tag_rewrite) {
    $tag_rewrite=array();
    $tags=get_tags(array('hide_empty'=>false));
    foreach($tags as $tag) {
        $tag_nicename = $tag->slug;
        if ( $tag->parent == $tag->tag_ID )
            $tag->parent = 0;
        elseif ($tag->parent != 0 )
            $tag_nicename = get_tag_parents( $tag->parent, false, '/', true ) . $tag_nicename;
        $tag_rewrite['('.$tag_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?tag=$matches[1]&feed=$matches[2]';
        $tag_rewrite['('.$tag_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?tag=$matches[1]&paged=$matches[2]';
        $tag_rewrite['('.$tag_nicename.')/?$'] = 'index.php?tag=$matches[1]';
    }
    global $wp_rewrite;
    $old_base = $wp_rewrite->get_tag_permastruct();
    $old_base = str_replace( '%tag%', '(.+)', $old_base );
    $old_base = trim($old_base, '/');
    $tag_rewrite[$old_base.'$'] = 'index.php?tag_redirect=$matches[1]';
    return $tag_rewrite;
}

// remove author base
add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules');
function no_author_base_rewrite_rules($author_rewrite) { 
    global $wpdb;    
    $author_rewrite = array();    
    $authors = $wpdb->get_results("SELECT user_nicename AS nicename from $wpdb->users");    
    foreach($authors as $author) {
        $author_rewrite["({$author->nicename})/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$"] = 'index.php?author_name=$matches[1]&feed=$matches[2]';
        $author_rewrite["({$author->nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
        $author_rewrite["({$author->nicename})/?$"] = 'index.php?author_name=$matches[1]';
    }      
    return $author_rewrite;}
add_filter('author_link', 'no_author_base', 1000, 2);
function no_author_base($link, $author_id) {
    $link_base = trailingslashit(get_option('home'));
    $link = preg_replace("|^{$link_base}author/|", '', $link);
    return $link_base . $link;
}

How to hide TabPage from TabControl

I realize the question is old, and the accepted answer is old, but ...

At least in .NET 4.0 ...

To hide a tab:

tabControl.TabPages.Remove(tabPage);

To put it back:

tabControl.TabPages.Insert(index, tabPage);

TabPages works so much better than Controls for this.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Make sure that you have put a log4j2.* file instead of a log4j.* file under .../src/main/resources folder.

Displaying standard DataTables in MVC

While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.

Get your Dataset into a List ..... I have a repository pattern and here is an example of getting a dataset from an old school asmx web service private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;

    public Get_Client_Repository()
        : this(new CISOnlineSRVDEV.ServiceSoapClient())
    {

    }
    public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
    {
        _ServiceSoapClient = serviceSoapClient;
    }


    public IEnumerable<IClient> GetClient(IClient client)
    {
        // ****  Calling teh web service with passing in the clientId and returning a dataset
        DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
                                                        client.ClientId,
                                                        client.AhcccsId,
                                                        client.LastName,
                                                        client.FirstName,
                                                        "");//client.BirthDate.ToString());  //TODO: NEED TO FIX

        // USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
        List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
                                 select new Client()
                                 {
                                     RbhaId = c[5].ToString(),
                                     ClientId = c[2].ToString(),
                                     AhcccsId = c[6].ToString(),
                                     LastName = c[0].ToString(), // Add another field called   Sex M/F  c[4]
                                     FirstName = c[1].ToString(),
                                     BirthDate = c[3].ToDateTime()  //extension helper  ToDateTime()
                                 }).ToList<IClient>();

        return clients;

    }

Then in the Controller I'm doing this

IClient client = (IClient)TempData["Client"];

// Instantiate and instance of the repository 
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);

// Call the View up passing in the data from the list
return View(model);

Then in the View it is easy :

@model IEnumerable<CISOnlineMVC.DAL.IClient>

@{
    ViewBag.Title = "CLIENT ALL INFORMATION";
}

<h2>CLIENT ALL INFORMATION</h2>

<table>
    <tr>
        <th></th>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Client ID</th>
        <th>DOB</th>
        <th>Gender</th>
        <th>RBHA ID</th>
        <th>AHCCCS ID</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
        </td>
        <td>
            @item.LastName
        </td>
        <td>
            @item.FirstName
        </td>
         <td>
            @item.ClientId
        </td>
         <td>
            @item.BirthDate
        </td>
         <td>
            Gender @* ADD in*@
        </td>
         <td>
            @item.RbhaId
        </td>
         <td>
            @item.AhcccsId
        </td>
    </tr>
}

</table>

How can I get Eclipse to show .* files?

1. From Package Explorer open the Filters... dialog:

enter image description here

2. Then uncheck .* resources option:

enter image description here

Jquery : Refresh/Reload the page on clicking a button

You can also use window.location.href=window.location.href;

How to set time to midnight for current day?

Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.

double utcOffset= 10.0;  // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;

var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);

How to implement the factory method pattern in C++ correctly

Simple Factory Example:

// Factory returns object and ownership
// Caller responsible for deletion.
#include <memory>
class FactoryReleaseOwnership{
  public:
    std::unique_ptr<Foo> createFooInSomeWay(){
      return std::unique_ptr<Foo>(new Foo(some, args));
    }
};

// Factory retains object ownership
// Thus returning a reference.
#include <boost/ptr_container/ptr_vector.hpp>
class FactoryRetainOwnership{
  boost::ptr_vector<Foo>  myFoo;
  public:
    Foo& createFooInSomeWay(){
      // Must take care that factory last longer than all references.
      // Could make myFoo static so it last as long as the application.
      myFoo.push_back(new Foo(some, args));
      return myFoo.back();
    }
};

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

If you are looking for TypeScript working functions then follow

public numericValue = (alphaChar: any) => alphaChar.toUpperCase().charCodeAt(0) - 64;

public alphaValue = (numericDigit: any) => 
   String.fromCharCode(64 + numericDigit) : '';

You can make several checks like (numericDigit >= 1 && numericDigit <= 26) ? inside function body as per the requirements.

How to see full query from SHOW PROCESSLIST

Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :

select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';

You can add any condition or ignore based on your requirement.

The output of the query is resulted as :

+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID    | USER | HOST            | DB     | COMMAND | TIME | STATE     | INFO                                                     |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
|     5 | ssss | localhost:41060 | somedb | Sleep   |    3 |           | NULL                                                     |
| 58169 | root | localhost       | somedb | Query   |    0 | executing | select * from sometable where tblColumnName = 'someName' |

Confirmation dialog on ng-click - AngularJS

I wish AngularJS had a built in confirmation dialog. Often, it is nicer to have a customized dialog than using the built in browser one.

I briefly used the twitter bootstrap until it was discontinued with version 6. I looked around for alternatives, but the ones I found were complicated. I decided to try the JQuery UI one.

Here is my sample that I call when I am about to remove something from ng-grid;

    // Define the Dialog and its properties.
    $("<div>Are you sure?</div>").dialog({
        resizable: false,
        modal: true,
        title: "Modal",
        height: 150,
        width: 400,
        buttons: {
            "Yes": function () {
                $(this).dialog('close');
                //proceed with delete...
                /*commented out but left in to show how I am using it in angular
                var index = $scope.myData.indexOf(row.entity);

                $http['delete']('/EPContacts.svc/json/' + $scope.myData[row.rowIndex].RecordID).success(function () { console.log("groovy baby"); });

                $scope.gridOptions.selectItem(index, false);
                $scope.myData.splice(index, 1);
                */
            },
            "No": function () {
                $(this).dialog('close');
                return;
            }
        }
    });

I hope this helps someone. I was pulling my hair out when I needed to upgrade ui-bootstrap-tpls.js but it broke my existing dialog. I came into work this morning, tried a few things and then realized I was over complicating.

#1062 - Duplicate entry for key 'PRIMARY'

  1. Make sure PRIMARY KEY was selected AUTO_INCREMENT.
  2. Just enable Auto increment by :
    ALTER TABLE [table name] AUTO_INCREMENT = 1
  3. When you execute the insert command you have to skip this key.

How does the keyword "use" work in PHP and can I import classes with it?

You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)

python tuple to dict

>>> dict([('hi','goodbye')])
{'hi': 'goodbye'}

Or:

>>> [ dict([i]) for i in (('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14)) ]
[{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

In testing IE7/8/9 I was getting an ActiveX warning trying to use this code snippet:

filter:progid:DXImageTransform.Microsoft.gradient

After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.

php how to go one level up on dirname(__FILE__)

For PHP < 5.3 use:

$upOne = realpath(dirname(__FILE__) . '/..');

In PHP 5.3 to 5.6 use:

$upOne = realpath(__DIR__ . '/..');

In PHP >= 7.0 use:

$upOne = dirname(__DIR__, 1);

A hex viewer / editor plugin for Notepad++?

There is an old plugin called HEX Editor here.

According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.

onchange event for html.dropdownlist

If you have a list view you can do this:

  1. Define a select list:

    @{
       var Acciones = new SelectList(new[]
       {
      new SelectListItem { Text = "Modificar", Value = 
       Url.Action("Edit", "Countries")},
      new SelectListItem { Text = "Detallar", Value = 
      Url.Action("Details", "Countries") },
      new SelectListItem { Text = "Eliminar", Value = 
      Url.Action("Delete", "Countries") },
     }, "Value", "Text");
    }
    
  2. Use the defined SelectList, creating a diferent id for each record (remember that id of each element must be unique in a view), and finally call a javascript function for onchange event (include parameters in example url and record key):

    @Html.DropDownList("ddAcciones", Acciones, "Acciones", new { id = 
    item.CountryID, @onchange = "RealizarAccion(this.value ,id)" })
    
  3. onchange function can be something as:

    @section Scripts {
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    
    <script type="text/javascript">
    
    function RealizarAccion(accion, country)
    {
    
        var url = accion + '/' + country;
        if (url != null && url != '') {
            window.location.href = url ;
        }
    }
    </script>
    
    @Scripts.Render("~/bundles/jqueryval")
    }
    

submitting a GET form with query string params and hidden params disappear

Your construction is illegal. You cannot include parameters in the action value of a form. What happens if you try this is going to depend on quirks of the browser. I wouldn't be surprised if it worked with one browser and not another. Even if it appeared to work, I would not rely on it, because the next version of the browser might change the behavior.

"But lets say I have parameters in query string and in hidden inputs, what can I do?" What you can do is fix the error. Not to be snide, but this is a little like asking, "But lets say my URL uses percent signs instead of slashes, what can I do?" The only possible answer is, you can fix the URL.

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

How to set bootstrap navbar active class with Angular JS?

I suggest using a directive on a link. Here is the fiddle.

But its not perfect yet. Watch out for the hashbangs ;)

Here is the javascript for directive:

angular.module('link', []).
  directive('activeLink', ['$location', function(location) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs, controller) {
        var clazz = attrs.activeLink;
        var path = attrs.href;
        path = path.substring(1); //hack because path does not return including hashbang
        scope.location = location;
        scope.$watch('location.path()', function(newPath) {
          if (path === newPath) {
            element.addClass(clazz);
          } else {
            element.removeClass(clazz);
          }
        });
      }
    };
  }]);

and here is how it would be used in html:

<div ng-app="link">
  <a href="#/one" active-link="active">One</a>
  <a href="#/two" active-link="active">One</a>
  <a href="#" active-link="active">home</a>
</div>

afterwards styling with css:

.active{ color:red; }

Android new Bottom Navigation bar or BottomNavigationView

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation" />

navigation.xml(inside menu)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/title_home"
        app:showAsAction="always|withText"
        android:enabled="true"/>

Inside onCreate() method,

BottomNavigationView navigation = (BottomNavigationView)findViewById(R.id.navigation);
//Dont forgot this line     
BottomNavigationViewHelper.disableShiftMode(navigation);

And Create class as below.

public class BottomNavigationViewHelper {
    public static void disableShiftMode(BottomNavigationView view) {
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
        try {
            Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
            shiftingMode.setAccessible(true);
            shiftingMode.setBoolean(menuView, false);
            shiftingMode.setAccessible(false);
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                //noinspection RestrictedApi
                item.setShiftingMode(false);
                // set once again checked value, so view will be updated
                //noinspection RestrictedApi
                item.setChecked(item.getItemData().isChecked());
            }
        } catch (NoSuchFieldException e) {
            Log.e("BNVHelper", "Unable to get shift mode field", e);
        } catch (IllegalAccessException e) {
            Log.e("BNVHelper", "Unable to change value of shift mode", e);
        }
    }
}

DataTable: Hide the Show Entries dropdown but keep the Search box

To disable the "Show Entries" label, use "bInfo", example: "bFilter" is the search component, but are active by default.

$(document).ready( function () {
  $('#example').dataTable( {
    "bInfo": false
  } );
} );

Enable or disable the table information display. This shows information about the data that is currently visible on the page, including information about filtered data if that action is being performed.

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

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

Not best answer but you can reuse an already created ca bundle using --cert option of pip, for instance:

pip install SQLAlchemy==1.1.15 --cert="C:\Users\myUser\certificates\my_ca-bundle.crt"

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

How to create a delay in Swift?

If you need to set a delay of less than a second, it is not necessary to set the .seconds parameter. I hope this is useful to someone.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
        // your code hear
})

Connecting to remote URL which requires authentication using Java

Use this code for basic authentication.

_x000D_
_x000D_
URL url = new URL(path);_x000D_
String userPass = "username:password";_x000D_
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or_x000D_
//String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));_x000D_
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();_x000D_
urlConnection.setRequestProperty("Authorization", basicAuth);_x000D_
urlConnection.connect();
_x000D_
_x000D_
_x000D_

Copying a HashMap in Java

Since this question is still unanswered and I had a similar problem, I will try to answer this. The problem (as others already mentioned) is that you just copy references to the same object and thus a modify on the copy will also modify the origin object. So what you have to to is to copy the object (your map value) itself. The far easiest way to do so is to make all your objects implementing the serializeable interface. Then serialize and deserialize your map to get a real copy. You can do this by yourself or use the apache commons SerializationUtils#clone() which you can find here: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SerializationUtils.html But be aware this is the simplest approach but it is an expensive task to serialize and deserialize a lot of objects.

What is a good way to handle exceptions when trying to read a file in python?

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

So the answer is either: "Tim's way" or "No, you're doing it correctly.".


Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
       try:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

Can't accept license agreement Android SDK Platform 24

I just ran into this issue, and what solved it for me on windows, you are using command line, and you recently installed the android sdk, you must restart Command Prompt or Power Shell after you install the android sdk.

How to test Spring Data repositories?

With Spring Boot + Spring Data it has become quite easy:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    MyRepository subject;

    @Test
    public void myTest() throws Exception {
        subject.save(new MyEntity());
    }
}

The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.

Tensorflow image reading & display

Just to give a complete answer:

filename_queue = tf.train.string_input_producer(['/Users/HANEL/Desktop/tf.png']) #  list of files to read

reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)

my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
  sess.run(init_op)

  # Start populating the filename queue.

  coord = tf.train.Coordinator()
  threads = tf.train.start_queue_runners(coord=coord)

  for i in range(1): #length of your filename list
    image = my_img.eval() #here is your image Tensor :) 

  print(image.shape)
  Image.fromarray(np.asarray(image)).show()

  coord.request_stop()
  coord.join(threads)

Or if you have a directory of images you can add them all via this Github source file

@mttk and @salvador-dali: I hope it is what you need

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How can I delete Docker's images?

In Bash:

for i in `sudo docker images|grep \<none\>|awk '{print $3}'`;do sudo docker rmi $i;done

This will remove all images with name "<none>". I found those images redundant.

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

How to make MySQL handle UTF-8 properly

I followed Javier's solution, but I added some different lines in my.cnf:

[myslqd]
skip-character-set-client-handshake
collation_server=utf8_unicode_ci
character_set_server=utf8 

I found this idea here: http://dev.mysql.com/doc/refman/5.0/en/charset-server.html in the first/only user comment on the bottom of the page. He mentions that skip-character-set-client-handshake has some importance.

Calculate rolling / moving average in C++

Basically I want to track the moving average of an ongoing stream of a stream of floating point numbers using the most recent 1000 numbers as a data sample.

Note that the below updates the total_ as elements as added/replaced, avoiding costly O(N) traversal to calculate the sum - needed for the average - on demand.

template <typename T, typename Total, size_t N>
class Moving_Average
{
  public:
    void operator()(T sample)
    {
        if (num_samples_ < N)
        {
            samples_[num_samples_++] = sample;
            total_ += sample;
        }
        else
        {
            T& oldest = samples_[num_samples_++ % N];
            total_ += sample - oldest;
            oldest = sample;
        }
    }

    operator double() const { return total_ / std::min(num_samples_, N); }

  private:
    T samples_[N];
    size_t num_samples_{0};
    Total total_{0};
};

Total is made a different parameter from T to support e.g. using a long long when totalling 1000 longs, an int for chars, or a double to total floats.

Issues

This is a bit flawed in that num_samples_ could conceptually wrap back to 0, but it's hard to imagine anyone having 2^64 samples: if concerned, use an extra bool data member to record when the container is first filled while cycling num_samples_ around the array (best then renamed something innocuous like "pos").

Another issue is inherent with floating point precision, and can be illustrated with a simple scenario for T=double, N=2: we start with total_ = 0, then inject samples...

  • 1E17, we execute total_ += 1E17, so total_ == 1E17, then inject

  • 1, we execute total += 1, but total_ == 1E17 still, as the "1" is too insignificant to change the 64-bit double representation of a number as large as 1E17, then we inject

  • 2, we execute total += 2 - 1E17, in which 2 - 1E17 is evaluated first and yields -1E17 as the 2 is lost to imprecision/insignificance, so to our total of 1E17 we add -1E17 and total_ becomes 0, despite current samples of 1 and 2 for which we'd want total_ to be 3. Our moving average will calculate 0 instead of 1.5. As we add another sample, we'll subtract the "oldest" 1 from total_ despite it never having been properly incorporated therein; our total_ and moving averages are likely to remain wrong.

You could add code that stores the highest recent total_ and if the current total_ is too small a fraction of that (a template parameter could provide a multiplicative threshold), you recalculate the total_ from all the samples in the samples_ array (and set highest_recent_total_ to the new total_), but I'll leave that to the reader who cares sufficiently.

What's NSLocalizedString equivalent in Swift?

I use next solution:

1) create extension:

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }
}

2) in Localizable.strings file:

"Hi" = "??????";

3) example of use:

myLabel.text = "Hi".localized

enjoy! ;)

--upd:--

for case with comments you can use this solution:

1) Extension:

extension String {
    func localized(withComment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
    }
}

2) in .strings file:

/* with !!! */
"Hi" = "??????!!!";

3) using:

myLabel.text = "Hi".localized(withComment: "with !!!")

How to generate random colors in matplotlib?

When less than 9 datasets:

colors = "bgrcmykw"
color_index = 0

for X,Y in data:
    scatter(X,Y, c=colors[color_index])
    color_index += 1

Why do I keep getting Delete 'cr' [prettier/prettier]?

I upgraded to "prettier": "^2.2.0" and error went away

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

How to change the Text color of Menu item in Android?

One simple line in your theme :)

<item name="android:actionMenuTextColor">@color/your_color</item>

What's the most efficient way to test two integer ranges for overlap?

Subtracting the Minimum of the ends of the ranges from the Maximum of the beginning seems to do the trick. If the result is less than or equal to zero, we have an overlap. This visualizes it well:

enter image description here

FileNotFoundError: [Errno 2] No such file or directory

Lets say we have a script in "c:\script.py" that contain :

result = open("index.html","r")
print(result.read())

Lets say that the index.html file is also in the same directory "c:\index.html" when i execute the script from cmd (or shell)

C:\Users\Amine>python c:\script.py

You will get error:

FileNotFoundError: [Errno 2] No such file or directory: 'index.html'

And that because "index.html" is not in working directory which is "C:\Users\Amine>". so in order to make it work you have to change the working directory

C:\python script.py

'<html><head></head><body></body></html>'

This is why is it preferable to use absolute path.

How do I clear/delete the current line in terminal?

You can use Ctrl+U to clear up to the beginning.

You can use Ctrl+W to delete just a word.

You can also use Ctrl+C to cancel.

If you want to keep the history, you can use Alt+Shift+# to make it a comment.


Bash Emacs Editing Mode Cheat Sheet

Create SQL identity as primary key?

This is similar to the scripts we generate on our team. Create the table first, then apply pk/fk and other constraints.

CREATE TABLE [dbo].[ImagenesUsuario] (
    [idImagen] [int] IDENTITY (1, 1) NOT NULL
)

ALTER TABLE [dbo].[ImagenesUsuario] ADD 
    CONSTRAINT [PK_ImagenesUsuario] PRIMARY KEY  CLUSTERED 
    (
        [idImagen]
    )  ON [PRIMARY] 

Check if string ends with one of the strings from a list

Just use:

if file_name.endswith(tuple(extensions)):

MySQL: Cloning a MySQL database on the same MySql instance

I don't think there is a method to do this. When PHPMyAdmin does this, it dumps the DB then re-inserts it under the new name.

Warning: comparison with string literals results in unspecified behaviour

You want to use strcmp() == 0 to compare strings instead of a simple ==, which will just compare if the pointers are the same (which they won't be in this case).

args[i] is a pointer to a string (a pointer to an array of chars null terminated), as is "&" or "<".

The expression argc[i] == "&" checks if the two pointers are the same (point to the same memory location).

The expression strcmp( argc[i], "&") == 0 will check if the contents of the two strings are the same.

Detect if HTML5 Video element is playing

Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events

_x000D_
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head>  _x000D_
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> _x000D_
<title>Html5 media events</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head> _x000D_
<body >_x000D_
    <div id="output"></div>_x000D_
    <video id="myVideo" width="320" height="176" controls autoplay>_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">_x000D_
    </video>_x000D_
    <script>_x000D_
        var media = document.getElementById('myVideo');_x000D_
_x000D_
        // Playing event_x000D_
        media.addEventListener("playing", function() {_x000D_
            $("#output").html("Playing event triggered");_x000D_
        });_x000D_
   _x000D_
        // Pause event_x000D_
        media.addEventListener("pause", function() { _x000D_
            $("#output").html("Pause event triggered"); _x000D_
        });_x000D_
_x000D_
        // Seeking event_x000D_
        media.addEventListener("seeking", function() { _x000D_
            $("#output").html("Seeking event triggered"); _x000D_
        });_x000D_
_x000D_
        // Volume changed event_x000D_
        media.addEventListener("volumechange", function(e) { _x000D_
            $("#output").html("Volumechange event triggered"); _x000D_
        });_x000D_
_x000D_
    </script>   _x000D_
</body> _x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I protect my .NET assemblies from decompilation?

I've heard about some projects that directly compile IL into native code. You can get some additional info from this post: Is it possible to compile .NET IL code to machine code?

how to set mongod --dbpath

You can use --dbpath flag in order to provide it with the parameters i.e, the directory address. I found it useful for Windows 10 OS.

With the default settings it is usually not required.

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

Undefined reference to 'vtable for xxx'

The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame(); instead you implement a non-member function, textualGame(). I think that adding the missing takeaway:: will fix that.

The cause of the last error is that you're calling a virtual function, initialData(), from the constructor of gameCore. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore), not the most derived class (takeaway). This particular function is pure virtual, and so calling it here gives undefined behaviour.

Two possible solutions:

  • Move the initialisation code for gameCore out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; or
  • Separate gameCore into two classes: an abstract interface to be implemented by takeaway, and a concrete class containing the state. Construct takeaway first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.

I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.

One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).

Convenient C++ struct initialisation

You could use a lambda:

const FooBar fb = [&] {
    FooBar fb;
    fb.foo = 12;
    fb.bar = 3.4;
    return fb;
}();

More information on this idiom can be found on Herb Sutter's blog.

Shorthand if/else statement Javascript

Here is a way to do it that works, but may not be best practise for any language really:

var x,y;
x='something';
y=1;
undefined === y || (x = y);

alternatively

undefined !== y && (x = y);

How to bind Dataset to DataGridView in windows application

following will show one table of dataset

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show

if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.

if two tables with same table schema

dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable

sample code to mode all tables

DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
     dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;

finding first day of the month in python

My solution to find the first and last day of the current month:

def find_current_month_last_day(today: datetime) -> datetime:
    if today.month == 2:
        return today.replace(day=28)

    if today.month in [4, 6, 9, 11]:
        return today.replace(day=30)

    return today.replace(day=31)


def current_month_first_and_last_days() -> tuple:
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    first_date = today.replace(day=1)
    last_date = find_current_month_last_day(today)
    return first_date, last_date

How can I increase the JVM memory?

If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m

Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini file which is present in your Eclipse home directory.

To get the size of the JVM during Runtime you can use Runtime.totalMemory() which returns the total amount of memory in the Java virtual machine, measured in bytes.

Why is the minidlna database not being refreshed?

AzP already provided most of the information, but some of it is incorrect.

First of all, there is no such option inotify_interval. The only option that exists is notify_interval and has nothing to do with inotify.

So to clarify, notify_interval controls how frequently the (mini)dlna server announces itself in the network. The default value of 895 means it will announce itself about once every 15 minutes, meaning clients will need at most 15 minutes to find the server. I personally use 1-5 minutes depending on client volatility in the network.

In terms of getting minidlna to find files that have been added, there are two options:

  • The first is equivalent to removing the file files.db and consists in restarting minidlna while passing the -R argument, which forces a full rescan and builds the database from scratch. Since version 1.2.0 there's now also the -r argument which performs a rebuild action. This preserves any existing database and drops and adds old and new records, respectively.
  • The second is to rely on inotify events by setting inotify=yes and restarting minidlna. If inotify is set to =no, the only option to update the file database is the forced full rescan.

Additionally, in order to have inotify working, the file-system must support inotify events, which is not the case in most remote file-systems. If you have minidlna running over NFS it will not see any inotify events because these are generated on the server side and not on the client.

Finally, even if inotify is working and is supported by the file-system, the user under which minidlna is running must be able to read the file, otherwise it will not be able to retrieve necessary metadata. In this case, the logfile (usually /var/log/minidlna.log) should contain useful information.

Powershell script to check if service is started, if not then start it

The below is a compact script that will check if "running" and attempt start service until the service returns as running.

$Service = 'ServiceName'
If ((Get-Service $Service).Status -ne 'Running') {
   do {
       Start-Service $Service -ErrorAction SilentlyContinue
       Start-Sleep 10
   } until ((Get-Service $Service).Status -eq 'Running')
} Return "$($Service) has STARTED"

How to disable Python warnings?

Look at the Temporarily Suppressing Warnings section of the Python docs:

If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

I don't condone it, but you could just suppress all warnings with this:

import warnings
warnings.filterwarnings("ignore")

Ex:

>>> import warnings
>>> def f():
...     print('before')
...     warnings.warn('you are warned!')
...     print('after')
...
>>> f()
before
<stdin>:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings("ignore")
>>> f()
before
after

Converting json results to a date

I use this:

function parseJsonDate(jsonDateString){
    return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}

Update 2018:

This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.

  • 2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object using dateObject.toISOString()
  • 1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object using dateObject.getTime()

What does the clearfix class do in css?

How floats work

When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.

float vs display:inline

Before the invention of display:inline-block, websites use float to set elements beside each other. float is preferred over display:inline since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.

Float problems

The main problem is that we're using float against its intended purpose.

Another is that while float allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>, the <div> will not impart 100px in height to the container.

Unlike position:absolute, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.

Clearfix to the rescue

What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear.

Examples

Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.

What you have

Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:

  • The first clearfix you have appends an invisible pseudo-element, which is styled clear:both, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.

  • The second one appends the style display:inline-block which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.

  • This was the reapplication of display:block due to IE-MAC rule above. This rule was "hidden" from IE-MAC.

All in all, these 3 rules keep the .clearfix working cross-browser, with old browsers in mind.

CSS Animation and Display None

CSS (or jQuery, for that matter) can't animate between display: none; and display: block;. Worse yet: it can't animate between height: 0 and height: auto. So you need to hard code the height (if you can't hard code the values then you need to use javascript, but this is an entirely different question);

#main-image{
    height: 0;
    overflow: hidden;
    background: red;
   -prefix-animation: slide 1s ease 3.5s forwards;
}

@-prefix-keyframes slide {
  from {height: 0;}
  to {height: 300px;}
}

You mention that you're using Animate.css, which I'm not familiar with, so this is a vanilla CSS.

You can see a demo here: http://jsfiddle.net/duopixel/qD5XX/

How can I select rows by range?

Use the LIMIT clause:

/* rows x- y numbers */
SELECT * FROM tbl LIMIT x,y;

refer : http://dev.mysql.com/doc/refman/5.0/en/select.html

How do I turn off autocommit for a MySQL client?

Instead of switching autocommit off manually at restore time you can already dump your MySQL data in a way that includes all necessary statements right into your SQL file.

The command line parameter for mysqldump is --no-autocommit. You might also consider to add --opt which sets a combination of other parameters to speed up restore operations.

Here is an example for a complete mysqldump command line as I use it, containing --no-autocommit and --opt:

mysqldump -hlocalhost -uMyUser -p'MyPassword' --no-autocommit --opt --default-character-set=utf8 --quote-names  MyDbName  >  dump.sql

For details of these parameters see the reference of mysqldump

Why am I getting error CS0246: The type or namespace name could not be found?

I had a similar problem after first pulling and starting a new solution. It was fixed in visual studio by first cleaning the project. Then restoring the packages. When I built again, there were no more type or namespace errors.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

I've been watching Douglas Crockford's video on this and his explanation for not using increment and decrement is that

  1. It has been used in the past in other languages to break the bounds of arrays and cause all manners of badness and
  2. That it is more confusing and inexperienced JS developers don't know exactly what it does.

Firstly arrays in JavaScript are dynamically sized and so, forgive me if I'm wrong, it is not possible to break the bounds of an array and access data that shouldn't be accessed using this method in JavaScript.

Secondly, should we avoid things that are complicated, surely the problem is not that we have this facility but the problem is that there are developers out there that claim to do JavaScript but don't know how these operators work?? It is simple enough. value++, give me the current value and after the expression add one to it, ++value, increment the value before giving me it.

Expressions like a ++ + ++ b, are simple to work out if you just remember the above.

var a = 1, b = 1, c;
c = a ++ + ++ b;
// c = 1 + 2 = 3; 
// a = 2 (equals two after the expression is finished);
// b = 2;

I suppose you've just got to remember who has to read through the code, if you have a team that knows JS inside out then you don't need to worry. If not then comment it, write it differently, etc. Do what you got to do. I don't think increment and decrement is inherently bad or bug generating, or vulnerability creating, maybe just less readable depending on your audience.

Btw, I think Douglas Crockford is a legend anyway, but I think he's caused a lot of scare over an operator that didn't deserve it.

I live to be proven wrong though...

How do I create directory if it doesn't exist to create a file?

An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:

public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.MoveTo(destination);
    }
}

Then use brand new MoveTo extension:

 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);

Check Methods extension documentation.

How to Generate unique file names in C#

  1. Create your timestamped filename following your normal process
  2. Check to see if filename exists
  3. False - save file
  4. True - Append additional character to file, perhaps a counter
  5. Go to step 2

Asking the user for input until they give a valid response

Yeah I'm 6 years late from the but this question deserves more up-to-date answer.

Separation of concerns

I am a big fan of Unix philosophy "Do one thing and do it well". In this type of problem, it is better practice to split the problem to

  • Ask input with get_input until the input is ok.
  • Validate in validator function. You could write different validators for different input queries.

Asking for input

It can be kept as simple as (Python 3+)

def myvalidator(value):
    try:
        value = int(value)
    except ValueError:
        return False
    return value >= 0

def get_input(prompt, validator, on_validationerror):
    while True:
        value = input(prompt)
        if validator(value):
            return value
        print(on_validationerror)

Example

In [2]: get_input('Give a positive number: ', myvalidator, 'Please, try again')
Give a positive number: foobar
Please, try again
Give a positive number: -10
Please, try again
Give a positive number: 42
Out[2]: '42'

Python 3.8+ Note

In Python 3.8+ you could use the walrus operator

def get_input(prompt, validator, on_validationerror):
    while not validator(value := input(prompt)):
        print(on_validationerror)
    return value 

What is the difference between Left, Right, Outer and Inner Joins?

Simple Example: Let's say you have a Students table, and a Lockers table. In SQL, the first table you specify in a join, Students, is the LEFT table, and the second one, Lockers, is the RIGHT table.

Each student can be assigned to a locker, so there is a LockerNumber column in the Student table. More than one student could potentially be in a single locker, but especially at the beginning of the school year, you may have some incoming students without lockers and some lockers that have no students assigned.

For the sake of this example, let's say you have 100 students, 70 of which have lockers. You have a total of 50 lockers, 40 of which have at least 1 student and 10 lockers have no student.

INNER JOIN is equivalent to "show me all students with lockers".
Any students without lockers, or any lockers without students are missing.
Returns 70 rows

LEFT OUTER JOIN would be "show me all students, with their corresponding locker if they have one".
This might be a general student list, or could be used to identify students with no locker.
Returns 100 rows

RIGHT OUTER JOIN would be "show me all lockers, and the students assigned to them if there are any".
This could be used to identify lockers that have no students assigned, or lockers that have too many students.
Returns 80 rows (list of 70 students in the 40 lockers, plus the 10 lockers with no student)

FULL OUTER JOIN would be silly and probably not much use.
Something like "show me all students and all lockers, and match them up where you can"
Returns 110 rows (all 100 students, including those without lockers. Plus the 10 lockers with no student)

CROSS JOIN is also fairly silly in this scenario.
It doesn't use the linked lockernumber field in the students table, so you basically end up with a big giant list of every possible student-to-locker pairing, whether or not it actually exists.
Returns 5000 rows (100 students x 50 lockers). Could be useful (with filtering) as a starting point to match up the new students with the empty lockers.

Install psycopg2 on Ubuntu

Using Ubuntu 12.04 it appears to work fine for me:

jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon: 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  python-psycopg2-doc
The following NEW packages will be installed
  python-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 334 not upgraded.
Need to get 153 kB of archives.

What error are you getting exactly? - double check you've spelt psycopg right - that's quite often a gotcha... and it never hurts to run an apt-get update to make sure your repo. is up to date.

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

I had received a similar error message. Think I inadvertently typed "9o" at start of first line of php.ini file. Once I removed that, I no longer received the "fatal error" messages. Hope this helps.

How do I merge my local uncommitted changes into another Git branch?

Stashing, temporary commits and rebasing may all be overkill. If you haven't added the changed files to the index, yet, then you may be able to just checkout the other branch.

git checkout branch2

This will work so long as no files that you are editing are different between branch1 and branch2. It will leave you on branch2 with you working changes preserved. If they are different then you can specify that you want to merge your local changes with the changes introduced by switching branches with the -m option to checkout.

git checkout -m branch2

If you've added changes to the index then you'll want to undo these changes with a reset first. (This will preserve your working copy, it will just remove the staged changes.)

git reset

How can I list the contents of a directory in Python?

Since Python 3.5, you can use os.scandir.

The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file to know if it's a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:

example to list a directory and print files bigger than max_value bytes:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

(read an extensive performance-based answer of mine here)

Java finished with non-zero exit value 2 - Android Gradle

Just in case if someone still struggling with this and have no clue why is this happening and how to fix. In fact this error

Error:Execution failed for task ':app:dexDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdkx.x.x_xx\bin\java.exe'' finished with non-zero exit value 2

can have many reasons to happen but certainly not something related to your JDK version so don't wast your time in wrong direction. These are two main reasons for this to happen

  1. You have same library or jar file included several places and some of them conflicting with each other.
  2. You are about to or already exceeded 65k method limit

First case can be fixed as follows: Find out which dependencies you have included multiple times. In order to do this run following command in android studio terminal

gradlew -q dependencies yourProjectName_usually_app:dependencies --configuration compile

this will return all the dependencies but jar files that you include from lib folder try to get rid of duplication marked with asterisk (*), this is not always possible but in some cases you still can do it, after this try to exclude modules that are included many times, you can do it like this

compile ('com.facebook.android:facebook-android-sdk:4.0.1'){
    exclude module: 'support-v4'
}

For the second case when you exceeding method limit suggestion is to try to minimize it by removing included libraries (note sounds like first solution) if no way to do it add multiDexEnabled true to your defaultConfig

defaultConfig {
   ...
   ...
   multiDexEnabled true
}

this increases method limit but it is not the best thing to do because of possible performance issues IMPORTANT adding only multiDexEnabled true to defaultConfig is not enough in fact on all devices running android <5 Lollipop it will result in unexpected behavior and NoClassDefFoundError. how to solve it is described here

Swift extract regex matches

I found that the accepted answer's solution unfortunately does not compile on Swift 3 for Linux. Here's a modified version, then, that does:

import Foundation

func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try RegularExpression(pattern: regex, options: [])
        let nsString = NSString(string: text)
        let results = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range) }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

The main differences are:

  1. Swift on Linux seems to require dropping the NS prefix on Foundation objects for which there is no Swift-native equivalent. (See Swift evolution proposal #86.)

  2. Swift on Linux also requires specifying the options arguments for both the RegularExpression initialization and the matches method.

  3. For some reason, coercing a String into an NSString doesn't work in Swift on Linux but initializing a new NSString with a String as the source does work.

This version also works with Swift 3 on macOS / Xcode with the sole exception that you must use the name NSRegularExpression instead of RegularExpression.

Django DB Settings 'Improperly Configured' Error

In your python shell/ipython do:

from django.conf import settings

settings.configure()

How do I run a simple bit of code in a new thread?

Here how can use threads with a progressBar , its just for understing how the threads works, in the form there are three progressBar and 4 button:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Thread t, t2, t3;
    private void Form1_Load(object sender, EventArgs e)
    {

        CheckForIllegalCrossThreadCalls = false;

         t = new Thread(birinicBar); //evry thread workes with a new progressBar


         t2 = new Thread(ikinciBar);


         t3 = new Thread(ucuncuBar);

    }

    public void birinicBar() //to make progressBar work
    {
        for (int i = 0; i < 100; i++) {
            progressBar1.Value++;
            Thread.Sleep(100); // this progressBar gonna work faster
        }
    }

    public void ikinciBar()
    {
        for (int i = 0; i < 100; i++)
        {
            progressBar2.Value++;
            Thread.Sleep(200);
        }


    }

    public void ucuncuBar()
    {
        for (int i = 0; i < 100; i++)
        {
            progressBar3.Value++;
            Thread.Sleep(300);
        }
    }

    private void button1_Click(object sender, EventArgs e) //that button to start the threads
    {
        t.Start();
        t2.Start(); t3.Start();

    }

    private void button4_Click(object sender, EventArgs e)//that button to stup the threads with the progressBar
    {
        t.Suspend();
        t2.Suspend();
        t3.Suspend();
    }

    private void button2_Click(object sender, EventArgs e)// that is for contuniue after stuping
    {
        t.Resume();
        t2.Resume();
        t3.Resume();
    }

    private void button3_Click(object sender, EventArgs e) // finally with that button you can remove all of the threads
    {
        t.Abort();
        t2.Abort();
        t3.Abort();
    }
}

What's the best way to select the minimum value from several columns?

You could also do this with a union query. As the number of columns increase, you would need to modify the query, but at least it would be a straight forward modification.

Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin
From   YourTable T
       Inner Join (
         Select A.Id, Min(A.Col1) As TheMin
         From   (
                Select Id, Col1
                From   YourTable

                Union All

                Select Id, Col2
                From   YourTable

                Union All

                Select Id, Col3
                From   YourTable
                ) As A
         Group By A.Id
       ) As A
       On T.Id = A.Id

Git and nasty "error: cannot lock existing info/refs fatal"

for me, removing .git/info/ref kick things going.There shouldn't be a ref file when git is not running. But in my case there were one for whatever reason and caused the problem.

Removing the file will not remove any of your local commits or branches.

linux shell script: split string, put them in an array then loop through them

Here's a variation on ashirazi's answer which doesn't rely on $IFS. It does have its own issues which I ouline below.

sentence="one;two;three"
sentence=${sentence//;/$'\n'}  # change the semicolons to white space
for word in $sentence
do
    echo "$word"
done

Here I've used a newline, but you could use a tab "\t" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS - it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I had the same issue when I changed the home directory of one use. In my case it was because of selinux. I used the below to fix the issue:

selinuxenabled 0
setenforce 0

Can't connect to Postgresql on port 5432

Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf and postgres.conf files I finally found out that my firewall was overriding everything and therefore blocking connections

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

What are good grep tools for Windows?

My tool of choice is the appropriately named Windows Grep:

  • nice simple GUI
  • supports search and replace
  • can show the lines around the lines found
  • can search within columns in CSVs and fixed-width files

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

    public static void ExportToExcel(DataGridView dgView)
    {
        Microsoft.Office.Interop.Excel.Application excelApp = null;
        try
        {
            // instantiating the excel application class
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
            currentWorksheet.Columns.ColumnWidth = 18;


            if (dgView.Rows.Count > 0)
            {
                currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
                int i = 1;
                foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
                {
                    // Excel work sheet indexing starts with 1
                    currentWorksheet.Cells[2, i] = dgviewColumn.Name;
                    ++i;
                }
                Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
                headerColumnRange.Font.Bold = true;
                headerColumnRange.Font.Color = 0xFF0000;
                //headerColumnRange.EntireColumn.AutoFit();
                int rowIndex = 0;
                for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
                {
                    DataGridViewRow dgRow = dgView.Rows[rowIndex];
                    for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
                    {
                        currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
                    }
                }
                Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
                fullTextRange.WrapText = true;
                fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("s");
                timeStamp = timeStamp.Replace(':', '-');
                timeStamp = timeStamp.Replace("T", "__");
                currentWorksheet.Cells[1, 1] = timeStamp;
                currentWorksheet.Cells[1, 2] = "No error occured";
            }
            using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
            {
                exportSaveFileDialog.Title = "Select Excel File";
                exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";

                if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
                {
                    string fullFileName = exportSaveFileDialog.FileName;
                   // currentWorkbook.SaveCopyAs(fullFileName);
                    // indicating that we already saved the workbook, otherwise call to Quit() will pop up
                    // the save file dialogue box

                    currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                    currentWorkbook.Saved = true;
                    MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            if (excelApp != null)
            {
                excelApp.Quit();
            }
        }



    }

Oracle SQL Query for listing all Schemas in a DB

Either of the following SQL will return all schema in Oracle DB.

  1. select owner FROM all_tables group by owner;
  2. select distinct owner FROM all_tables;

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

Proxy with urllib2

You have to install a ProxyHandler

urllib2.install_opener(
    urllib2.build_opener(
        urllib2.ProxyHandler({'http': '127.0.0.1'})
    )
)
urllib2.urlopen('http://www.google.com')

What does HTTP/1.1 302 mean exactly?

As per the http status code definitions a 302 indicates a (temporary) redirect. "The requested resource resides temporarily under a different URI"

The type or namespace name 'DbContext' could not be found

I had the same issue. Turns out, you need the EntityFramework.dll reference (and not System.Data.Entity).

I just pulled it from the MvcMusicStore application which you can download from: http://mvcmusicstore.codeplex.com/

It's also a useful example of how to use entity framework code-first with MVC.

UITextField text change event

Swift 3 Version

yourTextField.addTarget(self, action: #selector(YourControllerName.textChanges(_:)), for: UIControlEvents.editingChanged)

And get the changes in here

func textChanges(_ textField: UITextField) {
    let text = textField.text! // your desired text here
    // Now do whatever you want.
}

Hope it helps.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.

Laravel PHP Command Not Found

Add the following to .bashrc file (not .bash_profile).

export PATH="~/.composer/vendor/bin:$PATH" 

at the end of the file and then in terminal run source ~/.bashrc

To verify that:

echo $PATH

(Restart the terminal, Check & Confirm the path is there)

Run the laravel command!

Note: For Ubuntu 16 and above use below:

export PATH="~/.config/composer/vendor/bin:$PATH" 

Saving an image in OpenCV

hopefully this will save images form your webcam

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
   VideoCapture cap(0);

   Mat save_img;

   cap >> save_img;

   char Esc = 0;

   while (Esc != 27 && cap.isOpened()) {        
    bool Frame = cap.read(save_img);        
    if (!Frame || save_img.empty()) {       
        cout << "error: frame not read from webcam\n";      
        break;                                              
    }
    namedWindow("save_img", CV_WINDOW_NORMAL);  
    imshow("imgOriginal", save_img);            
    Esc = waitKey(1);
}
imwrite("test.jpg",save_img); 
}

querying WHERE condition to character length?

I think you want this:

select *
from dbo.table
where DATALENGTH(column_name) = 3

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

Convert Date To String

Use name Space

using System.Globalization;

Code

string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");

How do I get a button to open another activity?

Write code on xml file.

<Button android:width="wrap_content"
        android:height="wrap_content"
        android:id="@+id/button"
        android:text="Click"/>

Write Code in your java file

Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity(new Intent(getApplicationContext(),Secondclass.class));
           /* if you want to finish the first activity then just call
            finish(); */
        }
    });

Eclipse C++: Symbol 'std' could not be resolved

The includes folder in the project is probably missing /usr/include/c++. Goto your project in project explorer, right click -> Properties -> C\C++ Build -> Environment -> add -> value= /usr/include/c++. Restart eclipse.

useState set method not reflecting change immediately

You can solve it by using the useRef hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.

See this example:

var [state,setState,ref]=useStateRef(0)

It works exactly like useState but in addition, it gives you the current state under ref.current

Learn more:

Creating a file name as a timestamp in a batch job

I know this is an old post, but there is a FAR simpler answer (though maybe it only works in newer versions of windows). Just use the /t parameter for the DATE and TIME dos commands to only show the date or time and not prompt you to set it, like this:

@echo off
echo Starting test batch file > testlog.txt
date /t >> testlog.txt
time /t >> testlog.txt

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

ImportError: No module named _ssl

Did you build the Python from source? If so, you need the --with-ssl option while building.

Generating a random & unique 8 character string using MySQL

This function generates a Random string based on your input length and allowed characters like this:

SELECT str_rand(8, '23456789abcdefghijkmnpqrstuvwxyz');

function code:

DROP FUNCTION IF EXISTS str_rand;

DELIMITER //

CREATE FUNCTION str_rand(
    u_count INT UNSIGNED,
    v_chars TEXT
)
RETURNS TEXT
NOT DETERMINISTIC
NO SQL
SQL SECURITY INVOKER
COMMENT ''
BEGIN
    DECLARE v_retval TEXT DEFAULT '';
    DECLARE u_pos    INT UNSIGNED;
    DECLARE u        INT UNSIGNED;

    SET u = LENGTH(v_chars);
    WHILE u_count > 0
    DO
      SET u_pos = 1 + FLOOR(RAND() * u);
      SET v_retval = CONCAT(v_retval, MID(v_chars, u_pos, 1));
      SET u_count = u_count - 1;
    END WHILE;

    RETURN v_retval;
END;
//
DELIMITER ;

This code is based on shuffle string function sends by "Ross Smith II"

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

Stylish cannot do this because CSS cannot do this. CSS has no (pseudo) selectors for <input> value(s). See:

The :empty selector refers only to child nodes, not input values.
[value=""] does work; but only for the initial state. This is because a node's value attribute (that CSS sees), is not the same as the node's value property (Changed by the user or DOM javascript, and submitted as form data).

Unless you care only about the initial state, you must use a userscript or Greasemonkey script. Fortunately this is not hard. The following script will work in Chrome, or Firefox with Greasemonkey or Scriptish installed, or in any browser that supports userscripts (i.e. most browsers, except IE).

See a demo of the limits of CSS plus the javascript solution at this jsBin page.

// ==UserScript==
// @name     _Dynamically style inputs based on whether they are blank.
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

var inpsToMonitor = document.querySelectorAll (
    "form[name='JustCSS'] input[name^='inp']"
);
for (var J = inpsToMonitor.length - 1;  J >= 0;  --J) {
    inpsToMonitor[J].addEventListener ("change",    adjustStyling, false);
    inpsToMonitor[J].addEventListener ("keyup",     adjustStyling, false);
    inpsToMonitor[J].addEventListener ("focus",     adjustStyling, false);
    inpsToMonitor[J].addEventListener ("blur",      adjustStyling, false);
    inpsToMonitor[J].addEventListener ("mousedown", adjustStyling, false);

    //-- Initial update. note that IE support is NOT needed.
    var evt = document.createEvent ("HTMLEvents");
    evt.initEvent ("change", false, true);
    inpsToMonitor[J].dispatchEvent (evt);
}

function adjustStyling (zEvent) {
    var inpVal  = zEvent.target.value;
    if (inpVal  &&  inpVal.replace (/^\s+|\s+$/g, "") )
        zEvent.target.style.background = "lime";
    else
        zEvent.target.style.background = "inherit";
}

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Does "display:none" prevent an image from loading?

If so is there a way to not load the unnecessary content on mobile browsers?

use <img src="" srcset="">

http://www.webdesignerdepot.com/2015/08/the-state-of-responsive-images/

https://caniuse.com/#feat=srcset

How do I check how many options there are in a dropdown menu?

Get the number of options in a particular select element

$("#elementid option").length

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

Should black box or white box testing be the emphasis for testers?

In my experience most developers naturally migrate towards white box testing. Since we need to ensure that the underlying algorithm is "correct", we tend to focus more on the internals. But, as has been pointed out, both white and black box testing is important.

Therefore, I prefer to have testers focus more on the Black Box tests, to cover for the fact that most developers don't really do it, and frequently aren't very good at it.

That isn't to say that testers should be kept in the dark about how the system works, just that I prefer them to focus more on the problem domain and how actual users interact with the system, not whether the function SomeMethod(int x) will correctly throw an exception if x is equal to 5.

Git merge is not possible because I have unmerged files

I repeatedly had the same challenge sometime ago. This problem occurs mostly when you are trying to pull from the remote repository and you have some files on your local instance conflicting with the remote version, if you are using git from an IDE such as IntelliJ, you will be prompted and allowed to make a choice if you want to retain your own changes or you prefer the changes in the remote version to overwrite yours'. If you don't make any choice then you fall into this conflict. all you need to do is run:

git merge --abort # The unresolved conflict will be cleared off

And you can continue what you were doing before the break.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

Compile Views in ASP.NET MVC

Using Visual Studio's Productivity Power Tools (free) extension helps a bit. Specifically, the Solution Error Visualizer feature. With it, compilation errors marked visually in the solution explorer (in the source file where the error was found). For some reason, however, this feature does not work as with other errors anywhere else in the code.

With MVC views, any compile-time errors will still be underlined in red in their respective .cs files, but signaling these errors is not propagated upwards in the Solution Explorer (in no way, even not in the containing source file).

Thanks for BlueClouds for correcting my previous statement.

I have just reported this as an issue on the extension's github project.

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

How to get ° character in a string in python?

just use \xb0 (in a string); python will convert it automatically

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

If:

  • you want multiple, but not all, worksheets, and
  • you want a single df as an output

Then, you can pass a list of worksheet names. Which you could populate manually:

import pandas as pd
    
path = "C:\\Path\\To\\Your\\Data\\"
file = "data.xlsx"
sheet_lst_wanted = ["01_SomeName","05_SomeName","12_SomeName"] # tab names from Excel

### import and compile data ###
    
# read all sheets from list into an ordered dictionary    
dict_temp = pd.read_excel(path+file, sheet_name= sheet_lst_wanted)

# concatenate the ordered dict items into a dataframe
df = pd.concat(dict_temp, axis=0, ignore_index=True)

OR

A bit of automation is possible if your desired worksheets have a common naming convention that also allows you to differentiate from unwanted sheets:

# substitute following block for the sheet_lst_wanted line in above block

import xlrd

# string common to only worksheets you want
str_like = "SomeName" 
    
### create list of sheet names in Excel file ###
xls = xlrd.open_workbook(path+file, on_demand=True)
sheet_lst = xls.sheet_names()
    
### create list of sheets meeting criteria  ###
sheet_lst_wanted = []
    
for s in sheet_lst:
    # note: following conditional statement based on my sheets ending with the string defined in sheet_like
    if s[-len(str_like):] == str_like:
        sheet_lst_wanted.append(s)
    else:
        pass

Convert SVG to image (JPEG, PNG, etc.) in the browser

There are several ways to convert SVG to PNG using the Canvg library.

In my case, I needed to get the PNG blob from inline SVG.

The library documentation provides an example (see OffscreenCanvas example).

But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)

However, there is another way that will work in Firefox too.

const el = document.getElementById("some-svg"); //this is our inline SVG

var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;

const svg = new XMLSerializer().serializeToString(el); //convert SVG to string

//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();

let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

For the last line thanks to this answer

What are the Ruby File.open modes and options?

opt is new for ruby 1.9. The various options are documented in IO.new : www.ruby-doc.org/core/IO.html

XAMPP - Apache could not start - Attempting to start Apache service

I had a hard-coded IP in httpd.conf and my local IP had changed which was causing my issue, changed IP over and all worked again

SQL Server - Case Statement

Like so

DECLARE @t INT=1

SELECT CASE
            WHEN @t>0 THEN
                CASE
                    WHEN @t=1 THEN 'one'
                    ELSE 'not one'
                END
            ELSE 'less than one'
        END

EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.

Changing all files' extensions in a folder with one command on Windows

You can use ren (as in rename):

ren *.XXX *.YYY

And of course, switch XXX and YYY for the appropriate extensions. It will change from XXX to YYY. If you want to change all extensions, just use the wildcard again:

ren *.* *.YYY

One way to make this work recursively is with the FOR command. It can be used with the /R option to recursively apply a command to matching files. For example:

for /R %x in (*.txt) do ren "%x" *.renamed

will change all .txt extensions to .renamed recursively, starting in the current directory. %x is the variable that holds the matched file names.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.

Note: this works only on cmd. Won't work on Powershell or Bash

How to create an array containing 1...N

If I get what you are after, you want an array of numbers 1..n that you can later loop through.

If this is all you need, can you do this instead?

var foo = new Array(45); // create an empty array with length 45

then when you want to use it... (un-optimized, just for example)

for(var i = 0; i < foo.length; i++){
  document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>'); 
}

e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

See it in action here: http://jsfiddle.net/3kcvm/

How to define Singleton in TypeScript

I have found a new version of this that the Typescript compiler is totally okay with, and I think is better because it doesn't require calling a getInstance() method constantly.

import express, { Application } from 'express';

export class Singleton {
  // Define your props here
  private _express: Application = express();
  private static _instance: Singleton;

  constructor() {
    if (Singleton._instance) {
      return Singleton._instance;
    }

    // You don't have an instance, so continue

    // Remember, to set the _instance property
    Singleton._instance = this;
  }
}

This does come with a different drawback. If your Singleton does have any properties, then the Typescript compiler will throw a fit unless you initialize them with a value. That's why I included an _express property in my example class because unless you initialize it with a value, even if you assign it later in the constructor, Typescript will think it hasn't been defined. This could be fixed by disabling strict mode, but I prefer not to if possible. There is also another downside to this method I should point out, because the constructor is actually getting called, each time it does another instance is technically created, but not accessible. This could, in theory, cause memory leaks.

Node.js: Difference between req.query[] and req.params

Suppose you have defined your route name like this:

https://localhost:3000/user/:userid

which will become:

https://localhost:3000/user/5896544

Here, if you will print: request.params

{
userId : 5896544
}

so

request.params.userId = 5896544

so request.params is an object containing properties to the named route

and request.query comes from query parameters in the URL eg:

https://localhost:3000/user?userId=5896544 

request.query

{

userId: 5896544

}

so

request.query.userId = 5896544

pandas groupby sort within groups

If you don't need to sum a column, then use @tvashtar's answer. If you do need to sum, then you can use @joris' answer or this one which is very similar to it.

df.groupby(['job']).apply(lambda x: (x.groupby('source')
                                      .sum()
                                      .sort_values('count', ascending=False))
                                     .head(3))

Including all the jars in a directory within the Java classpath

Think of a jar file as the root of a directory structure. Yes, you need to add them all separately.

Download files from server php

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}

Scatter plot with error bars

Using ggplot and a little dplyr for data manipulation:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by call (e.g., group_by(x, file) if file is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file).

Android Studio: Gradle: error: cannot find symbol variable

Open project in android studio click file and click Invalidate Caches/Restart

bootstrap button shows blue outline when clicked

I found this quite useful in my case after the button click.

$('#buttonId').blur();

How do I convert a double into a string in C++?

You can convert any thing to anything using this function:

template<class T = std::string, class U>
T to(U a) {
    std::stringstream ss;
    T ret;
    ss << a;
    ss >> ret;
    return ret;
};

usage :

std::string str = to(2.5);
double d = to<double>("2.5");

How to fix C++ error: expected unqualified-id

Get rid of the semicolon after WordGame.

You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

How to iterate over rows in a DataFrame in Pandas

 for ind in df.index:
     print df['c1'][ind], df['c2'][ind]

How to copy a dictionary and only edit the copy

When you assign dict2 = dict1, you are not making a copy of dict1, it results in dict2 being just another name for dict1.

To copy the mutable types like dictionaries, use copy / deepcopy of the copy module.

import copy

dict2 = copy.deepcopy(dict1)

Does --disable-web-security Work In Chrome Anymore?

This flag worked for me at v30.0.1599.101 m enter image description here

The warning "You are using an unsupported command-line flag" can be ignored. The flag still works (as of Chrome v86).

jQuery - select the associated label element of a input field

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

Check if all values of array are equal

const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] )  // true

Or one-liner:

[1,1,1,1].every( (val, i, arr) => val === arr[0] )   // true

Array.prototype.every (from MDN) : The every() method tests whether all elements in the array pass the test implemented by the provided function.

IF-THEN-ELSE statements in postgresql

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,

select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:

 coalesce | coalesce |  x  |  y  
----------+----------+-----+-----
 abc      | abc      | abc | 
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr | 
(5 rows)

How do I verify that an Android apk is signed with a release certificate?

Use this command : (Jarsigner is in your Java bin folder goto java->jdk->bin path in cmd prompt)

$ jarsigner -verify my_signed.apk

If the .apk is signed properly, Jarsigner prints "jar verified"

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Determine the process pid listening on a certain port

netstat -p -l | grep $PORT and lsof -i :$PORT solutions are good but I prefer fuser $PORT/tcp extension syntax to POSIX (which work for coreutils) as with pipe:

pid=`fuser $PORT/tcp`

it prints pure pid so you can drop sed magic out.

One thing that makes fuser my lover tools is ability to send signal to that process directly (this syntax is also extension to POSIX):

$ fuser -k $port/tcp       # with SIGKILL
$ fuser -k -15 $port/tcp   # with SIGTERM
$ fuser -k -TERM $port/tcp # with SIGTERM

Also -k is supported by FreeBSD: http://www.freebsd.org/cgi/man.cgi?query=fuser

Asp.net Hyperlink control equivalent to <a href="#"></a>

I agree with SLaks, but here you go

   <asp:HyperLink id="hyperlink1" 
                  NavigateUrl="#"
                  Text=""
                  runat="server"/> 

or you can alter the href using

hyperlink1.NavigateUrl = "#"; 
hyperlink1.Text = string.empty;

How to sort findAll Doctrine's method?

This works for me:

$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(),array('name' => 'ASC'));

Keeping the first array empty fetches back all data, it worked in my case.

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi

or

"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

Which terminal command to get just IP address and nothing else?

I would Use Hostname -L to get just the IP to use as a variable in a script.

How to correct TypeError: Unicode-objects must be encoded before hashing?

import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())

My httpd.conf is empty

It seems to me, that it is by design that this file is empty.

A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf

So, you should have a look for /etc/apache2/apache2.conf

dynamically set iframe src

You should also consider that in some Opera versions onload is fired several times and add some hooks:

// fixing Opera 9.26, 10.00
if (doc.readyState && doc.readyState != 'complete') {
    // Opera fires load event multiple times
    // Even when the DOM is not ready yet
    // this fix should not affect other browsers
    return;
}

// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
    // In Opera 9.64 event was fired second time
    // when body.innerHTML changed from false
    // to server response approx. after 1 sec
    return;
}

Code borrowed from Ajax Upload

Performance of Arrays vs. Lists

The measurements are nice, but you are going to get significantly different results depending on what you're doing exactly in your inner loop. Measure your own situation. If you're using multi-threading, that alone is a non-trivial activity.

T-SQL How to create tables dynamically in stored procedures?

First up, you seem to be mixing table variables and tables.

Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.

If you just want to declare a table variable:

CREATE PROC sp_createATable 
  @name        VARCHAR(10), 
  @properties  VARCHAR(500) 
AS 
  declare @tablename TABLE
  ( 
    id  CHAR(10)  PRIMARY KEY 
  ); 

The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.

How to make php display \t \n as tab and new line instead of characters

"\t" not '\t', php doesnt escape in single quotes

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

MySQL: update a field only if condition is met

Another variation:

UPDATE test
SET field = IF ( {condition}, {new value}, field )
WHERE id = 123

This will update the field with {new value} only if {condition} is met

Change remote repository credentials (authentication) on Intellij IDEA 14

IN Android Studio 2.3

  1. Open Setting (CTRL+ALT+S)
  2. Select Other Settings (at the end)
  3. select Bitbucket

Here you can change your new Password or User

GROUP BY to combine/concat a column

A good question. Should tell you it took some time to crack this one. Here is my result.

DECLARE @TABLE TABLE
(  
ID INT,  
USERS VARCHAR(10),  
ACTIVITY VARCHAR(10),  
PAGEURL VARCHAR(10)  
)

INSERT INTO @TABLE  
VALUES  (1, 'Me', 'act1', 'ab'),
        (2, 'Me', 'act1', 'cd'),
        (3, 'You', 'act2', 'xy'),
        (4, 'You', 'act2', 'st')


SELECT T1.USERS, T1.ACTIVITY,   
        STUFF(  
        (  
        SELECT ',' + T2.PAGEURL  
        FROM @TABLE T2  
        WHERE T1.USERS = T2.USERS  
        FOR XML PATH ('')  
        ),1,1,'')  
FROM @TABLE T1  
GROUP BY T1.USERS, T1.ACTIVITY

Android get image path from drawable as string

based on the some of above replies i improvised it a bit

create this method and call it by passing your resource

Reusable Method

public String getURLForResource (int resourceId) {
    //use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
    return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}

Sample call

getURLForResource(R.drawable.personIcon)

complete example of loading image

String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
 Glide.with(patientProfileImageView.getContext())
          .load(imageUrl)
          .into(patientProfileImageView);

you can move the function getURLForResource to a Util file and make it static so it can be reused

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

The behavior depends on which version your repository has. Subversion 1.5 allows 4 types of merge:

  1. merge sourceURL1[@N] sourceURL2[@M] [WCPATH]
  2. merge sourceWCPATH1@N sourceWCPATH2@M [WCPATH]
  3. merge [-c M[,N...] | -r N:M ...] SOURCE[@REV] [WCPATH]
  4. merge --reintegrate SOURCE[@REV] [WCPATH]

Subversion before 1.5 only allowed the first 2 formats.

Technically you can perform all merges with the first two methods, but the last two enable subversion 1.5's merge tracking.

TortoiseSVN's options merge a range or revisions maps to method 3 when your repository is 1.5+ or to method one when your repository is older.

When merging features over to a release/maintenance branch you should use the 'Merge a range of revisions' command.

Only when you want to merge all features of a branch back to a parent branch (commonly trunk) you should look into using 'Reintegrate a branch'.

And the last command -Merge two different trees- is only usefull when you want to step outside the normal branching behavior. (E.g. Comparing different releases and then merging the differenct to yet another branch)

How to define custom exception class in Java, the easiest way?

If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception and check "Constructors from superclass" and it will generate the following:

package com.example.exception;

public class MyException extends Exception {

    public MyException() {
        // TODO Auto-generated constructor stub
    }

    public MyException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public MyException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

}

In response to the question below about not calling super() in the defualt constructor, Oracle has this to say:

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

How to get current memory usage in android?

Linux's memory management philosophy is "Free memory is wasted memory".

I assume that the next two lines will show how much memory is in "Buffers" and how much is "Cached". While there is a difference between the two (please don't ask what that difference is :) they both roughly add up to the amount of memory used to cache file data and metadata.

A far more useful guide to free memory on a Linux system is the free(1) command; on my desktop, it reports information like this:

$ free -m
             total       used       free     shared    buffers     cached
Mem:          5980       1055       4924          0         91        374
-/+ buffers/cache:        589       5391
Swap:         6347          0       6347

The +/- buffers/cache: line is the magic line, it reports that I've really got around 589 megs of actively required process memory, and around 5391 megs of 'free' memory, in the sense that the 91+374 megabytes of buffers/cached memory can be thrown away if the memory could be more profitably used elsewhere.

(My machine has been up for about three hours, doing nearly nothing but stackoverflow, which is why I have so much free memory.)

If Android doesn't ship with free(1), you can do the math yourself with the /proc/meminfo file; I just like the free(1) output format. :)

How do I group Windows Form radio buttons?

I like the concept of grouping RadioButtons in WPF. There is a property GroupName that specifies which RadioButton controls are mutually exclusive (http://msdn.microsoft.com/de-de/library/system.windows.controls.radiobutton.aspx).

So I wrote a derived class for WinForms that supports this feature:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;

namespace Use.your.own
{
    public class AdvancedRadioButton : CheckBox
    {
        public enum Level { Parent, Form };

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the level that specifies which RadioButton controls are affected."),
        DefaultValue(Level.Parent)]
        public Level GroupNameLevel { get; set; }

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the name that specifies which RadioButton controls are mutually exclusive.")]
        public string GroupName { get; set; }

        protected override void OnCheckedChanged(EventArgs e)
        {
            base.OnCheckedChanged(e);

            if (Checked)
            {
                var arbControls = (dynamic)null;
                switch (GroupNameLevel)
                {
                    case Level.Parent:
                        if (this.Parent != null)
                            arbControls = GetAll(this.Parent, typeof(AdvancedRadioButton));
                        break;
                    case Level.Form:
                        Form form = this.FindForm();
                        if (form != null)
                            arbControls = GetAll(this.FindForm(), typeof(AdvancedRadioButton));
                        break;
                }
                if (arbControls != null)
                    foreach (Control control in arbControls)
                        if (control != this &&
                            (control as AdvancedRadioButton).GroupName == this.GroupName)
                            (control as AdvancedRadioButton).Checked = false;
            }
        }

        protected override void OnClick(EventArgs e)
        {
            if (!Checked)
                base.OnClick(e);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            CheckBoxRenderer.DrawParentBackground(pevent.Graphics, pevent.ClipRectangle, this);

            RadioButtonState radioButtonState;
            if (Checked)
            {
                radioButtonState = RadioButtonState.CheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.CheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.CheckedDisabled;
            }
            else
            {
                radioButtonState = RadioButtonState.UncheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.UncheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.UncheckedDisabled;
            }

            Size glyphSize = RadioButtonRenderer.GetGlyphSize(pevent.Graphics, radioButtonState);
            Rectangle rect = pevent.ClipRectangle;
            rect.Width -= glyphSize.Width;
            rect.Location = new Point(rect.Left + glyphSize.Width, rect.Top);

            RadioButtonRenderer.DrawRadioButton(pevent.Graphics, new System.Drawing.Point(0, rect.Height / 2 - glyphSize.Height / 2), rect, this.Text, this.Font, this.Focused, radioButtonState);
        }

        private IEnumerable<Control> GetAll(Control control, Type type)
        {
            var controls = control.Controls.Cast<Control>();

            return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
        }
    }
}

How to pull remote branch from somebody else's repo

If antak's answer:

git fetch [email protected]:<THEIR USERNAME>/<REPO>.git <THEIR BRANCH>:<OUR NAME FOR BRANCH> 

gives you:

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Then (following Przemek D's advice) use

git fetch https://github.com/<THEIR USERNAME>/<REPO>.git <THEIR BRANCH>:<OUR NAME FOR BRANCH>

Create a string of variable length, filled with a repeated character

A great ES6 option would be to padStart an empty string. Like this:

var str = ''.padStart(10, "#");

Note: this won't work in IE (without a polyfill).

explode string in jquery

if your input's id is following

<input type='text'  id='kg_row1' >

then you can get explode/split the above with the following function of split in jquery

  var kg_id = $(this).attr("id");
  var getvalues =kg_id.split("_");
  var id = getvalues[1];

Git log out user from command line

I was not able to clone a repository due to have logged on with other credentials.

To switch to another user, I >>desperate<< did:

git config --global --unset user.name
git config --global --unset user.email
git config --global --unset credential.helper

after, instead using ssh link, I used HTTPS link. It asked for credentials and it worked fine FOR ME!

Best way to overlay an ESRI shapefile on google maps?

I would not use KML. Instead, use GeoJSON which you can natively consume in Google Maps API now. It is a newer feature that didn't exist from the original responses.

In any case, simply open the SHP file in Quantum GIS, and then you can output it in any format you like (KML, GeoJSON).

If you are using Google Maps for Work, I found a premium extension that handles loading shapefiles directly where you can just connect direct to the shapefile that you generate from ESRI. I did a search on the CMaps site and found this snippet which loaded US by state shapefile: https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp

var cMap = new centigon.locationIntelligence.MapView();
    cMap.key([your_api_key]);


    cMap.layerNames(["Basic Shapes"]);
    cMap.dbfKeys([['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']]);
    cMap.userShapeKeys([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 
    cMap.labels([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 

    cMap.polyDataSources([centigon.locationIntelligence.CMapAnalytics.DATA_PROVIDERS.SHAPE_DATAPROVIDER]);
    cMap.layerTypes([centigon.mapping.Layer.TYPE.POLY]);
    cMap.locations([["https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp"]]);

    cMap.panTo("USA");
    cMap.zoomLevel(3);

Default passwords of Oracle 11g?

actually during the installation process.it will prompt u to enter the password..At the last step of installation, a window will appear showing cloning database files..After copying,there will be a option..like password managament..there we hav to set our password..and user name will be default..

Pattern matching using a wildcard

If you really do want to use wildcards to identify specific variables, then you can use a combination of ls() and grep() as follows:

l = ls()
vars.with.result <- l[grep("result", l)]

Can I set an opacity only to the background image of a div?

So here is an other way:

background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");