Programs & Examples On #Side by side

Side-by-side Assemblies are a Microsoft Windows solution that reduces versioning conflicts in Windows-client applications.

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:

plt.tight_layout()

before the show. Yielding:

neater side by side plot

Make div fill remaining space along the main axis in flexbox

Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex on the row container and at least making sure your middle container on the row has a flex-grow value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow properties applied, middle container only needs 1 for flex-grow).

Here's a pic of what I was trying to do and sample code for how I solved it.

enter image description here

_x000D_
_x000D_
.row {
  background: lightgray;
  height: 30px;
  width: 100%;
  display: flex;
  align-items:flex-end;
  margin-top:5px;
}
.left {
  background:lightblue;
}
.separator{
  flex-grow:1;
  border-bottom:dotted 2px black;
}
.right {
  background:coral;
}
_x000D_
<div class="row">
  <div class="left">Left</div>
  <div class="separator"></div>
  <div class="right">Right With Text</div>
</div>
<div class="row">
  <div class="left">Left With More Text</div>
  <div class="separator"></div>
  <div class="right">Right</div>
</div>
<div class="row">
  <div class="left">Left With Text</div>
  <div class="separator"></div>
  <div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

How can one display images side by side in a GitHub README.md?

The easiest way I can think of solving this is using the tables included in GitHub's flavored markdown.

To your specific example it would look something like this:

Solarized dark             |  Solarized Ocean
:-------------------------:|:-------------------------:
![](https://...Dark.png)  |  ![](https://...Ocean.png)

This creates a table with Solarized Dark and Ocean as headers and then contains the images in the first row. Obviously you would replace the ... with the real link. The :s are optional (They just center the content in the cells, which is kinda unnecessary in this case). Also you might want to downsize the images so they will display better side-by-side.

How do I get interactive plots again in Spyder/IPython/matplotlib?

You can quickly control this by typing built-in magic commands in Spyder's IPython console, which I find faster than picking these from the preferences menu. Changes take immediate effect, without needing to restart Spyder or the kernel.

To switch to "automatic" (i.e. interactive) plots, type:

%matplotlib auto

then if you want to switch back to "inline", type this:

%matplotlib inline

(Note: these commands don't work in non-IPython consoles)

See more background on this topic: Purpose of "%matplotlib inline"

Paging UICollectionView by cells, not screen

Also you can create fake scroll view to handle scrolling.

Horizontal or Vertical

// === Defaults ===
let bannerSize = CGSize(width: 280, height: 170)
let pageWidth: CGFloat = 290 // ^ + paging
let insetLeft: CGFloat = 20
let insetRight: CGFloat = 20
// ================

var pageScrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Create fake scrollview to properly handle paging
    pageScrollView = UIScrollView(frame: CGRect(origin: .zero, size: CGSize(width: pageWidth, height: 100)))
    pageScrollView.isPagingEnabled = true
    pageScrollView.alwaysBounceHorizontal = true
    pageScrollView.showsVerticalScrollIndicator = false
    pageScrollView.showsHorizontalScrollIndicator = false
    pageScrollView.delegate = self
    pageScrollView.isHidden = true
    view.insertSubview(pageScrollView, belowSubview: collectionView)

    // Set desired gesture recognizers to the collection view
    for gr in pageScrollView.gestureRecognizers! {
        collectionView.addGestureRecognizer(gr)
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == pageScrollView {
        // Return scrolling back to the collection view
        collectionView.contentOffset.x = pageScrollView.contentOffset.x
    }
}

func refreshData() {
    ...

    refreshScroll()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    refreshScroll()
}

/// Refresh fake scrolling view content size if content changes
func refreshScroll() {
    let w = collectionView.width - bannerSize.width - insetLeft - insetRight
    pageScrollView.contentSize = CGSize(width: pageWidth * CGFloat(banners.count) - w, height: 100)
}

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

Actualy you can do almost everything with dropdown field, and it will looks the same on every browser, take a look at code example

select.custom {
  background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20fill%3D%22%23555555%22%20%0A%09%20width%3D%2224px%22%20height%3D%2224px%22%20viewBox%3D%22-261%20145.2%2024%2024%22%20style%3D%22enable-background%3Anew%20-261%20145.2%2024%2024%3B%22%20xml%3Aspace%3D%22preserve%22%3E%0A%3Cpath%20d%3D%22M-245.3%2C156.1l-3.6-6.5l-3.7%2C6.5%20M-252.7%2C159l3.7%2C6.5l3.6-6.5%22%2F%3E%0A%3C%2Fsvg%3E");
  padding-right: 25px;
  background-repeat: no-repeat;
  background-position: right center;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

select.custom::-ms-expand {
  display: none;
}

https://jsfiddle.net/x76j455z/10/

Comparing two dataframes and getting the differences

This approach, df1 != df2, works only for dataframes with identical rows and columns. In fact, all dataframes axes are compared with _indexed_same method, and exception is raised if differences found, even in columns/indices order.

If I got you right, you want not to find changes, but symmetric difference. For that, one approach might be concatenate dataframes:

>>> df = pd.concat([df1, df2])
>>> df = df.reset_index(drop=True)

group by

>>> df_gpby = df.groupby(list(df.columns))

get index of unique records

>>> idx = [x[0] for x in df_gpby.groups.values() if len(x) == 1]

filter

>>> df.reindex(idx)
         Date   Fruit   Num   Color
9  2013-11-25  Orange   8.6  Orange
8  2013-11-25   Apple  22.1     Red

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Compare two DataFrames and output their differences side-by-side

I have faced this issue, but found an answer before finding this post :

Based on unutbu's answer, load your data...

import pandas as pd
import io

texts = ['''\
id   Name   score                    isEnrolled                       Date
111  Jack                            True              2013-05-01 12:00:00
112  Nick   1.11                     False             2013-05-12 15:05:23
     Zoe    4.12                     True                                  ''',

         '''\
id   Name   score                    isEnrolled                       Date
111  Jack   2.17                     True              2013-05-01 12:00:00
112  Nick   1.21                     False                                
     Zoe    4.12                     False             2013-05-01 12:00:00''']


df1 = pd.read_fwf(io.StringIO(texts[0]), widths=[5,7,25,17,20], parse_dates=[4])
df2 = pd.read_fwf(io.StringIO(texts[1]), widths=[5,7,25,17,20], parse_dates=[4])

...define your diff function...

def report_diff(x):
    return x[0] if x[0] == x[1] else '{} | {}'.format(*x)

Then you can simply use a Panel to conclude :

my_panel = pd.Panel(dict(df1=df1,df2=df2))
print my_panel.apply(report_diff, axis=0)

#          id  Name        score    isEnrolled                       Date
#0        111  Jack   nan | 2.17          True        2013-05-01 12:00:00
#1        112  Nick  1.11 | 1.21         False  2013-05-12 15:05:23 | NaT
#2  nan | nan   Zoe         4.12  True | False  NaT | 2013-05-01 12:00:00

By the way, if you're in IPython Notebook, you may like to use a colored diff function to give colors depending whether cells are different, equal or left/right null :

from IPython.display import HTML
pd.options.display.max_colwidth = 500  # You need this, otherwise pandas
#                          will limit your HTML strings to 50 characters

def report_diff(x):
    if x[0]==x[1]:
        return unicode(x[0].__str__())
    elif pd.isnull(x[0]) and pd.isnull(x[1]):
        return u'<table style="background-color:#00ff00;font-weight:bold;">'+\
            '<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % ('nan', 'nan')
    elif pd.isnull(x[0]) and ~pd.isnull(x[1]):
        return u'<table style="background-color:#ffff00;font-weight:bold;">'+\
            '<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % ('nan', x[1])
    elif ~pd.isnull(x[0]) and pd.isnull(x[1]):
        return u'<table style="background-color:#0000ff;font-weight:bold;">'+\
            '<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % (x[0],'nan')
    else:
        return u'<table style="background-color:#ff0000;font-weight:bold;">'+\
            '<tr><td>%s</td></tr><tr><td>%s</td></tr></table>' % (x[0], x[1])

HTML(my_panel.apply(report_diff, axis=0).to_html(escape=False))

Converting dict to OrderedDict

You are creating a dictionary first, then passing that dictionary to an OrderedDict. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict is inherently not ordered.

Pass in a sequence of tuples instead:

ship = [("NAME", "Albatross"),
        ("HP", 50),
        ("BLASTERS", 13),
        ("THRUSTERS", 18),
        ("PRICE", 250)]
ship = collections.OrderedDict(ship)

What you see when you print the OrderedDict is it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)]) just shows you, in a reproducable representation, what the contents are of the OrderedDict.


(*): In the CPython 3.6 implementation, the dict type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict() for certain cases.

Matplotlib 2 Subplots, 1 Colorbar

This topic is well covered but I still would like to propose another approach in a slightly different philosophy.

It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3

# Make a new figure
fig = plt.figure(constrained_layout=True)

# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)

# Fill your figure with desired plots
axes = []
for i in range(nrow):
    for j in range(ncol):
        axes.append(fig.add_subplot(gs[i, j]))
        im = axes[-1].pcolormesh(np.random.random((10,10)))

# Shared colorbar    
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])

plt.show()

enter image description here

How to use filter, map, and reduce in Python 3

One of the advantages of map, filter and reduce is how legible they become when you "chain" them together to do something complex. However, the built-in syntax isn't legible and is all "backwards". So, I suggest using the PyFunctional package (https://pypi.org/project/PyFunctional/). Here's a comparison of the two:

flight_destinations_dict = {'NY': {'London', 'Rome'}, 'Berlin': {'NY'}}

PyFunctional version

Very legible syntax. You can say:

"I have a sequence of flight destinations. Out of which I want to get the dict key if city is in the dict values. Finally, filter out the empty lists I created in the process."

from functional import seq  # PyFunctional package to allow easier syntax

def find_return_flights_PYFUNCTIONAL_SYNTAX(city, flight_destinations_dict):
    return seq(flight_destinations_dict.items()) \
        .map(lambda x: x[0] if city in x[1] else []) \
        .filter(lambda x: x != []) \

Default Python version

It's all backwards. You need to say:

"OK, so, there's a list. I want to filter empty lists out of it. Why? Because I first got the dict key if the city was in the dict values. Oh, the list I'm doing this to is flight_destinations_dict."

def find_return_flights_DEFAULT_SYNTAX(city, flight_destinations_dict):
    return list(
        filter(lambda x: x != [],
               map(lambda x: x[0] if city in x[1] else [], flight_destinations_dict.items())
               )
    )

Bootstrap: Collapse other sections when one is expanded

If you are using Bootstrap 4, and you don't want to change your markup:

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.show').collapse('hide');
});

How to display items side-by-side without using tables?

these days div is the new norm

<div style="float:left"><img.. ></div>
<div style="float:right">text</div>
<div style="clear:both"/>

PHP cURL not working - WAMP on Windows 7 64 bit

I had the problem with not working curl on win8 wamp3 php5.6. Reinstalling wamp (x64 version as I had x64 in system info) made it work fine.

How to reposition Chrome Developer Tools

The Version 56.0.2924.87 which I am in now, Undocks the DevTools automatically if you are NOT in a desktop. Otherwise Open a NEW new Chrome tab and Inspect to Dock the DevTools back into the window.

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

How can I get a side-by-side diff when I do "git diff"?

I personally really like icdiff !

If you're on Mac OS X with HomeBrew, just do brew install icdiff.

To get the file labels correctly, plus other cool features, I have in my ~/.gitconfig:

[pager]
    difftool = true
[diff]
    tool = icdiff
[difftool "icdiff"]
    cmd = icdiff --head=5000 --highlight --line-numbers -L \"$BASE\" -L \"$REMOTE\" \"$LOCAL\" \"$REMOTE\"

And I use it like: git difftool

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

How could others, on a local network, access my NodeJS app while it's running on my machine?

put this codes in your server.js :

app.set('port', (80))
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'))
})

after that if you can't access app on network disable firewall like this :

enter image description here

How to get these two divs side-by-side?

Using flexbox

   #parent_div_1{
     display:flex;
     flex-wrap: wrap;
  }

what's the easiest way to put space between 2 side-by-side buttons in asp.net

    <style>
    .Button
    {
        margin:5px;
    }
    </style>

 <asp:Button ID="Button1" runat="server" Text="Button" CssClass="Button" />
 <asp:Button ID="Button2" runat="server" Text="Button" CssClass="Button"/>

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

<form>
  <label for="company">
    <span>Company Name</span>
    <input type="text" id="company" />
  </label>
  <label for="contact">
    <span>Contact Name</span>
    <input type="text" id="contact" />
  </label>
</form>

label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }

Illustrated at http://jsfiddle.net/H3y8j/

How to compare files from two different branches?

In order to compare two files in the git bash you need to use the command:

git diff <Branch name>..master -- Filename.extension   

This command will show the difference between the two files in the bash itself.

How do I keep two side-by-side divs the same height?

you can use jQuery to achieve this easily.

CSS

.left, .right {border:1px solid #cccccc;}

jQuery

$(document).ready(function() {
    var leftHeight = $('.left').height();
    $('.right').css({'height':leftHeight});
});

HTML

   <div class="left">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada, lacus eu dapibus tempus, ante odio aliquet risus, ac ornare orci velit in sapien. Duis suscipit sapien vel nunc scelerisque in pretium velit mattis. Cras vitae odio sed eros mollis malesuada et eu nunc.</p>
   </div>
   <div class="right">
    <p>Lorem ipsum dolor sit amet.</p>
   </div>

You'll need to include jQuery

Aligning two divs side-by-side

I don't understand why Nick is using margin-left: 200px; instead off floating the other div to the left or right, I've just tweaked his markup, you can use float for both elements instead of using margin-left.

Demo

#main {
    margin: auto;
    width: 400px;
}

#sidebar    {
    width: 100px;
    min-height: 400px;
    background: red;
    float: left;
}

#page-wrap  {
    width: 300px;
    background: #0f0;
    min-height: 400px;
    float: left;
}

.clear:after {
    clear: both;
    display: table;
    content: "";
}

Also, I've used .clear:after which am calling on the parent element, just to self clear the parent.

awk without printing newline

If Perl is an option, here is a solution using fedorqui's example:

seq 5 | perl -ne 'chomp; print "$_ "; END{print "\n"}'

Explanation:
chomp removes the newline
print "$_ " prints each line, appending a space
the END{} block is used to print a newline

output: 1 2 3 4 5

Side-by-side plots with ggplot2

Using the patchwork package, you can simply use + operator:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


p1 + p2

patchwork

Other operators include / to stack plots to place plots side by side, and () to group elements. For example you can configure a top row of 3 plots and a bottom row of one plot with (p1 | p2 | p3) /p. For more examples, see the package documentation.

Side-by-side list items as icons within a div (css)

I would recommend that you use display: inline;. float is screwed up in IE. Here is an example of how I would approach it:

<ul class="side-by-side">
  <li>item 1<li>
  <li>item 2<li>
  <li>item 3<li>
</ul>

and here's the css:

.side-by-side {
  width: 100%;
  border: 1px solid black;

}
.side-by-side li {
  display: inline;
}

Also, if you use floats the ul will not wrap around the li's and will instead have a hight of 0 in this example:

.side-by-side li {
  float: left;
}

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

I also had to remove the SMSS before it would get past that step.

What is the Difference Between Mercurial and Git?

One thing to notice between mercurial of bitbucket.org and git of github is, mercurial can have as many private repositories as you want, but github you have to upgrade to a paid account. So, that's why I go for bitbucket which uses mercurial.

How to insert a new line in Linux shell script?

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

Effect of NOLOCK hint in SELECT statements

In addition to what is said above, you should be very aware that nolock actually imposes the risk of you not getting rows that has been committed before your select.

See http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx

Double precision floating values in Python?

Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..

import random
from decimal import Decimal

GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)

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

Test for year > 2079. I found that a user typo'ed 2106 instead of 2016 in the year (10/12/2106) and boom; so on 10/12/2016 I tested and found SQL Server accepted up to 2078, started throwing that error if the year is 2079 or higher. I have not done any further research as to what kind of date sliding SQL Server does.

Cannot hide status bar in iOS7

For Swift 2.0+ IOS 9

override func prefersStatusBarHidden() -> Bool {
return true
}

UTF-8 encoding problem in Spring MVC

I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.

Adding a header to the HttpServletResponse works.

@RequestMapping(value="/test", method=RequestMethod.POST)
public void test(HttpServletResponse resp) {
    try {
        resp.addHeader("content-type", "application/json; charset=utf-8");
        PrintWriter w = resp.getWriter();
        w.write("{\"name\" : \"µr µicron\"}");
        w.flush();
        w.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

C++ - Hold the console window open?

A more appropriate method is to use std::cin.ignore:

#include <iostream>

void Pause()
{
   std::cout << "Press Enter to continue...";
   std::cout.flush();
   std::cin.ignore(10000, '\n');
   return;
}

Find element's index in pandas Series

Another way to do this, although equally unsatisfying is:

s = pd.Series([1,3,0,7,5],index=[0,1,2,3,4])

list(s).index(7)

returns: 3

On time tests using a current dataset I'm working with (consider it random):

[64]:    %timeit pd.Index(article_reference_df.asset_id).get_loc('100000003003614')
10000 loops, best of 3: 60.1 µs per loop

In [66]: %timeit article_reference_df.asset_id[article_reference_df.asset_id == '100000003003614'].index[0]
1000 loops, best of 3: 255 µs per loop


In [65]: %timeit list(article_reference_df.asset_id).index('100000003003614')
100000 loops, best of 3: 14.5 µs per loop

Remove all special characters, punctuation and spaces from string

Here is a regex to match a string of characters that are not a letters or numbers:

[^A-Za-z0-9]+

Here is the Python command to do a regex substitution:

re.sub('[^A-Za-z0-9]+', '', mystring)

Get path of executable

This is what I ended up with

The header file looks like this:

#pragma once

#include <string>
namespace MyPaths {

  std::string getExecutablePath();
  std::string getExecutableDir();
  std::string mergePaths(std::string pathA, std::string pathB);
  bool checkIfFileExists (const std::string& filePath);

}

Implementation


#if defined(_WIN32)
    #include <windows.h>
    #include <Shlwapi.h>
    #include <io.h> 

    #define access _access_s
#endif

#ifdef __APPLE__
    #include <libgen.h>
    #include <limits.h>
    #include <mach-o/dyld.h>
    #include <unistd.h>
#endif

#ifdef __linux__
    #include <limits.h>
    #include <libgen.h>
    #include <unistd.h>

    #if defined(__sun)
        #define PROC_SELF_EXE "/proc/self/path/a.out"
    #else
        #define PROC_SELF_EXE "/proc/self/exe"
    #endif

#endif

namespace MyPaths {

#if defined(_WIN32)

std::string getExecutablePath() {
   char rawPathName[MAX_PATH];
   GetModuleFileNameA(NULL, rawPathName, MAX_PATH);
   return std::string(rawPathName);
}

std::string getExecutableDir() {
    std::string executablePath = getExecutablePath();
    char* exePath = new char[executablePath.length()];
    strcpy(exePath, executablePath.c_str());
    PathRemoveFileSpecA(exePath);
    std::string directory = std::string(exePath);
    delete[] exePath;
    return directory;
}

std::string mergePaths(std::string pathA, std::string pathB) {
  char combined[MAX_PATH];
  PathCombineA(combined, pathA.c_str(), pathB.c_str());
  std::string mergedPath(combined);
  return mergedPath;
}

#endif

#ifdef __linux__

std::string getExecutablePath() {
   char rawPathName[PATH_MAX];
   realpath(PROC_SELF_EXE, rawPathName);
   return  std::string(rawPathName);
}

std::string getExecutableDir() {
    std::string executablePath = getExecutablePath();
    char *executablePathStr = new char[executablePath.length() + 1];
    strcpy(executablePathStr, executablePath.c_str());
    char* executableDir = dirname(executablePathStr);
    delete [] executablePathStr;
    return std::string(executableDir);
}

std::string mergePaths(std::string pathA, std::string pathB) {
  return pathA+"/"+pathB;
}

#endif

#ifdef __APPLE__
    std::string getExecutablePath() {
        char rawPathName[PATH_MAX];
        char realPathName[PATH_MAX];
        uint32_t rawPathSize = (uint32_t)sizeof(rawPathName);

        if(!_NSGetExecutablePath(rawPathName, &rawPathSize)) {
            realpath(rawPathName, realPathName);
        }
        return  std::string(realPathName);
    }

    std::string getExecutableDir() {
        std::string executablePath = getExecutablePath();
        char *executablePathStr = new char[executablePath.length() + 1];
        strcpy(executablePathStr, executablePath.c_str());
        char* executableDir = dirname(executablePathStr);
        delete [] executablePathStr;
        return std::string(executableDir);
    }

    std::string mergePaths(std::string pathA, std::string pathB) {
        return pathA+"/"+pathB;
    }
#endif


bool checkIfFileExists (const std::string& filePath) {
   return access( filePath.c_str(), 0 ) == 0;
}

}

How to create byte array from HttpPostedFile

Use a BinaryReader object to return a byte array from the stream like:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

ld cannot find an existing library

Unless I'm badly mistaken libmagic or -lmagic is not the same library as ImageMagick. You state that you want ImageMagick.

ImageMagick comes with a utility to supply all appropriate options to the compiler.

Ex:

g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o "prog"

How to override equals method in Java

I'm not sure of the details as you haven't posted the whole code, but:

  • remember to override hashCode() as well
  • the equals method should have Object, not People as its argument type. At the moment you are overloading, not overriding, the equals method, which probably isn't what you want, especially given that you check its type later.
  • you can use instanceof to check it is a People object e.g. if (!(other instanceof People)) { result = false;}
  • equals is used for all objects, but not primitives. I think you mean age is an int (primitive), in which case just use ==. Note that an Integer (with a capital 'I') is an Object which should be compared with equals.

See What issues should be considered when overriding equals and hashCode in Java? for more details.

Execute specified function every X seconds

You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

Example JavaScript code to parse CSV data

Here's my PEG(.js) grammar that seems to do ok at RFC 4180 (i.e. it handles the examples at http://en.wikipedia.org/wiki/Comma-separated_values):

start
  = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }

line
  = first:field rest:("," text:field { return text; })*
    & { return !!first || rest.length; } // ignore blank lines
    { rest.unshift(first); return rest; }

field
  = '"' text:char* '"' { return text.join(''); }
  / text:[^\n\r,]* { return text.join(''); }

char
  = '"' '"' { return '"'; }
  / [^"]

Try it out at http://jsfiddle.net/knvzk/10 or http://pegjs.majda.cz/online. Download the generated parser at https://gist.github.com/3362830.

How to use data-binding with Fragment

Just as most have said, but dont forget to set LifeCycleOwner
Sample in Java i.e

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    BindingClass binding = DataBindingUtil.inflate(inflater, R.layout.fragment_layout, container, false);
    ModelClass model = ViewModelProviders.of(getActivity()).get(ViewModelClass.class);
    binding.setLifecycleOwner(getActivity());
    binding.setViewmodelclass(model);

    //Your codes here

    return binding.getRoot();
}

How do I install SciPy on 64 bit Windows?

Okey, here I am going to share what I have done to install SciPy on my Windows PC without the command line.

My PC configuration is Windows 7 64-bit and Python 2.7

  • First I download the required packages form http://www.lfd.uci.edu/~gohlke/pythonlibs/ (which version match your configuration EX: cp27==>python2.7 & cp35==>3.5)
  • Second I extract the file using 7-Zip (also can be used any zipper like WinRAR)
  • Third I copy the scipy folder which I extracted and paste it into C:\Python27\Lib\site-packages (or put it where the exact location is in your PC like ..\..\Lib\site-packages)

NOTE: You have to install NumPy first before installing SciPy in this same way.

Regex to match string containing two names in any order

Explanation of command that i am going to write:-

. means any character, digit can come in place of .

* means zero or more occurrences of thing written just previous to it.

| means 'or'.

So,

james.*jack

would search james , then any number of character until jack comes.

Since you want either jack.*james or james.*jack

Hence Command:

jack.*james|james.*jack

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

How to find Max Date in List<Object>?

A small improvement from the accepted answer is to do the null check and also get full object.

public class DateComparator {

public static void main(String[] args) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
    employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
    employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
    employees.add(new Employee(4, "name4", null));
    employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
    employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
    System.out.println(employees);
    Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
    System.out.println(format.format(maxDate));
    //Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

    Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
    System.out.println(" minDatedEmployee : " + minDatedEmployee);

}

public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, days); // minus number would decrement the days
    return cal.getTime();
}
}

You would get below results :

 [Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
 maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]

 minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]

Update : What if list itself is empty ?

        Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
    System.out.println(format.format(maxDate));
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

Run C++ in command prompt - Windows

have MinGW compiler bin directory added to path.

use mingw32-g++ -s -c source_file_name.cpp -o output_file_name.o to compile

then mingw32-g++ -o executable_file_name.exe output_file_name.o to build exe

finally, you run with executable_file_name.exe

Excel: Creating a dropdown using a list in another sheet?

Yes it is. Use Data Validation from the Data panel. Select Allow: List and pick those cells on the other sheet as your source.

HTML code for an apostrophe

&#39; in decimal.

%27 in hex.

Asynchronously wait for Task<T> to complete with timeout

How about this:

int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // task completed within timeout
} else { 
    // timeout logic
}

And here's a great blog post "Crafting a Task.TimeoutAfter Method" (from MS Parallel Library team) with more info on this sort of thing.

Addition: at the request of a comment on my answer, here is an expanded solution that includes cancellation handling. Note that passing cancellation to the task and the timer means that there are multiple ways cancellation can be experienced in your code, and you should be sure to test for and be confident you properly handle all of them. Don't leave to chance various combinations and hope your computer does the right thing at runtime.

int timeout = 1000;
var task = SomeOperationAsync(cancellationToken);
if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) == task)
{
    // Task completed within timeout.
    // Consider that the task may have faulted or been canceled.
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;

}
else
{
    // timeout/cancellation logic
}

Linq select objects in list where exists IN (A,B,C)

Try with Contains function;

Determines whether a sequence contains a specified element.

var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));

How do I get into a Docker container's shell?

Let's say, for reasons that are your own, you really do want to use SSH. It takes a few steps, but it can be done. Here are the commands that you would run inside the container to set it up...

apt-get update
apt-get install openssh-server

mkdir /var/run/sshd
chmod 0755 /var/run/sshd
/usr/sbin/sshd

useradd --create-home --shell /bin/bash --groups sudo username ## includes 'sudo'
passwd username ## Enter a password

apt-get install x11-apps ## X11 demo applications (optional)
ifconfig | awk '/inet addr/{print substr($2,6)}' ## Display IP address (optional)

Now you can even run graphical applications (if they are installed in the container) using X11 forwarding to the SSH client:

ssh -X username@IPADDRESS
xeyes ## run an X11 demo app in the client

Here are some related resources:

Decrementing for loops

You need to give the range a -1 step

 for i in range(10,0,-1):
    print i

JVM heap parameters

The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory.

So,

  • -Xms512m -Xmx512m

JVM starts with 512 M, never resizes.

  • -Xms64m -Xmx512m

JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.

What key shortcuts are to comment and uncomment code?

From your screenshot it appears you have ReSharper installed.

Depending on the key binding options you chose when you installed it, some of your standard shortcuts may now be redirected to ReSharper commands. It's worth checking, for example Ctrl+E, C is used by R# for the code cleanup dialog.

Failed to load resource: the server responded with a status of 404 (Not Found)

Your files are not under the jsp folder that's why it is not found. You have to go back again 1 folder Try this:

     <script  src="../../Jquery/prettify.js"></script>

Error 1053 the service did not respond to the start or control request in a timely fashion

In my case the problem was missing version of .net framework.

My service used

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

But .net Framework version of server was 4, so by changing 4.5 to 4 the problem fixed:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>

Regular cast vs. static_cast vs. dynamic_cast

Avoid using C-Style casts.

C-style casts are a mix of const and reinterpret cast, and it's difficult to find-and-replace in your code. A C++ application programmer should avoid C-style cast.

How can I update a single row in a ListView?

exactly I used this

private void updateSetTopState(int index) {
        View v = listview.getChildAt(index -
                listview.getFirstVisiblePosition()+listview.getHeaderViewsCount());

        if(v == null)
            return;

        TextView aa = (TextView) v.findViewById(R.id.aa);
        aa.setVisibility(View.VISIBLE);
    }

How to turn on front flash light programmatically in Android?

Try this.

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; // Usually front camera is at 0 position.
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

Configure apache to listen on port other than 80

Run this command if your ufw(Uncomplicatd Firewall) is enabled . Add for Example port 8080

$ sudo ufw allow 8080/tcp

And you can check the status by running

$ sudo ufw status

For more info check : https://linuxhint.com/ubuntu_allow_port_firewall

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

How to scroll to top of a div using jQuery?

Or, for less code, inside your click you place:

setTimeout(function(){ 

$('#DIV_ID').scrollTop(0);

}, 500);

Incorrect syntax near ''

The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.

To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.

How to get all properties values of a JavaScript Object (without knowing the keys)?

const object1 = {
  a: 'somestring',
  b: 42
};

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed

Load local javascript file in chrome for testing?

Running a simple local HTTP server

To test such examples, one needs a local webserver. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer (or http.server, depending on the version of Python installed.)

# Install Python & try one of the following depending on your python version. if the version is 3.X
python3 -m http.server
# On windows try "python" instead of "python3", or "py -3"
# If Python version is 2.X
python -m SimpleHTTPServer

How to add an image to the "drawable" folder in Android Studio?

Android Studio 3.0:

1) Right click directory 'drawable'.
2) Click on: Show in Explorer

Now you have an explorer opent with a few directories in it, one of then is 'drawable'.

3) Go in the directory 'drawable'.
4) Place the image you want in there.
5) Close the explorer again.

Now the image is in Android Studio under 'res/drawable'.

Handling warning for possible multiple enumeration of IEnumerable

Using IReadOnlyCollection<T> or IReadOnlyList<T> in the method signature instead of IEnumerable<T>, has the advantage of making explicit that you might need to check the count before iterating, or to iterate multiple times for some other reason.

However they have a huge downside that will cause problems if you try to refactor your code to use interfaces, for instance to make it more testable and friendly to dynamic proxying. The key point is that IList<T> does not inherit from IReadOnlyList<T>, and similarly for other collections and their respective read-only interfaces. (In short, this is because .NET 4.5 wanted to keep ABI compatibility with earlier versions. But they didn't even take the opportunity to change that in .NET core.)

This means that if you get an IList<T> from some part of the program and want to pass it to another part that expects an IReadOnlyList<T>, you can't! You can however pass an IList<T> as an IEnumerable<T>.

In the end, IEnumerable<T> is the only read-only interface supported by all .NET collections including all collection interfaces. Any other alternative will come back to bite you as you realize that you locked yourself out from some architecture choices. So I think it's the proper type to use in function signatures to express that you just want a read-only collection.

(Note that you can always write a IReadOnlyList<T> ToReadOnly<T>(this IList<T> list) extension method that simple casts if the underlying type supports both interfaces, but you have to add it manually everywhere when refactoring, where as IEnumerable<T> is always compatible.)

As always this is not an absolute, if you're writing database-heavy code where accidental multiple enumeration would be a disaster, you might prefer a different trade-off.

Difference between string and text in rails?

As explained above not just the db datatype it will also affect the view that will be generated if you are scaffolding. string will generate a text_field text will generate a text_area

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

CheckBox in RecyclerView keeps on checking different items

USE THIS ONLY IF YOU HAVE LIMITED NUMBER OF ITEMS IN YOUR RECYCLER VIEW.
I tried using boolean value in model and keep the checkbox status, but it did not help in my case. What worked for me is this.setIsRecyclable(false);

public class ComponentViewHolder extends RecyclerView.ViewHolder {
    public MyViewHolder(View itemView) {
        super(itemView);
        ....
        this.setIsRecyclable(false);
    }

More explanation on this can be found here https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#isRecyclable()

NOTE: This is a workaround. To use it properly you can refer the document which states "Calls to setIsRecyclable() should always be paired (one call to setIsRecyclabe(false) should always be matched with a later call to setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally reference-counted." I don't know how to do this in code, if someone can provide more code on this.

JUnit Testing private variables?

I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?

What is the use of the @ symbol in PHP?

Like already some answered before: The @ operator suppresses all errors in PHP, including notices, warnings and even critical errors.

BUT: Please, really do not use the @ operator at all.

Why?

Well, because when you use the @ operator for error supression, you have no clue at all where to start when an error occurs. I already had some "fun" with legacy code where some developers used the @ operator quite often. Especially in cases like file operations, network calls, etc. Those are all cases where lots of developers recommend the usage of the @ operator as this sometimes is out of scope when an error occurs here (for example a 3rdparty API could be unreachable, etc.).

But what's the point to still not use it? Let's have a look from two perspectives:

As a developer: When @ is used, I have absolutely no idea where to start. If there are hundreds or even thousands of function calls with @ the error could be like everyhwere. No reasonable debugging possible in this case. And even if it is just a 3rdparty error - then it's just fine and you're done fast. ;-) Moreover, it's better to add enough details to the error log, so developers are able to decide easily if a log entry is something that must be checked further or if it's just a 3rdparty failure that is out of the developer's scope.

As a user: Users don't care at all what the reason for an error is or not. Software is there for them to work, to finish a specific task, etc. They don't care if it's the developer's fault or a 3rdparty problem. Especially for the users, I strongly recommend to log all errors, even if they're out of scope. Maybe you'll notice that a specific API is offline frequently. What can you do? You can talk to your API partner and if they're not able to keep it stable, you should probably look for another partner.

In short: You should know that there exists something like @ (knowledge is always good), but just do not use it. Many developers (especially those debugging code from others) will be very thankful.

CSS: background image on background color

Assuming you want an icon on the right (or left) then this should work best:

.show-hide-button::after {
    content:"";
    background-repeat: no-repeat;
    background-size: contain;
    display: inline-block;
    background-size: 1em;
    width: 1em;
    height: 1em;
    background-position: 0 2px;
    margin-left: .5em;
}
.show-hide-button.shown::after {
    background-image: url(img/eye.svg);
}

You could also do background-size: contain;, but that should be mostly the same. the background-position will depened on your image.

Then you can easily do an alternative state on hover:

.show-hide-button.shown:hover::after {
    background-image: url(img/eye-no.svg);
}

Parse RSS with jQuery

I'm using jquery with yql for feed. You can retrieve twitter,rss,buzz with yql. I read from http://tutorialzine.com/2010/02/feed-widget-jquery-css-yql/ . It's very useful for me.

Correlation between two vectors?

To perform a linear regression between two vectors x and y follow these steps:

[p,err] = polyfit(x,y,1);   % First order polynomial
y_fit = polyval(p,x,err);   % Values on a line
y_dif = y - y_fit;          % y value difference (residuals)
SSdif = sum(y_dif.^2);      % Sum square of difference
SStot = (length(y)-1)*var(y);   % Sum square of y taken from variance
rsq = 1-SSdif/SStot;        % Correlation 'r' value. If 1.0 the correlelation is perfect

For x=[10;200;7;150] and y=[0.001;0.45;0.0007;0.2] I get rsq = 0.9181.

Reference URL: http://www.mathworks.com/help/matlab/data_analysis/linear-regression.html

How to invoke function from external .c file in C?

Change your Main.c like so

#include <stdlib.h>
#include <stdio.h>
#include "ClasseAusiliaria.h"

int main(void)
{
  int risultato;
  risultato = addizione(5,6);
  printf("%d\n",risultato);
}

Create ClasseAusiliaria.h like so

extern int addizione(int a, int b);

I then compiled and ran your code, I got an output of

11

"No Content-Security-Policy meta tag found." error in my phonegap application

For me it was enough to reinstall whitelist plugin:

cordova plugin remove cordova-plugin-whitelist

and then

cordova plugin add cordova-plugin-whitelist

It looks like updating from previous versions of Cordova was not succesful.

Generate a UUID on iOS from Swift

You could also just use the NSUUID API:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

Note that NSUUID is available from iOS 6 and up.

Launch Failed. Binary not found. CDT on Eclipse Helios

If you still have an error even after building the project then try to do this:

  • click on Binaries in Project Explorer with the left button
  • click on green "Play" button (Run Debug)

curl : (1) Protocol https not supported or disabled in libcurl

Specifying the protocol within the url might solve your problem.

I had a similar problem (while using curl php client) :

I was passing domain.com instead of sftp://domain.com which lead to this confusing error:

Protocol "http" not supported or disabled in libcurl, took 0 seconds.

Adding Git-Bash to the new Windows Terminal

Adding "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i" doesn't work for me. Because of space symbol (which is separator in cmd) in %PROGRAMFILES% terminal executes command "C:\Program" instead of "C:\Program Files\Git\bin\bash.exe -l -i". The solution should be something like adding quotation marks in json file, but I didn't figure out how. The only solution is to add "C:\Program Files\Git\bin" to %PATH% and write "commandline": "bash.exe" in profiles.json

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

To add to Alan Wells's elaborate answer here is a quick fix

Run a Local Server

you can serve any folder in your computer with Serve

First, navigate using the command line into the folder you'd like to serve.

Then

npx i -g serve
serve

or if you'd like to test Serve without downloading it

npx serve

and that's it! You can view your files at http://localhost:5000

enter image description here

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!

This started happening after I've updated android studio to latest version.

How to change progress bar's progress color in Android

I'm sorry that it's not the answer, but what's driving the requirement setting it from code ? And .setProgressDrawable should work if it's defined correctly

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#ff9d9e9d"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:angle="270"
        />
    </shape>
</item>

<item android:id="@android:id/secondaryProgress">
    <clip>
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#80ffd300"
                    android:centerColor="#80ffb600"
                    android:centerY="0.75"
                    android:endColor="#a0ffcb00"
                    android:angle="270"
            />
        </shape>
    </clip>
</item>

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners
                android:radius="5dip" />
            <gradient
                android:startColor="@color/progress_start"
                android:endColor="@color/progress_end"
                android:angle="270" 
            />
        </shape>
    </clip>
</item>

</layer-list>

std::vector versus std::array in C++

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).

Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

It's more limited than std::vector, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector.

For an introduction to std::array, have a look at this article; for a quick introduction to std::vector and to the the operations that are possible on it, you may want to look at its documentation.


  1. Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array. As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so it is a dynamic array, stored where the associated allocator puts it.

Fastest way to download a GitHub project

Another faster way of downloading a GitHub project would be to use the clone functionality with the --depth argument as:

git clone --depth=1 [email protected]:organization/your-repo.git

to perform a shallow clone.

How to really read text file from classpath in Java

If you use Guava:

import com.google.common.io.Resources;

we can get URL from CLASSPATH:

URL resource = Resources.getResource("test.txt");
String file = resource.getFile();   // get file path 

or InputStream:

InputStream is = Resources.getResource("test.txt").openStream();

Ways to convert an InputStream to a String

How to write log file in c#?

Add log to file with Static Class

 public static class LogWriter
        {
            private static string m_exePath = string.Empty;
            public static void LogWrite(string logMessage)
            {
                m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (!File.Exists(m_exePath + "\\" + "log.txt"))
                    File.Create(m_exePath + "\\" + "log.txt");

                try
                {
                    using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
                        AppendLog(logMessage, w);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }

            private static void AppendLog(string logMessage, TextWriter txtWriter)
            {
                try
                {
                    txtWriter.Write("\r\nLog Entry : ");
                    txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
                    txtWriter.WriteLine("  :");
                    txtWriter.WriteLine("  :{0}", logMessage);
                    txtWriter.WriteLine("-------------------------------");
                }
                catch (Exception ex)
                {
                }
            }
        }

Simulate a click on 'a' element using javascript/jquery

Using jQuery:

$('#gift-close').click();

CodeIgniter -> Get current URL relative to base url

// For current url
echo base_url(uri_string());

When to use "new" and when not to, in C++?

New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;

What is the difference between LATERAL and a subquery in PostgreSQL?

What is a LATERAL join?

The feature was introduced with PostgreSQL 9.3.
Quoting the manual:

Subqueries appearing in FROM can be preceded by the key word LATERAL. This allows them to reference columns provided by preceding FROM items. (Without LATERAL, each subquery is evaluated independently and so cannot cross-reference any other FROM item.)

Table functions appearing in FROM can also be preceded by the key word LATERAL, but for functions the key word is optional; the function's arguments can contain references to columns provided by preceding FROM items in any case.

Basic code examples are given there.

More like a correlated subquery

A LATERAL join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:

For returning more than one column, a LATERAL join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true:

Things a subquery can't do

There are things that a LATERAL join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM clause. Like unnest() with multiple parameters in Postgres 9.4 or later. The manual:

This is only allowed in the FROM clause;

So this works, but cannot (easily) be replaced with a subquery:

CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2);  -- implicit LATERAL

The comma (,) in the FROM clause is short notation for CROSS JOIN.
LATERAL is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] ):

Set-returning functions in the SELECT list

You can also use set-returning functions like unnest() in the SELECT list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:

Building on above example:

SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM   tbl;

Comparison:

dbfiddle for pg 9.6 here
dbfiddle for pg 10 here

Clarify misinformation

The manual:

For the INNER and OUTER join types, a join condition must be specified, namely exactly one of NATURAL, ON join_condition, or USING (join_column [, ...]). See below for the meaning.
For CROSS JOIN, none of these clauses can appear.

So these two queries are valid (even if not particularly useful):

SELECT *
FROM   tbl t
LEFT   JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;

SELECT *
FROM   tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;

While this one is not:

SELECT *
FROM   tbl t
LEFT   JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;

That's why Andomar's code example is correct (the CROSS JOIN does not require a join condition) and Attila's is was not.

How can I "reset" an Arduino board?

I just spent the last five hours searching for a solution to this problem (serial port COM3 already in use and grayed out serial port)...I tried everything every forum and Q&A site I could find suggested, including this one...

What finally fixed it (got rid of the last code I'd input that got stuck and uploaded simple blink function)?

Follow this link -- http://arduino.cc/en/guide/windows and follow the instructions for installing the drivers. My driver was "already up to date", but following these steps fixed the glitch. I am now a happy camper once again.

Note: Resetting the board manually with the button on the chip, or digitally through miscellaneous codes on the Internet did not work to fix this problem, because the signal was somehow blocked/confused between my Arduino Uno and the port in my laptop. Updating the drivers is like a reset for the "serial port already in use" problem.

At least so far...

How to go from one page to another page using javascript?

To simply redirect a browser using javascript:

window.location.href = "http://example.com/new_url";

To redirect AND submit a form (i.e. login details), requires no javascript:

<form action="/new_url" method="POST">
   <input name="username">
   <input type="password" name="password">
   <button type="submit">Submit</button>
</form>

Force browser to clear cache

Not as such. One method is to send the appropriate headers when delivering content to force the browser to reload:

Making sure a web page is not cached, across all browsers.

If your search for "cache header" or something similar here on SO, you'll find ASP.NET specific examples.

Another, less clean but sometimes only way if you can't control the headers on server side, is adding a random GET parameter to the resource that is being called:

myimage.gif?random=1923849839

How to get year/month/day from a date object?

var date = new Date().toLocaleDateString()
"12/30/2009"

adb remount permission denied, but able to access super user in shell -- android

you can use:

adb shell su -c "your command here"

only rooted devices with su works.

Capitalize first letter. MySQL

UPDATE users
SET first_name = CONCAT(UCASE(LEFT(first_name, 1)), 
                             LCASE(SUBSTRING(first_name, 2)))
,last_name = CONCAT(UCASE(LEFT(last_name, 1)), 
                             LCASE(SUBSTRING(last_name, 2)));

How should I pass an int into stringWithFormat?

And for comedic value:

label.text = [NSString stringWithFormat:@"%@", [NSNumber numberWithInt:count]];

(Though it could be useful if one day you're dealing with NSNumber's)

How to pass data to view in Laravel?

You can also do the same thing in another way,

If you are using PHP 5.5 or latest one then you can do it as follow,

Controller:

return view(index, compact('data1','data2')); //as many as you want to pass

View:

<div>
    You can access {{$data1}}. [if it is variable]
</div>

@foreach($data1 as $d1)
    <div>
        You can access {{$d1}}. [if it is array]
    </div>
@endforeach

Same way you can access all variable that you have passed in compact function.

Hope it helps :)

How to get multiple counts with one SQL query?

For MySQL, this can be shortened to:

SELECT distributor_id,
    COUNT(*) total,
    SUM(level = 'exec') ExecCount,
    SUM(level = 'personal') PersonalCount
FROM yourtable
GROUP BY distributor_id

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Can't append <script> element

Append script to body:

$(document).ready(function() {
    $("<script>", {  src : "bootstrap.min.js",  type : "text/javascript" }).appendTo("body");
});

Java HTTP Client Request with defined timeout

HttpConnectionParams.setSoTimeout(params, 10*60*1000);// for 10 mins i have set the timeout

You can as well define your required time out.

Iif equivalent in C#

C# has the ? ternary operator, like other C-style languages. However, this is not perfectly equivalent to IIf(); there are two important differences.

To explain the first difference, the false-part argument for this IIf() call causes a DivideByZeroException, even though the boolean argument is True.

IIf(true, 1, 1/0)

IIf() is just a function, and like all functions all the arguments must be evaluated before the call is made. Put another way, IIf() does not short circuit in the traditional sense. On the other hand, this ternary expression does short-circuit, and so is perfectly fine:

(true)?1:1/0;

The other difference is IIf() is not type safe. It accepts and returns arguments of type Object. The ternary operator is type safe. It uses type inference to know what types it's dealing with. Note you can fix this very easily with your own generic IIF(Of T)() implementation, but out of the box that's not the way it is.

If you really want IIf() in C#, you can have it:

object IIf(bool expression, object truePart, object falsePart) 
{return expression?truePart:falsePart;}

or a generic/type-safe implementation:

T IIf<T>(bool expression, T truePart, T falsePart) 
{return expression?truePart:falsePart;}

On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new If() operator that works like C#'s ternary operator. It uses type inference to know what it's returning, and it really is an operator rather than a function. This means there's no issues from pre-evaluating expressions, even though it has function semantics.

python setup.py uninstall

Note: Avoid using python setup.py install use pip install .

You need to remove all files manually, and also undo any other stuff that installation did manually.

If you don't know the list of all files, you can reinstall it with the --record option, and take a look at the list this produces.

To record a list of installed files, you can use:

python setup.py install --record files.txt

Once you want to uninstall you can use xargs to do the removal:

xargs rm -rf < files.txt

Or if you're running Windows, use Powershell:

Get-Content files.txt | ForEach-Object {Remove-Item $_ -Recurse -Force}

Then delete also the containing directory, e.g. /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/my_module-0.1.egg/ on macOS. It has no files, but Python will still import an empty module:

>>> import my_module
>>> my_module.__file__
None

Once deleted, Python shows:

>>> import my_module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'my_module'

Finding the type of an object in C++

Your description is a little confusing.

Generally speaking, though some C++ implementations have mechanisms for it, you're not supposed to ask about the type. Instead, you are supposed to do a dynamic_cast on the pointer to A. What this will do is that at runtime, the actual contents of the pointer to A will be checked. If you have a B, you'll get your pointer to B. Otherwise, you'll get an exception or null.

What is the difference between vmalloc and kmalloc?

Linux Kernel Development by Robert Love (Chapter 12, page 244 in 3rd edition) answers this very clearly.

Yes, physically contiguous memory is not required in many of the cases. Main reason for kmalloc being used more than vmalloc in kernel is performance. The book explains, when big memory chunks are allocated using vmalloc, kernel has to map the physically non-contiguous chunks (pages) into a single contiguous virtual memory region. Since the memory is virtually contiguous and physically non-contiguous, several virtual-to-physical address mappings will have to be added to the page table. And in the worst case, there will be (size of buffer/page size) number of mappings added to the page table.

This also adds pressure on TLB (the cache entries storing recent virtual to physical address mappings) when accessing this buffer. This can lead to thrashing.

How to select only 1 row from oracle sql?

The answer is:

You should use nested query as:

SELECT *
FROM ANY_TABLE_X 
WHERE ANY_COLUMN_X = (SELECT MAX(ANY_COLUMN_X) FROM ANY_TABLE_X) 

=> In PL/SQL "ROWNUM = 1" is NOT equal to "TOP 1" of TSQL.

So you can't use a query like this: "select * from any_table_x where rownum=1 order by any_column_x;" Because oracle gets first row then applies order by clause.

Align image in center and middle within div

This should work.

IMPORTANT FOR TEST: To Run code snippet click left button RUN code snippet, then right link Full page

_x000D_
_x000D_
#fader{_x000D_
position:fixed;z-index: 10;_x000D_
top:0;right:0;bottom:0;left:0;_x000D_
opacity: 0.8;background: black;_x000D_
width:100%;height:100%;_x000D_
text-align: center;_x000D_
}_x000D_
.faders{display:inline-block;height:100%;vertical-align:middle;}_x000D_
.faderi{display:inline-block;vertical-align:middle;}
_x000D_
<div id="fader">_x000D_
<span class="faders"></span>_x000D_
<img class="faderi" src="https://i.stack.imgur.com/qHF2K.png" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Program to find prime numbers

Prime Helper very fast calculation

public static class PrimeHelper
{

    public static IEnumerable<Int32> FindPrimes(Int32 maxNumber)
    {
        return (new PrimesInt32(maxNumber));
    }

    public static IEnumerable<Int32> FindPrimes(Int32 minNumber, Int32 maxNumber)
    {
        return FindPrimes(maxNumber).Where(pn => pn >= minNumber);
    }

    public static bool IsPrime(this Int64 number)
    {
        if (number < 2)
            return false;
        else if (number < 4 )
            return true;

        var limit = (Int32)System.Math.Sqrt(number) + 1;
        var foundPrimes = new PrimesInt32(limit);

        return !foundPrimes.IsDivisible(number);
    }

    public static bool IsPrime(this Int32 number)
    {
        return IsPrime(Convert.ToInt64(number));
    }

    public static bool IsPrime(this Int16 number)
    {
        return IsPrime(Convert.ToInt64(number));
    }

    public static bool IsPrime(this byte number)
    {
        return IsPrime(Convert.ToInt64(number));
    }
}

public class PrimesInt32 : IEnumerable<Int32>
{
    private Int32 limit;
    private BitArray numbers;

    public PrimesInt32(Int32 limit)
    {
        if (limit < 2)
            throw new Exception("Prime numbers not found.");

        startTime = DateTime.Now;
        calculateTime = startTime - startTime;
        this.limit = limit;
        try { findPrimes(); } catch{/*Overflows or Out of Memory*/}

        calculateTime = DateTime.Now - startTime;
    }

    private void findPrimes()
    {
        /*
        The Sieve Algorithm
        http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
        */
        numbers = new BitArray(limit, true);
        for (Int32 i = 2; i < limit; i++)
            if (numbers[i])
                for (Int32 j = i * 2; j < limit; j += i)
                     numbers[j] = false;
    }

    public IEnumerator<Int32> GetEnumerator()
    {
        for (Int32 i = 2; i < 3; i++)
            if (numbers[i])
                yield return i;
        if (limit > 2)
            for (Int32 i = 3; i < limit; i += 2)
                if (numbers[i])
                    yield return i;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    // Extended for Int64
    public bool IsDivisible(Int64 number)
    {
        var sqrt = System.Math.Sqrt(number);
        foreach (var prime in this)
        {
            if (prime > sqrt)
                break;
            if (number % prime == 0)
            {
                DivisibleBy = prime;
                return true;
            }
        }
        return false;
    }

    private static DateTime startTime;
    private static TimeSpan calculateTime;
    public static TimeSpan CalculateTime { get { return calculateTime; } }
    public Int32 DivisibleBy { get; set; }
}

How to get progress from XMLHttpRequest

For the total uploaded there doesn't seem to be a way to handle that, but there's something similar to what you want for download. Once readyState is 3, you can periodically query responseText to get all the content downloaded so far as a String (this doesn't work in IE), up until all of it is available at which point it will transition to readyState 4. The total bytes downloaded at any given time will be equal to the total bytes in the string stored in responseText.

For a all or nothing approach to the upload question, since you have to pass a string for upload (and it's possible to determine the total bytes of that) the total bytes sent for readyState 0 and 1 will be 0, and the total for readyState 2 will be the total bytes in the string you passed in. The total bytes both sent and received in readyState 3 and 4 will be the sum of the bytes in the original string plus the total bytes in responseText.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

What is the most efficient way to concatenate N arrays?

[].concat.apply([], [array1, array2, ...])

edit: proof of efficiency: http://jsperf.com/multi-array-concat/7

edit2: Tim Supinie mentions in the comments that this may cause the interpreter to exceed the call stack size. This is perhaps dependent on the js engine, but I've also gotten "Maximum call stack size exceeded" on Chrome at least. Test case: [].concat.apply([], Array(300000).fill().map(_=>[1,2,3])). (I've also gotten the same error using the currently accepted answer, so one is anticipating such use cases or building a library for others, special testing may be necessary no matter which solution you choose.)

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Table row and column number in jQuery

its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am

Laravel: Validation unique on update

It works like a charm someone can try this. Here I have used soft delete checker. You could omit the last: id,deleted_at, NULL if your model doesn't have soft delete implementation.

public function rules()
{
    switch ($this->method()) {
        case 'PUT':
            $emailRules = "required|unique:users,email,{$this->id},id,deleted_at,NULL";
            break;
        default:
            $emailRules = "required|unique:users,email,NULL,id,deleted_at,NULL";
            break;
    }

    return [
        'email' => $emailRules,
        'display_name' => 'nullable',
        'description' => 'nullable',
    ];
}

Thank you.

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

How to parse XML in Bash?

starting from the chad's answer, here is the COMPLETE working solution to parse UML, with propper handling of comments, with just 2 little functions (more than 2 bu you can mix them all). I don't say chad's one didn't work at all, but it had too much issues with badly formated XML files: So you have to be a bit more tricky to handle comments and misplaced spaces/CR/TAB/etc.

The purpose of this answer is to give ready-2-use, out of the box bash functions to anyone needing parsing UML without complex tools using perl, python or anything else. As for me, I cannot install cpan, nor perl modules for the old production OS i'm working on, and python isn't available.

First, a definition of the UML words used in this post:

<!-- comment... -->
<tag attribute="value">content...</tag>

EDIT: updated functions, with handle of:

  • Websphere xml (xmi and xmlns attributes)
  • must have a compatible terminal with 256 colors
  • 24 shades of grey
  • compatibility added for IBM AIX bash 3.2.16(1)

The functions, first is the xml_read_dom which's called recursively by xml_read:

xml_read_dom() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
local ENTITY IFS=\>
if $ITSACOMMENT; then
  read -d \< COMMENTS
  COMMENTS="$(rtrim "${COMMENTS}")"
  return 0
else
  read -d \< ENTITY CONTENT
  CR=$?
  [ "x${ENTITY:0:1}x" == "x/x" ] && return 0
  TAG_NAME=${ENTITY%%[[:space:]]*}
  [ "x${TAG_NAME}x" == "x?xmlx" ] && TAG_NAME=xml
  TAG_NAME=${TAG_NAME%%:*}
  ATTRIBUTES=${ENTITY#*[[:space:]]}
  ATTRIBUTES="${ATTRIBUTES//xmi:/}"
  ATTRIBUTES="${ATTRIBUTES//xmlns:/}"
fi

# when comments sticks to !-- :
[ "x${TAG_NAME:0:3}x" == "x!--x" ] && COMMENTS="${TAG_NAME:3} ${ATTRIBUTES}" && ITSACOMMENT=true && return 0

# http://tldp.org/LDP/abs/html/string-manipulation.html
# INFO: oh wait it doesn't work on IBM AIX bash 3.2.16(1):
# [ "x${ATTRIBUTES:(-1):1}x" == "x/x" -o "x${ATTRIBUTES:(-1):1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:(-1)}"
[ "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x/x" -o "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:${#ATTRIBUTES} -1}"
return $CR
}

and the second one :

xml_read() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
ITSACOMMENT=false
local MULTIPLE_ATTR LIGHT FORCE_PRINT XAPPLY XCOMMAND XATTRIBUTE GETCONTENT fileXml tag attributes attribute tag2print TAGPRINTED attribute2print XAPPLIED_COLOR PROSTPROCESS USAGE
local TMP LOG LOGG
LIGHT=false
FORCE_PRINT=false
XAPPLY=false
MULTIPLE_ATTR=false
XAPPLIED_COLOR=g
TAGPRINTED=false
GETCONTENT=false
PROSTPROCESS=cat
Debug=${Debug:-false}
TMP=/tmp/xml_read.$RANDOM
USAGE="${C}${FUNCNAME}${c} [-cdlp] [-x command <-a attribute>] <file.xml> [tag | \"any\"] [attributes .. | \"content\"]
${nn[2]}  -c = NOCOLOR${END}
${nn[2]}  -d = Debug${END}
${nn[2]}  -l = LIGHT (no \"attribute=\" printed)${END}
${nn[2]}  -p = FORCE PRINT (when no attributes given)${END}
${nn[2]}  -x = apply a command on an attribute and print the result instead of the former value, in green color${END}
${nn[1]}  (no attribute given will load their values into your shell; use '-p' to print them as well)${END}"

! (($#)) && echo2 "$USAGE" && return 99
(( $# < 2 )) && ERROR nbaram 2 0 && return 99
# getopts:
while getopts :cdlpx:a: _OPT 2>/dev/null
do
{
  case ${_OPT} in
    c) PROSTPROCESS="${DECOLORIZE}" ;;
    d) local Debug=true ;;
    l) LIGHT=true; XAPPLIED_COLOR=END ;;
    p) FORCE_PRINT=true ;;
    x) XAPPLY=true; XCOMMAND="${OPTARG}" ;;
    a) XATTRIBUTE="${OPTARG}" ;;
    *) _NOARGS="${_NOARGS}${_NOARGS+, }-${OPTARG}" ;;
  esac
}
done
shift $((OPTIND - 1))
unset _OPT OPTARG OPTIND
[ "X${_NOARGS}" != "X" ] && ERROR param "${_NOARGS}" 0

fileXml=$1
tag=$2
(( $# > 2 )) && shift 2 && attributes=$*
(( $# > 1 )) && MULTIPLE_ATTR=true

[ -d "${fileXml}" -o ! -s "${fileXml}" ] && ERROR empty "${fileXml}" 0 && return 1
$XAPPLY && $MULTIPLE_ATTR && [ -z "${XATTRIBUTE}" ] && ERROR param "-x command " 0 && return 2
# nb attributes == 1 because $MULTIPLE_ATTR is false
[ "${attributes}" == "content" ] && GETCONTENT=true

while xml_read_dom; do
  # (( CR != 0 )) && break
  (( PIPESTATUS[1] != 0 )) && break

  if $ITSACOMMENT; then
    # oh wait it doesn't work on IBM AIX bash 3.2.16(1):
    # if [ "x${COMMENTS:(-2):2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:(-2)}" && ITSACOMMENT=false
    # elif [ "x${COMMENTS:(-3):3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:(-3)}" && ITSACOMMENT=false
    if [ "x${COMMENTS:${#COMMENTS} - 2:2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 2}" && ITSACOMMENT=false
    elif [ "x${COMMENTS:${#COMMENTS} - 3:3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 3}" && ITSACOMMENT=false
    fi
    $Debug && echo2 "${N}${COMMENTS}${END}"
  elif test "${TAG_NAME}"; then
    if [ "x${TAG_NAME}x" == "x${tag}x" -o "x${tag}x" == "xanyx" ]; then
      if $GETCONTENT; then
        CONTENT="$(trim "${CONTENT}")"
        test ${CONTENT} && echo "${CONTENT}"
      else
        # eval local $ATTRIBUTES => eval test "\"\$${attribute}\"" will be true for matching attributes
        eval local $ATTRIBUTES
        $Debug && (echo2 "${m}${TAG_NAME}: ${M}$ATTRIBUTES${END}"; test ${CONTENT} && echo2 "${m}CONTENT=${M}$CONTENT${END}")
        if test "${attributes}"; then
          if $MULTIPLE_ATTR; then
            # we don't print "tag: attr=x ..." for a tag passed as argument: it's usefull only for "any" tags so then we print the matching tags found
            ! $LIGHT && [ "x${tag}x" == "xanyx" ] && tag2print="${g6}${TAG_NAME}: "
            for attribute in ${attributes}; do
              ! $LIGHT && attribute2print="${g10}${attribute}${g6}=${g14}"
              if eval test "\"\$${attribute}\""; then
                test "${tag2print}" && ${print} "${tag2print}"
                TAGPRINTED=true; unset tag2print
                if [ "$XAPPLY" == "true" -a "${attribute}" == "${XATTRIBUTE}" ]; then
                  eval ${print} "%s%s\ " "\${attribute2print}" "\${${XAPPLIED_COLOR}}\"\$(\$XCOMMAND \$${attribute})\"\${END}" && eval unset ${attribute}
                else
                  eval ${print} "%s%s\ " "\${attribute2print}" "\"\$${attribute}\"" && eval unset ${attribute}
                fi
              fi
            done
            # this trick prints a CR only if attributes have been printed durint the loop:
            $TAGPRINTED && ${print} "\n" && TAGPRINTED=false
          else
            if eval test "\"\$${attributes}\""; then
              if $XAPPLY; then
                eval echo "\${g}\$(\$XCOMMAND \$${attributes})" && eval unset ${attributes}
              else
                eval echo "\$${attributes}" && eval unset ${attributes}
              fi
            fi
          fi
        else
          echo eval $ATTRIBUTES >>$TMP
        fi
      fi
    fi
  fi
  unset CR TAG_NAME ATTRIBUTES CONTENT COMMENTS
done < "${fileXml}" | ${PROSTPROCESS}
# http://mywiki.wooledge.org/BashFAQ/024
# INFO: I set variables in a "while loop" that's in a pipeline. Why do they disappear? workaround:
if [ -s "$TMP" ]; then
  $FORCE_PRINT && ! $LIGHT && cat $TMP
  # $FORCE_PRINT && $LIGHT && perl -pe 's/[[:space:]].*?=/ /g' $TMP
  $FORCE_PRINT && $LIGHT && sed -r 's/[^\"]*([\"][^\"]*[\"][,]?)[^\"]*/\1 /g' $TMP
  . $TMP
  rm -f $TMP
fi
unset ITSACOMMENT
}

and lastly, the rtrim, trim and echo2 (to stderr) functions:

rtrim() {
local var=$@
var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
echo -n "$var"
}
trim() {
local var=$@
var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
echo -n "$var"
}
echo2() { echo -e "$@" 1>&2; }

Colorization:

oh and you will need some neat colorizing dynamic variables to be defined at first, and exported, too:

set -a
TERM=xterm-256color
case ${UNAME} in
AIX|SunOS)
  M=$(${print} '\033[1;35m')
  m=$(${print} '\033[0;35m')
  END=$(${print} '\033[0m')
;;
*)
  m=$(tput setaf 5)
  M=$(tput setaf 13)
  # END=$(tput sgr0)          # issue on Linux: it can produces ^[(B instead of ^[[0m, more likely when using screenrc
  END=$(${print} '\033[0m')
;;
esac
# 24 shades of grey:
for i in $(seq 0 23); do eval g$i="$(${print} \"\\033\[38\;5\;$((232 + i))m\")" ; done
# another way of having an array of 5 shades of grey:
declare -a colorNums=(238 240 243 248 254)
for num in 0 1 2 3 4; do nn[$num]=$(${print} "\033[38;5;${colorNums[$num]}m"); NN[$num]=$(${print} "\033[48;5;${colorNums[$num]}m"); done
# piped decolorization:
DECOLORIZE='eval sed "s,${END}\[[0-9;]*[m|K],,g"'

How to load all that stuff:

Either you know how to create functions and load them via FPATH (ksh) or an emulation of FPATH (bash)

If not, just copy/paste everything on the command line.

How does it work:

xml_read [-cdlp] [-x command <-a attribute>] <file.xml> [tag | "any"] [attributes .. | "content"]
  -c = NOCOLOR
  -d = Debug
  -l = LIGHT (no \"attribute=\" printed)
  -p = FORCE PRINT (when no attributes given)
  -x = apply a command on an attribute and print the result instead of the former value, in green color
  (no attribute given will load their values into your shell as $ATTRIBUTE=value; use '-p' to print them as well)

xml_read server.xml title content     # print content between <title></title>
xml_read server.xml Connector port    # print all port values from Connector tags
xml_read server.xml any port          # print all port values from any tags

With Debug mode (-d) comments and parsed attributes are printed to stderr

Selenium IDE - Command to wait for 5 seconds

This will wait until your link has appeared, and then you can click it.

Command: waitForElementPresent Target: link=do something Value:

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

just adding to above answers, when we have a static code (ie code block is instance independent) that needs to be present in memory, we can have the class returned so we'll use Class.forname("someName") else if we dont have static code we can go for Class.forname().newInstance("someName") as it will load object level code blocks(non static) to memory

Return char[]/string from a function

If you want to return a char* from a function, make sure you malloc() it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.

change it to

char* createStr() {
    char char1= 'm';
    char char2= 'y';
    char *str = malloc(3 * sizeof(char));
    if(str == NULL) return NULL;
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';
    return str;
}

Putting a password to a user in PhpMyAdmin in Wamp

my config.inc.php file in the phpmyadmin folder. Change username and password to the one you have set for your database.

    <?php
/*
 * This is needed for cookie based authentication to encrypt password in
 * cookie
 */
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'enter_username_here';
$cfg['Servers'][$i]['password'] = 'enter_password_here';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';

/*
 * End of servers configuration
 */

?>

How to generate a random number between 0 and 1?

Here's a general procedure for producing a random number in a specified range:

int randInRange(int min, int max)
{
  return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1));
}

Depending on the PRNG algorithm being used, the % operator may result in a very non-random sequence of numbers.

Explaining the 'find -mtime' command

To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.

find . -mtime -1 -ls

Efficiently getting all divisors of a given number

//DIVISORS IN TIME COMPLEXITY sqrt(n)

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
    ll int n;
    cin >> n;

    for(ll i = 2;  i <= sqrt(n); i++)
    {
        if (n%i==0)
        {
            if (n/i!=i)
                cout << i << endl << n/i<< endl;
            else
                cout << i << endl;
        }
    }
}

Getting all names in an enum as a String[]

Got the simple solution

Arrays.stream(State.values()).map(Enum::name).collect(Collectors.toList())

Fastest way to check if a file exist using standard C++/C++11/C?

If you need to distinguish between a file and a directory, consider the following which both use stat which the fastest standard tool as demonstrated by PherricOxide:

#include <sys/stat.h>
int FileExists(char *path)
{
    struct stat fileStat; 
    if ( stat(path, &fileStat) )
    {
        return 0;
    }
    if ( !S_ISREG(fileStat.st_mode) )
    {
        return 0;
    }
    return 1;
}

int DirExists(char *path)
{
    struct stat fileStat;
    if ( stat(path, &fileStat) )
    {
        return 0;
    }
    if ( !S_ISDIR(fileStat.st_mode) )
    {
        return 0;
    }
    return 1;
}

Can git undo a checkout of unstaged files

Technically yes. But only on certain instances. If for example you have the code page up and you hit git checkout, and you realize that you accidently checked out the wrong page or something. Go to the page and click undo. (for me, command + z), and it will go back to exactly where you were before you hit the good old git checkout.

This will not work if your page has been closed, and then you hit git checkout. It only works if the actual code page is open

Redirect to new Page in AngularJS using $location

$location won't help you with external URLs, use the $window service instead:

$window.location.href = 'http://www.google.com';

Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.

how to set start page in webconfig file in asp.net c#

You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.

void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

            Response.Redirect("~/Index.aspx");

        }

You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings

Get Memory Usage in Android

I use this function to calculate cpu usage. Hope it can help you.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" +");  // Split on one or more spaces

        long idle1 = Long.parseLong(toks[4]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" +");

        long idle2 = Long.parseLong(toks[4]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 

Which Python memory profiler is recommended?

guppy3 is quite simple to use. At some point in your code, you have to write the following:

from guppy import hpy
h = hpy()
print(h.heap())

This gives you some output like this:

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.

There is a graphical browser as well, written in Tk.

For Python 2.x, use Heapy.

Find column whose name contains a specific string

Just iterate over DataFrame.columns, now this is an example in which you will end up with a list of column names that match:

import pandas as pd

data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)

spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)

Output:

['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']

Explanation:

  1. df.columns returns a list of column names
  2. [col for col in df.columns if 'spike' in col] iterates over the list df.columns with the variable col and adds it to the resulting list if col contains 'spike'. This syntax is list comprehension.

If you only want the resulting data set with the columns that match you can do this:

df2 = df.filter(regex='spike')
print(df2)

Output:

   spike-2  spiked-in
0        1          7
1        2          8
2        3          9

Targeting only Firefox with CSS

Here is some browser hacks for targeting only the Firefox browser,

Using selector hacks.

_:-moz-tree-row(hover), .selector {}

JavaScript Hacks

var isFF = !!window.sidebar;

var isFF = 'MozAppearance' in document.documentElement.style;

var isFF = !!navigator.userAgent.match(/firefox/i);

Media Query Hacks

This is gonna work on, Firefox 3.6 and Later

@media screen and (-moz-images-in-menus:0) {}

If you need more information,Please visit browserhacks

Parse query string into an array

If you're having a problem converting a query string to an array because of encoded ampersands

&amp;

then be sure to use html_entity_decode

Example:

// Input string //
$input = 'pg_id=2&amp;parent_id=2&amp;document&amp;video';

// Parse //
parse_str(html_entity_decode($input), $out);

// Output of $out //
array(
  'pg_id' => 2,
  'parent_id' => 2,
  'document' => ,
  'video' =>
)

SCRIPT438: Object doesn't support property or method IE

I forgot to use var on my item variable

Incorrect code:

var itemCreateInfo = new SP.ListItemCreationInformation();
item = list.addItem(itemCreateInfo); 
item.set_item('Title', 'Haytham - Oil Eng'); 

Correct code:

var itemCreateInfo = new SP.ListItemCreationInformation();
var item = list.addItem(itemCreateInfo);  
item.set_item('Title', 'Haytham - Oil Eng');

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

I had problems using pdftk with the cat parameter had a better success with output.

The following command worked for me:

pdftk file_1.pdf file_1.pdf file_1.pdf file_1.pdf cat output.pdf

Using cat produced the following error:

Error: Unexpected text in page range end, here: 
    output.pdf
    Exiting.
    Acceptable keywords, for example: "even" or "odd".
    To rotate pages, use: "north" "south" "east"
        "west" "left" "right" or "down"
Errors encountered.  No output created.
Done.  Input errors, so no output created.

http://www.pdflabs.com/docs/pdftk-cli-examples/.

I created a 172mb PDF is no time at all.

Extract subset of key-value pairs from Python dictionary object?

This answer uses a dictionary comprehension similar to the selected answer, but will not except on a missing item.

python 2 version:

{k:v for k, v in bigDict.iteritems() if k in ('l', 'm', 'n')}

python 3 version:

{k:v for k, v in bigDict.items() if k in ('l', 'm', 'n')}

Best way to update data with a RecyclerView adapter

RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:

class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   List<Data> data;
   ...

    public void swap(ArrayList<Data> datas)
    {
        data.clear();
        data.addAll(datas);
        notifyDataSetChanged();     
    }
}

Also there is a difference between

list.clear();
list.add(data);

and

list = newList;

The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.

Error: Execution failed for task ':app:clean'. Unable to delete file

I just solved this exact problem for myself.

The problem was that somebody else had created the file so even though I have admin rights on the computer I was unable to make changes to the file or files. You need to go into the properties of the file or folder and change the ownership or add ownership. This web page explains it well step by step what you need to do.

Once I did the above, I found the file in file explorer and manually extracted it. I don't think it's needed in the android studio project if it was trying to delete it anyway.

How to replace innerHTML of a div using jQuery?

The html() function can take strings of HTML, and will effectively modify the .innerHTML property.

$('#regTitle').html('Hello World');

However, the text() function will change the (text) value of the specified element, but keep the html structure.

$('#regTitle').text('Hello world'); 

Font Awesome 5 font-family issue

Requiring 900 weight is not a weirdness but a intentional restriction added by FontAwesome (since they share the same unicode but just different font-weight) so that you are not hacking your way into using the 'solid' and 'light' icons, most of which are available only in the paid 'Pro' version.

How to unpack an .asar file?

https://www.electronjs.org/apps/asarui

UI for Asar, Extract All, or drag extract file/directory

PostgreSQL Autoincrement

In the context of the asked question and in reply to the comment by @sereja1c, creating SERIAL implicitly creates sequences, so for the above example-

CREATE TABLE foo (id SERIAL,bar varchar);

CREATE TABLE would implicitly create sequence foo_id_seq for serial column foo.id. Hence, SERIAL [4 Bytes] is good for its ease of use unless you need a specific datatype for your id.

if statements matching multiple values

An extensionmethod like this would do it...

public static bool In<T>(this T item, params T[] items)
{
    return items.Contains(item);
}

Use it like this:

Console.WriteLine(1.In(1,2,3));
Console.WriteLine("a".In("a", "b"));

How can I debug my JavaScript code?

I used to use Firebug, until Internet Explorer 8 came out. I'm not a huge fan of Internet Explorer, but after spending some time with the built-in developer tools, which includes a really nice debugger, it seems pointless to use anything else. I have to tip my hat to Microsoft they did a fantastic job on this tool.

Why does printf not flush after the call unless a newline is in the format string?

There are generally 2 levels of buffering-

1. Kernel buffer Cache (makes read/write faster)

2. Buffering in I/O library (reduces no. of system calls)

Let's take example of fprintf and write().

When you call fprintf(), it doesn't wirte directly to the file. It first goes to stdio buffer in the program's memory. From there it is written to the kernel buffer cache by using write system call. So one way to skip I/O buffer is directly using write(). Other ways are by using setbuff(stream,NULL). This sets the buffering mode to no buffering and data is directly written to kernel buffer. To forcefully make the data to be shifted to kernel buffer, we can use "\n", which in case of default buffering mode of 'line buffering', will flush I/O buffer. Or we can use fflush(FILE *stream).

Now we are in kernel buffer. Kernel(/OS) wants to minimise disk access time and hence it reads/writes only blocks of disk. So when a read() is issued, which is a system call and can be invoked directly or through fscanf(), kernel reads the disk block from disk and stores it in a buffer. After that data is copied from here to user space.

Similarly that fprintf() data recieved from I/O buffer is written to the disk by the kernel. This makes read() write() faster.

Now to force the kernel to initiate a write(), after which data transfer is controlled by hardware controllers, there are also some ways. We can use O_SYNC or similar flags during write calls. Or we could use other functions like fsync(),fdatasync(),sync() to make the kernel initiate writes as soon as data is available in the kernel buffer.

Build Step Progress Bar (css and jquery)

There are a lot of very nice answers on this page and I googled for some more, but none of the answers ticked all the checkboxes on my wish list:

  • CSS only, no Javascript
  • Stick to Tom Kenny's Best Design Practices
  • Layout like the other answers
  • Each step has a name and a number
  • Responsive layout: font size independent
  • Fluid layout: the list and its items scale with the available width
  • The names and numbers are centered in their block
  • The "done" color goes up to and including the active item, but not past it.
  • The active item should stand out graphically

So I mixed the code of several examples, fixed the things that I needed and here is the result:

Progress Tracker v2

I used the following CSS and HTML:

_x000D_
_x000D_
/* Progress Tracker v2 */_x000D_
ol.progress[data-steps="2"] li { width: 49%; }_x000D_
ol.progress[data-steps="3"] li { width: 33%; }_x000D_
ol.progress[data-steps="4"] li { width: 24%; }_x000D_
ol.progress[data-steps="5"] li { width: 19%; }_x000D_
ol.progress[data-steps="6"] li { width: 16%; }_x000D_
ol.progress[data-steps="7"] li { width: 14%; }_x000D_
ol.progress[data-steps="8"] li { width: 12%; }_x000D_
ol.progress[data-steps="9"] li { width: 11%; }_x000D_
_x000D_
.progress {_x000D_
    width: 100%;_x000D_
    list-style: none;_x000D_
    list-style-image: none;_x000D_
    margin: 20px 0 20px 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
.progress li {_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.progress .name {_x000D_
    display: block;_x000D_
    vertical-align: bottom;_x000D_
    text-align: center;_x000D_
    margin-bottom: 1em;_x000D_
    color: black;_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .step {_x000D_
    color: black;_x000D_
    border: 3px solid silver;_x000D_
    background-color: silver;_x000D_
    border-radius: 50%;_x000D_
    line-height: 1.2;_x000D_
    width: 1.2em;_x000D_
    height: 1.2em;_x000D_
    display: inline-block;_x000D_
    z-index: 0;_x000D_
}_x000D_
_x000D_
.progress .step span {_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .active .name,_x000D_
.progress .active .step span {_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
.progress .step:before {_x000D_
    content: "";_x000D_
    display: block;_x000D_
    background-color: silver;_x000D_
    height: 0.4em;_x000D_
    width: 50%;_x000D_
    position: absolute;_x000D_
    bottom: 0.6em;_x000D_
    left: 0;_x000D_
    z-index: -1;_x000D_
}_x000D_
_x000D_
.progress .step:after {_x000D_
    content: "";_x000D_
    display: block;_x000D_
    background-color: silver;_x000D_
    height: 0.4em;_x000D_
    width: 50%;_x000D_
    position: absolute;_x000D_
    bottom: 0.6em;_x000D_
    right: 0;_x000D_
    z-index: -1;_x000D_
}_x000D_
_x000D_
.progress li:first-of-type .step:before {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
.progress li:last-of-type .step:after {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .done .step:before,_x000D_
.progress .done .step:after,_x000D_
.progress .active .step,_x000D_
.progress .active .step:before {_x000D_
    background-color: yellowgreen;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .active .step {_x000D_
    border: 3px solid yellowgreen;_x000D_
}
_x000D_
<!-- Progress Tracker v2 -->_x000D_
<ol class="progress" data-steps="4">_x000D_
    <li class="done">_x000D_
        <span class="name">Foo</span>_x000D_
        <span class="step"><span>1</span></span>_x000D_
    </li>_x000D_
    <li class="done">_x000D_
        <span class="name">Bar</span>_x000D_
        <span class="step"><span>2</span></span>_x000D_
    </li>_x000D_
    <li class="active">_x000D_
        <span class="name">Baz</span>_x000D_
        <span class="step"><span>3</span></span>_x000D_
    </li>_x000D_
    <li>_x000D_
        <span class="name">Quux</span>_x000D_
        <span class="step"><span>4</span></span>_x000D_
    </li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

As can be seen in the example above, there are now two list item classes to take note of: active and done. Use class="active" for the current step, use class="done" for all steps before it.

Also note the data-steps="4" in the ol tag; set this to the total number of steps to apply the correct size to all list items.

Feel free to play around with the JSFiddle. Enjoy!

How to start color picker on Mac OS?

You can call up the color picker from any Cocoa application (TextEdit, Mail, Keynote, Pages, etc.) by hitting Shift-Command-C

The following article explains more about using Mac OS's Color Picker.

http://www.macworld.com/article/46746/2005/09/colorpickersecrets.html

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

The easiest way to get rid of the the ugly frame in newer versions of matplotlib:

import matplotlib.pyplot as plt
plt.box(False)

If you really must always use the object oriented approach, then do: ax.set_frame_on(False).

SQL count rows in a table

Here is the Query

select count(*) from tablename

or

select count(rownum) from studennt

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

Reading in a JSON File Using Swift

Latest swift 3.0 absolutely working

func loadJson(filename fileName: String) -> [String: AnyObject]?
{
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") 
{
      if let data = NSData(contentsOf: url) {
          do {
                    let object = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
                    if let dictionary = object as? [String: AnyObject] {
                        return dictionary
                    }
                } catch {
                    print("Error!! Unable to parse  \(fileName).json")
                }
            }
            print("Error!! Unable to load  \(fileName).json")
        }
        return nil
    }

Intellij reformat on file save

If you have InteliJ Idea Community 2018.2 the steps are as fallows:

  1. In the top menu you click: Edit > Macros > Start Macro Recordings (you'll see a window lower right corner of your screen confirming that macros are being recorded)
  2. In the top menu you click: Code > Reformat Code (you'll see the option being selected in the lower right corner)
  3. In the top menu you click: Code > Optimize Imports (you'll see the option being selected in the lower right corner)
  4. In the top menu you click: File > Save All
  5. In the top menu you click: Edit > Macros > Stop Macro Recording
  6. You name the macro: "Format Code, Organize Imports, Save"
  7. In the top menu you clock: File > Settings. In the settings windows you click Keymap
  8. In the search box on the right you search "save". You'll find Save All (Ctrl+S). Right click on it and select "Remove Ctrl+S"
  9. Remove your search text from the box, press on the Collapse All button (Second button from the top left)
  10. Go to macros, press on the arrow to expand your macros, find your saved macro and right click on it. Select Add Keyboard Shortcut, and press Ctrl+S and okay.

Restart your IDE and try it.

I know what you're going to say, the guys before me wrote the same thing. But I got confused using the steps above this post, and I wanted to write a dumb down version for people who have the latest version of the IDE.

How can I get the error message for the mail() function?

There is no error message associated with the mail() function. There is only a true or false returned on whether the email was accepted for delivery. Not whether it ultimately gets delivered, but basically whether the domain exists and the address is a validly formatted email address.

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

Build Solution - Builds any assemblies which have changed files. If an assembly has no changes, it won't be re-built. Also will not delete any intermediate files.

Used most commonly.

Rebuild Solution - Rebuilds all assemblies regardless of changes but leaves intermediate files.

Used when you notice that Visual Studio didn't incorporate your changes in the latest assembly. Sometimes Visual Studio does make mistakes.

Clean Solution - Delete all intermediate files.

Used when all else fails and you need to clean everything up and start fresh.

How to return a class object by reference in C++?

Well, it is maybe not a really beautiful solution in the code, but it is really beautiful in the interface of your function. And it is also very efficient. It is ideal if the second is more important for you (for example, you are developing a library).

The trick is this:

  1. A line A a = b.make(); is internally converted to a constructor of A, i.e. as if you had written A a(b.make());.
  2. Now b.make() should result a new class, with a callback function.
  3. This whole thing can be fine handled only by classes, without any template.

Here is my minimal example. Check only the main(), as you can see it is simple. The internals aren't.

From the viewpoint of the speed: the size of a Factory::Mediator class is only 2 pointers, which is more that 1 but not more. And this is the only object in the whole thing which is transferred by value.

#include <stdio.h>

class Factory {
  public:
    class Mediator;

    class Result {
      public:
        Result() {
          printf ("Factory::Result::Result()\n");
        };

        Result(Mediator fm) {
          printf ("Factory::Result::Result(Mediator)\n");
          fm.call(this);
        };
    };

    typedef void (*MakeMethod)(Factory* factory, Result* result);

    class Mediator {
      private:
        Factory* factory;
        MakeMethod makeMethod;

      public:
        Mediator(Factory* factory, MakeMethod makeMethod) {
          printf ("Factory::Mediator::Mediator(Factory*, MakeMethod)\n");
          this->factory = factory;
          this->makeMethod = makeMethod;
        };

        void call(Result* result) {
          printf ("Factory::Mediator::call(Result*)\n");
          (*makeMethod)(factory, result);
        };
    };
};

class A;

class B : private Factory {
  private:
    int v;

  public:
    B(int v) {
      printf ("B::B()\n");
      this->v = v;
    };

    int getV() const {
      printf ("B::getV()\n");
      return v;
    };

    static void makeCb(Factory* f, Factory::Result* a);

    Factory::Mediator make() {
      printf ("Factory::Mediator B::make()\n");
      return Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
    };
};

class A : private Factory::Result {
  friend class B;

  private:
    int v;

  public:
    A() {
      printf ("A::A()\n");
      v = 0;
    };

    A(Factory::Mediator fm) : Factory::Result(fm) {
      printf ("A::A(Factory::Mediator)\n");
    };

    int getV() const {
      printf ("A::getV()\n");
      return v;
    };

    void setV(int v) {
      printf ("A::setV(%i)\n", v);
      this->v = v;
    };
};

void B::makeCb(Factory* f, Factory::Result* r) {
      printf ("B::makeCb(Factory*, Factory::Result*)\n");
      B* b = static_cast<B*>(f);
      A* a = static_cast<A*>(r);
      a->setV(b->getV()+1);
    };

int main(int argc, char **argv) {
  B b(42);
  A a = b.make();
  printf ("a.v = %i\n", a.getV());
  return 0;
}

Ways to insert javascript into URL?

I don't believe you can hack via the URL. Someone could try to inject code into your application if you are passing parameters (either GET or POST) into your app so your avoidance is going to be very similar to what you'd do for a local application.

Make sure you aren't adding parameters to SQL or other script executions that were passed into the code from the browser without making sure the strings don't contain any script language. Search the next for details about injection attacks for the development platform you are working with, that should yield lots of good advice and examples.

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

PHP/regex: How to get the string value of HTML tag?

try $pattern = "<($tagname)\b.*?>(.*?)</\1>" and return $matches[2]

how to query for a list<String> in jdbctemplate

You can't use placeholders for column names, table names, data type names, or basically anything that isn't data.

how to set start value as "0" in chartjs?

For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes instead of yAxes. Note that an array (and plural) is used for yAxes (or xAxes), because you may as well have multiple axes.

Programmatically scroll to a specific position in an Android ListView

I have set OnGroupExpandListener and override onGroupExpand() as:

and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs)

    yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
    {

        @Override
        public void onGroupExpand(int groupPosition) {

            expList.setSelectionFromTop(groupPosition, 0);
            //your other code
        }
    });

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

Creating a file only if it doesn't exist in Node.js

You can do something like this:

function writeFile(i){
    var i = i || 0;
    var fileName = 'a_' + i + '.jpg';
    fs.exists(fileName, function (exists) {
        if(exists){
            writeFile(++i);
        } else {
            fs.writeFile(fileName);
        }
    });
}

SQL update trigger only when column is modified

fyi The code I ended up with:

IF UPDATE (QtyToRepair)
    begin
        INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
        SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber 
        WHERE I.QtyToRepair <> D.QtyToRepair
end

How to get value at a specific index of array In JavaScript?

shift can be used in places where you want to get the first element (index=0) of an array and chain with other array methods.

example:

const comps = [{}, {}, {}]
const specComp = comps
                  .map(fn1)
                  .filter(fn2)
                  .shift()

Remember shift mutates the array, which is very different from accessing via an indexer.

Convert a positive number to negative in C#

Use binary and to remove the last bit which is responsible for negative sign.

Or use binary or to add sign to a datatype.

This soln may sound absurd and incomplete but I can guarantee this is the fastest method.

If you don't experiment with what I have posted this post may look crap :D

Eg for int:

Int is 32 bit datatype so the last bit (32th one) determines the sign.

And with a value which has 0 in the 32 place and rest 1. It will convert negative no to +ve.

For just the opposite or with a value with 1 in 32th place and rest 0.

Get size of a View in React Native

You can directly use the Dimensions module and calc your views sizes. Actually, Dimensions give to you the main window sizes.

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

Hope to help you!

Update: Today using native StyleSheet with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...

Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components

jQuery: Selecting by class and input type

Your selector is looking for any descendants of a checkbox element that have a class of .myClass.

Try this instead:

$("input.myClass:checkbox")

Check it out in action.

I also tested this:

$("input:checkbox.myClass")

And it will also work properly. In my humble opinion this syntax really looks rather ugly, as most of the time I expect : style selectors to come last. As I said, though, either one will work.

How to extract the hostname portion of a URL in JavaScript

There is another hack I use and never saw in any StackOverflow response : using "src" attribute of an image will yield the complete base path of your site. For instance :

var dummy = new Image;
dummy.src = '$';                  // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'

On an URL like http://domain.com/somesite/index.html, root will be set to http://domain.com/somesite/. This also works for localhost or any valid base URL.

Note that this will cause a failed HTTP request on the $ dummy image. You can use an existing image instead to avoid this, with only slight code changes.

Another variant uses a dummy link, with no side effect on HTTP requests :

var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;

I did not test it on every browser, though.

using facebook sdk in Android studio

I deployed Facebook Android SDK to Sonatype repository.

You can include this library as Gradle dependency:

repositories {
    maven {
        url 'https://oss.sonatype.org/content/groups/public'
    }
}

dependencies {
    compile 'com.shamanland:facebook-android-sdk:3.15.0-SNAPSHOT'
}

Original post here.

What does the Excel range.Rows property really do?

I've found myself using range.Rows for its effects in the Copy method. It copies the height of the rows from the origin to the destination, which is the behaviour I want.

rngLastRecord.Rows.Copy Destination:=Sheets("Availability").Range("a" & insertRow)

If I had used rngLastRecord.Copy instead of rngLastRecord.Rows.Copy, the row heights would be whatever was there before the copy.

Change the Arrow buttons in Slick slider

<div class="prev">Prev</div>

<div class="next">Next</div>

$('.your_class').slick({
        infinite: true,
        speed: 300,
        slidesToShow: 5,
        slidesToScroll: 5,
        arrows: true,
        prevArrow: $('.prev'),
        nextArrow: $('.next')
});

Swift - How to convert String to Double

my problem was comma so i solve it this way:

extension String {
    var doubleValue: Double {
        return Double((self.replacingOccurrences(of: ",", with: ".") as NSString).doubleValue)
    }
}

How to use andWhere and orWhere in Doctrine?

Why not just

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

EDIT: You can also use the Expr class (Doctrine2).

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

How To Remove Outline Border From Input Button

Removing nessorry accessible event not a good idea in up to standard web developments. either way if you looking for a solution removing just the outline doesn't solve the problem. you also have to remove the blue color shadow. for specific scenarios use a separate class name to isolate the this special style to your button.

.btn.focus, .btn:focus {
    outline: 0;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, .25);
}

Better do this

.remove-border.focus, .remove-border:focus {
        outline: 0;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, .25);
 }

MySQL count occurrences greater than 2

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1

Android custom Row Item for ListView

Step 1:Create a XML File

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <ListView
            android:id="@+id/lvItems"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </LinearLayout>

Step 2:Studnet.java

package com.scancode.acutesoft.telephonymanagerapp;


public class Student
{
    String email,phone,address;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Step 3:MainActivity.java

 package com.scancode.acutesoft.telephonymanagerapp;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ListView;

    import java.util.ArrayList;

    public class MainActivity extends Activity  {

        ListView lvItems;
        ArrayList<Student> studentArrayList ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            lvItems = (ListView) findViewById(R.id.lvItems);
            studentArrayList = new ArrayList<Student>();
            dataSaving();
            CustomAdapter adapter = new CustomAdapter(MainActivity.this,studentArrayList);
            lvItems.setAdapter(adapter);
        }

        private void dataSaving() {

            Student student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Hyderabad");
            studentArrayList.add(student);


            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);
        }


    }

Step 4:CustomAdapter.java

  package com.scancode.acutesoft.telephonymanagerapp;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import java.util.ArrayList;


    public class CustomAdapter extends BaseAdapter
    {
        ArrayList<Student> studentList;
        Context mContext;


        public CustomAdapter(Context context, ArrayList<Student> studentArrayList) {
            this.mContext = context;
            this.studentList = studentArrayList;

        }

        @Override
        public int getCount() {
            return studentList.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Student student = studentList.get(position);
            convertView = LayoutInflater.from(mContext).inflate(R.layout.student_row,null);

            TextView tvStudEmail = (TextView) convertView.findViewById(R.id.tvStudEmail);
            TextView tvStudPhone = (TextView) convertView.findViewById(R.id.tvStudPhone);
            TextView tvStudAddress = (TextView) convertView.findViewById(R.id.tvStudAddress);

            tvStudEmail.setText(student.getEmail());
            tvStudPhone.setText(student.getPhone());
            tvStudAddress.setText(student.getAddress());


            return convertView;
        }
    }

How to set value in @Html.TextBoxFor in Razor syntax?

The problem is that you are using a lower case v.

You need to set it to Value and it should fix your issue:

@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Comparing websocket and webrtc is unfair.

Websocket is based on top of TCP. Packet's boundary can be detected from header information of a websocket packet unlike tcp.

Typically, webrtc makes use of websocket. The signalling for webrtc is not defined, it is upto the service provider what kind of signalling he wants to use. It may be SIP, HTTP, JSON or any text / binary message.

The signalling messages can be send / received using websocket.

Why can't I call a public method in another class?

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

GradeBook myGradeBook = new GradeBook();

Then call the method on the obect you just created.

myGradeBook.[method you want called]

Vertical align in bootstrap table

As of Bootstrap 4 this is now much easier using the included utilities instead of custom CSS. You simply have to add the class align-middle to the td-element:

<table>
  <tbody>
    <tr>
      <td class="align-baseline">baseline</td>
      <td class="align-top">top</td>
      <td class="align-middle">middle</td>
      <td class="align-bottom">bottom</td>
      <td class="align-text-top">text-top</td>
      <td class="align-text-bottom">text-bottom</td>
    </tr>
  </tbody>
</table>

FIFO class in Java

You don't have to implement your own FIFO Queue, just look at the interface java.util.Queue and its implementations

How to tell if JRE or JDK is installed

A generic, pure Java solution..

For Windows and MacOS, the following can be inferred (most of the time)...

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null && path.contains("jdk")) {
        return true;
    }
    return false;
}

However... on Linux this isn't as reliable... For example...

  • Many JREs on Linux contain openjdk the path
  • There's no guarantee that the JRE doesn't also contain a JDK.

So a more fail-safe approach is to check for the existence of the javac executable.

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null) {
        String javacPath = "";
        if(path.endsWith(File.separator + "bin")) {
            javacPath = path;
        } else {
            int libIndex = path.lastIndexOf(File.separator + "lib");
            if(libIndex > 0) {
                javacPath = path.substring(0, libIndex) + File.separator + "bin";
            }
        }
        if(!javacPath.isEmpty()) {
            return new File(javacPath, "javac").exists() || new File(javacPath, "javac.exe").exists();
        }
    }
    return false;
}

Warning: This will still fail for JRE + JDK combos which report the JRE's sun.boot.library.path identically between the JRE and the JDK. For example, Fedora's JDK will fail (or pass depending on how you look at it) when the above code is run. See unit tests below for more info...

Unit tests:

# Unix
java -XshowSettings:properties -version 2>&1|grep "sun.boot.library.path"
# Windows
java -XshowSettings:properties -version 2>&1|find "sun.boot.library.path"
    # PASS: MacOS AdoptOpenJDK JDK11
    /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/lib

    # PASS: Windows Oracle JDK12
    c:\Program Files\Java\jdk-12.0.2\bin

    # PASS: Windows Oracle JRE8
    C:\Program Files\Java\jre1.8.0_181\bin

    # PASS: Windows Oracle JDK8
    C:\Program Files\Java\jdk1.8.0_181\bin

    # PASS: Ubuntu AdoptOpenJDK JDK11
    /usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/lib

    # PASS: Ubuntu Oracle JDK11
    /usr/lib/jvm/java-11-oracle/lib

    # PASS: Fedora OpenJDK JDK8
    /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.fc24.x86_64/jre/lib/amd64

    #### FAIL: Fedora OpenJDK JDK8
    /usr/java/jdk1.8.0_231-amd64/jre/lib/amd64

How to make a back-to-top button using CSS and HTML only?

HTML

<a name="gettop"></a>

<button id="btn"><a href="#gettop">Back to Top</a></button>

CSS

#btn {  
    position: fixed;
    bottom: 10px;
    float: right;
    right: 20.5%;
    left: 77.25%;
    max-width: 90px;
    width: 100%;
    font-size: 12px;
    border-color: rgba(5, 82, 248);
    background-color: rgb(5, 82, 248);
    padding: .5px;
    border-radius: 4px;
    font-family: Georgia, 'Times New Roman', Times, serif;
}

On Hover Color Change

#btn:hover {
    background-color: #fafafa;
}

Access parent's parent from javascript object

With the following code you can access the parent of the object:

var Users = function(parent) {
    this.parent = parent;
};
Users.prototype.guys = function(){ 
    this.parent.nameAndDestroy(['test-name-and-destroy']);
};
Users.prototype.girls = function(){ 
    this.parent.kiss(['test-kiss']);
};

var list = {
    users : function() {
        return new Users(this);
    },
    nameAndDestroy : function(group){ console.log(group); },
    kiss : function(group){ console.log(group); }
};

list.users().guys(); // should output ["test-name-and-destroy"]
list.users().girls(); // should output ["test-kiss"]

I would recommend you read about javascript Objects to get to know how you can work with Objects, it helped me a lot. I even found out about functions that I didn't even knew they existed.

Sharing a variable between multiple different threads

AtomicBoolean

The succinct Answer by NPE sums up your three options. I'll add some example code for the second item listed there: AtomicBoolean.

You can think of the AtomicBoolean class as providing some thread-safety wrapping around a boolean value.

If you instantiate the AtomicBoolean only once, then you need not worry about the visibility issue in the Java Memory Model that requires volatile as a solution (the first item in that other Answer). Also, you need not concern yourself with synchronization (the third item in that other Answer) because AtomicBoolean performs that function of protecting multi-threaded access to its internal boolean value.

Let's look at some example code.

Firstly, in modern Java we generally do not address the Thread class directly. We now have the Executors framework to simplify handling of threads.

This code below is using Project Loom technology, coming to a future version of Java. Preliminary builds available now, built on early-access Java 16. This makes for simpler coding, with ExecutorService being AutoCloseable for convenient use with try-with-resources syntax. But Project Loom is not related to the point of this Answer; it just makes for simpler code that is easier to understand as “structured concurrency”.

The idea here is that we have three threads: the original thread, plus a ExecutorService that will create two more threads. The two new threads both report the value of our AtomicBoolean. The first new thread does so immediately, while the other waits 10 seconds before reporting. Meanwhile, our main thread sleeps for 5 seconds, wakes, changes the AtomicBoolean object’s contained value, and then waits for that second thread to wake and complete its work the report on the now-altered AtomicBoolean contained value. While we are installing seconds between each event, this is merely for dramatic demonstration. The real point is that these threads could coincidently try to access the AtomicBoolean simultaneously, but that object will protect access to its internal boolean value in a thread-safe manner. Protecting against simultaneous access is the job of the Atomic… classes.

try (
        ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
    AtomicBoolean flag = new AtomicBoolean( true );

    // This task, when run, will immediately report the flag.
    Runnable task1 = ( ) -> System.out.println( "First task reporting flag = " + flag.get() + ". " + Instant.now() );

    // This task, when run, will wait several seconds, then report the flag. Meanwhile, code below waits a shorter time before *changing* the flag.
    Runnable task2 = ( ) -> {
        try { Thread.sleep( Duration.ofSeconds( 10 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
        System.out.println( "Second task reporting flag = " + flag.get() + ". " + Instant.now() );
    };

    executorService.submit( task1 );
    executorService.submit( task2 );

    // Wait for first task to complete, so sleep here briefly. But wake before the sleeping second task awakens.
    try { Thread.sleep( Duration.ofSeconds( 5 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
    System.out.println( "INFO - Original thread waking up, and setting flag to false. " + Instant.now() );
    flag.set( false );
}
// At this point, with Project Loom technology, the flow-of-control blocks until the submitted tasks are done.
// Also, the `ExecutorService` is automatically closed/shutdown by this point, via try-with-resources syntax.
System.out.println( "INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone." + Instant.now() );

Methods such as AtomicBoolean#get and AtomicBoolean#set are built to be thread-safe, to internally protect access to the boolean value nested within. Read up on the various other methods as well.

When run:

First task reporting flag = true. 2021-01-05T06:42:17.367337Z
INFO - Original thread waking up, and setting flag to false. 2021-01-05T06:42:22.367456Z
Second task reporting flag = false. 2021-01-05T06:42:27.369782Z
INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone.2021-01-05T06:42:27.372597Z

Pro Tip: When engaging in threaded code in Java, always study the excellent book, Java Concurrency in Practice by Brian Goetz et al.

How to properly use jsPDF library

You only need this link jspdf.min.js

It has everything in it.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

How to install multiple python packages at once using pip

pip install -r requirements.txt

and in the requirements.txt file you put your modules in a list, with one item per line.

  • Django=1.3.1

  • South>=0.7

  • django-debug-toolbar

How to read data from java properties file using Spring Boot

We can read properties file in spring boot using 3 way

1. Read value from application.properties Using @Value

map key as

public class EmailService {

 @Value("${email.username}")
 private String username;

}

2. Read value from application.properties Using @ConfigurationProperties

In this we will map prefix of key using ConfigurationProperties and key name is same as field of class

  @Component
   @ConfigurationProperties("email")
    public class EmailConfig {

        private String   username;
    }

3. Read application.properties Using using Environment object

public class EmailController {

@Autowired
private Environment env;

@GetMapping("/sendmail")
public void sendMail(){     
    System.out.println("reading value from application properties file  using Environment ");
    System.out.println("username ="+ env.getProperty("email.username"));
    System.out.println("pwd ="+ env.getProperty("email.pwd"));
}

Reference : how to read value from application.properties in spring boot

Date formatting in WPF datagrid

Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"

Go back button in a page

You can either use:

<button onclick="window.history.back()">Back</button>

or..

<button onclick="window.history.go(-1)">Back</button>

The difference, of course, is back() only goes back 1 page but go() goes back/forward the number of pages you pass as a parameter, relative to your current page.

How to post a file from a form with Axios

This works for me, I hope helps to someone.

var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
    .then(res => {
        console.log({res});
    }).catch(err => {
        console.error({err});
    });

Passing an array by reference

Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.

Spring Boot REST API - request timeout?

A fresh answer for Spring Boot 2.2 is required as server.connection-timeout=5000 is deprecated. Each server behaves differently, so server specific properties are recommended instead.

SpringBoot embeds Tomcat by default, if you haven't reconfigured it with Jetty or something else. Use server specific application properties like server.tomcat.connection-timeout or server.jetty.idle-timeout.

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

facebook: permanent Page Access Token?

I created a small NodeJS script based on donut's answer. Store the following in a file called get-facebook-access-token.js:

const fetch = require('node-fetch');
const open = require('open');

const api_version = 'v9.0';
const app_id = '';
const app_secret = '';
const short_lived_token = '';
const page_name = '';

const getPermanentAccessToken = async () => {
  try {
    const long_lived_access_token = await getLongLivedAccessToken();
    const account_id = await getAccountId(long_lived_access_token);
    const permanent_page_access_token = await getPermanentPageAccessToken(
      long_lived_access_token,
      account_id
    );
    checkExpiration(permanent_page_access_token);
  } catch (reason) {
    console.error(reason);
  }
};

const getLongLivedAccessToken = async () => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${short_lived_token}`
  );
  const body = await response.json();
  return body.access_token;
};

const getAccountId = async (long_lived_access_token) => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/me?access_token=${long_lived_access_token}`
  );
  const body = await response.json();
  return body.id;
};

const getPermanentPageAccessToken = async (
  long_lived_access_token,
  account_id
) => {
  const response = await fetch(
    `https://graph.facebook.com/${api_version}/${account_id}/accounts?access_token=${long_lived_access_token}`
  );
  const body = await response.json();
  const page_item = body.data.find(item => item.name === page_name);  
  return page_item.access_token;
};

const checkExpiration = (access_token) => {
  open(`https://developers.facebook.com/tools/debug/accesstoken/?access_token=${access_token}&version=${api_version}`);
}

getPermanentAccessToken();

Fill in the constants and then run:

npm install node-fetch
npm install open
node get-facebook-access-token.js

After running the script a page is opened in the browser that shows the token and how long it is valid.

Determining image file size + dimensions via Javascript?

How about this:

var imageUrl = 'https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg';
var blob = null;
var xhr = new XMLHttpRequest(); 
xhr.open('GET', imageUrl, true); 
xhr.responseType = 'blob';
xhr.onload = function() 
{
    blob = xhr.response;
    console.log(blob, blob.size);
}
xhr.send();

http://qnimate.com/javascript-create-file-object-from-url/

due to Same Origin Policy, only work under same origin

Regex to extract substring, returning 2 results for some reason

I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

NuGet behind a proxy

Maybe this helps someone else. For me the solution was to open NuGet settings on Visual Studio (2015/2017) and add a new feed URL: http://www.nuget.org/api/v2/.

I didn't have to change any proxy related settings.

Android - Get value from HashMap

Note: If you know Key, use this code

String value=meMap.get(key);

What does the "+=" operator do in Java?

^ = (bitwise XOR)

Description

Binary XOR Operator copies the bit if it is set in one operand but not both.

example

(A ^ B) will give 49 which is 0011 0001

How to printf "unsigned long" in C?

%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?

Intro to GPU programming

Take a look at the ATI Stream Computing SDK. It is based on BrookGPU developed at Stanford.

In the future all GPU work will be standardized using OpenCL. It's an Apple-sponsored initiative that will be graphics card vendor neutral.

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

Limiting the output of PHP's echo to 200 characters

more flexible way is a function with two parameters:

function lchar($str,$val){return strlen($str)<=$val?$str:substr($str,0,$val).'...';}

usage:

echo lchar($str,200);

Operation Not Permitted when on root - El Capitan (rootless disabled)

If you want to take control of /usr/bin/

You will need to reboot your system:

Right after the boot sound, Hold down Command-R to boot into the Recovery System

Click the Utilities menu and select Terminal

Type csrutil disable and press return

Click the ? menu and select Restart

Once you have committed your changes, make sure to re-enable SIP! It does a lot to protect your system. (Same steps as above except type: csrutil enable)

How do you roll back (reset) a Git repository to a particular commit?

Update:

Because of changes to how tracking branches are created and pushed I no longer recommend renaming branches. This is what I recommend now:

Make a copy of the branch at its current state:

git branch crazyexperiment

(The git branch <name> command will leave you with your current branch still checked out.)

Reset your current branch to your desired commit with git reset:

git reset --hard c2e7af2b51

(Replace c2e7af2b51 with the commit that you want to go back to.)

When you decide that your crazy experiment branch doesn't contain anything useful, you can delete it with:

git branch -D crazyexperiment

It's always nice when you're starting out with history-modifying git commands (reset, rebase) to create backup branches before you run them. Eventually once you're comfortable you won't find it necessary. If you do modify your history in a way that you don't want and haven't created a backup branch, look into git reflog. Git keeps commits around for quite a while even if there are no branches or tags pointing to them.

Original answer:

A slightly less scary way to do this than the git reset --hard method is to create a new branch. Let's assume that you're on the master branch and the commit you want to go back to is c2e7af2b51.

Rename your current master branch:

git branch -m crazyexperiment

Check out your good commit:

git checkout c2e7af2b51

Make your new master branch here:

git checkout -b master

Now you still have your crazy experiment around if you want to look at it later, but your master branch is back at your last known good point, ready to be added to. If you really want to throw away your experiment, you can use:

git branch -D crazyexperiment

How to remove unused imports in Intellij IDEA on commit?

In Mac IntelliJ IDEA, the command is Cmd + Option + O

For some older versions it is apparently Ctrl + Option + O.

(Letter O not Zero 0) on the latest version 2019.x

How can Perl's print add a newline by default?

The way you're writing your print statement is unnecessarily verbose. There's no need to separate the newline into its own string. This is sufficient.

print "hello.\n";

This realization will probably make your coding easier in general.

In addition to using use feature "say" or use 5.10.0 or use Modern::Perl to get the built in say feature, I'm going to pimp perl5i which turns on a lot of sensible missing Perl 5 features by default.

'node' is not recognized as an internal or external command

Try adding C:\Program Files\Nodejs to your PATH environment variable. The PATH environment variable allows run executables or access files within the folders specified (separated by semicolons).

On the command prompt, the command would be set PATH=%PATH%;C:\Program Files\Nodejs.

Converting an int or String to a char array on Arduino

You can convert it to char* if you don't need a modifiable string by using:

(char*) yourString.c_str();

This would be very useful when you want to publish a String variable via MQTT in arduino.

Make a nav bar stick

Just use z-index CSS property as described in the highest liked answer and the nav bar will stick to the top.

Example:

<div class="navigation">
 <nav>
   <ul>
    <li>Home</li>
    <li>Contact</li>
   </ul>
 </nav>

.navigation {
   /* fixed keyword is fine too */
   position: sticky;
   top: 0;
   z-index: 100;
   /* z-index works pretty much like a layer:
   the higher the z-index value, the greater
   it will allow the navigation tag to stay on top
   of other tags */
}

Getting last month's date in php

It's simple to get last month date

echo date("Y-n-j", strtotime("first day of previous month"));
echo date("Y-n-j", strtotime("last day of previous month"));

at November 3 returns

2014-10-1
2014-10-31

CSS: Fix row height

_x000D_
_x000D_
    _x000D_
    table tbody_x000D_
    {_x000D_
        border:1px solid red;_x000D_
    }_x000D_
    table td_x000D_
    {_x000D_
        background:yellow;_x000D_
        _x000D_
        border-bottom:1px solid green;_x000D_
        _x000D_
        _x000D_
    }_x000D_
    .tr0{_x000D_
        line-height:0;_x000D_
     }_x000D_
     .tr0 td{_x000D_
        background:red;_x000D_
     }
_x000D_
<table>_x000D_
<tbody>_x000D_
    <tr><td>test</td></tr>_x000D_
    <tr><td>test</td></tr>    _x000D_
    <tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_