Programs & Examples On #Graph

Graph refers to a graphic (such as a chart or diagram) which displays the relationship between two or more variables. For the discrete mathematics structure consisting of vertices and edges, use the graph-theory tag.

Python Graph Library

I second zweiterlinde's suggestion to use python-graph. I've used it as the basis of a graph-based research project that I'm working on. The library is well written, stable, and has a good interface. The authors are also quick to respond to inquiries and reports.

Charts for Android

SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.

SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.

Some useful links can be found below:

enter image description here

Disclosure: I am the tech lead on the SciChart project!

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

How to plot multiple functions on the same figure, in Matplotlib?

Perhaps a more pythonic way of doing so.

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)

nx.draw(g,with_labels=True)
plt.draw()
plt.show()

This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.

Note: It's just a simple representation. Weighted Edges could be added like

g.add_edges_from([(1,2),(2,5)], weight=2)

and hence plotted again.

Difference between hamiltonian path and euler path

Euler path is a graph using every edge(NOTE) of the graph exactly once. Euler circuit is a euler path that returns to it starting point after covering all edges.

While hamilton path is a graph that covers all vertex(NOTE) exactly once. When this path returns to its starting point than this path is called hamilton circuit.

How to trace the path in a Breadth-First Search?

I liked qiao's first answer very much! The only thing missing here is to mark the vertexes as visited.

Why we need to do it?
Lets imagine that there is another node number 13 connected from node 11. Now our goal is to find node 13.
After a little bit of a run the queue will look like this:

[[1, 2, 6], [1, 3, 10], [1, 4, 7], [1, 4, 8], [1, 2, 5, 9], [1, 2, 5, 10]]

Note that there are TWO paths with node number 10 at the end.
Which means that the paths from node number 10 will be checked twice. In this case it doesn't look so bad because node number 10 doesn't have any children.. But it could be really bad (even here we will check that node twice for no reason..)
Node number 13 isn't in those paths so the program won't return before reaching to the second path with node number 10 at the end..And we will recheck it..

All we are missing is a set to mark the visited nodes and not to check them again..
This is qiao's code after the modification:

graph = {
    1: [2, 3, 4],
    2: [5, 6],
    3: [10],
    4: [7, 8],
    5: [9, 10],
    7: [11, 12],
    11: [13]
}


def bfs(graph_to_search, start, end):
    queue = [[start]]
    visited = set()

    while queue:
        # Gets the first path in the queue
        path = queue.pop(0)

        # Gets the last node in the path
        vertex = path[-1]

        # Checks if we got to the end
        if vertex == end:
            return path
        # We check if the current node is already in the visited nodes set in order not to recheck it
        elif vertex not in visited:
            # enumerate all adjacent nodes, construct a new path and push it into the queue
            for current_neighbour in graph_to_search.get(vertex, []):
                new_path = list(path)
                new_path.append(current_neighbour)
                queue.append(new_path)

            # Mark the vertex as visited
            visited.add(vertex)


print bfs(graph, 1, 13)

The output of the program will be:

[1, 4, 7, 11, 13]

Without the unneccecery rechecks..

How do I calculate a trendline for a graph?

Here's a working example in golang. I searched around and found this page and converted this over to what I needed. Hope someone else can find it useful.

// https://classroom.synonym.com/calculate-trendline-2709.html
package main

import (
    "fmt"
    "math"
)

func main() {

    graph := [][]float64{
        {1, 3},
        {2, 5},
        {3, 6.5},
    }

    n := len(graph)

    // get the slope
    var a float64
    var b float64
    var bx float64
    var by float64
    var c float64
    var d float64
    var slope float64

    for _, point := range graph {

        a += point[0] * point[1]
        bx += point[0]
        by += point[1]
        c += math.Pow(point[0], 2)
        d += point[0]

    }

    a *= float64(n)           // 97.5
    b = bx * by               // 87
    c *= float64(n)           // 42
    d = math.Pow(d, 2)        // 36
    slope = (a - b) / (c - d) // 1.75

    // calculating the y-intercept (b) of the Trendline
    var e float64
    var f float64

    e = by                            // 14.5
    f = slope * bx                    // 10.5
    intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3

    // output
    fmt.Println(slope)
    fmt.Println(intercept)

}

Python equivalent to 'hold on' in Matlab

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

Set Colorbar Range in matplotlib

Using figure environment and .set_clim()

Could be easier and safer this alternative if you have multiple plots:

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )
data1 = np.clip(data,0,6)
data2 = np.clip(data,-6,0)
vmin = np.min(np.array([data,data1,data2]))
vmax = np.max(np.array([data,data1,data2]))

fig = plt.figure()
ax = fig.add_subplot(131)
mesh = ax.pcolormesh(data, cmap = cm)
mesh.set_clim(vmin,vmax)
ax1 = fig.add_subplot(132)
mesh1 = ax1.pcolormesh(data1, cmap = cm)
mesh1.set_clim(vmin,vmax)
ax2 = fig.add_subplot(133)
mesh2 = ax2.pcolormesh(data2, cmap = cm)
mesh2.set_clim(vmin,vmax)
# Visualizing colorbar part -start
fig.colorbar(mesh,ax=ax)
fig.colorbar(mesh1,ax=ax1)
fig.colorbar(mesh2,ax=ax2)
fig.tight_layout()
# Visualizing colorbar part -end

plt.show()

enter image description here

A single colorbar

The best alternative is then to use a single color bar for the entire plot. There are different ways to do that, this tutorial is very useful for understanding the best option. I prefer this solution that you can simply copy and paste instead of the previous visualizing colorbar part of the code.

fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8,
                    wspace=0.4, hspace=0.1)
cb_ax = fig.add_axes([0.83, 0.1, 0.02, 0.8])
cbar = fig.colorbar(mesh, cax=cb_ax)

enter image description here

P.S.

I would suggest using pcolormesh instead of pcolor because it is faster (more infos here ).

Cycles in family tree software

I hate commenting on such a screwed up situation, but the easiest way to not rejigger all of your invariants is to create a phantom vertex in your graph that acts as a proxy back to the incestuous dad.

What is better, adjacency lists or adjacency matrices for graph problems in C++?

If you are looking at graph analysis in C++ probably the first place to start would be the boost graph library, which implements a number of algorithms including BFS.

EDIT

This previous question on SO will probably help:

how-to-create-a-c-boost-undirected-graph-and-traverse-it-in-depth-first-search

Generating statistics from Git repository

Beside GitStats (git history statistics generator) mentioned by xyld, written in Python and requiring Gnuplot for graphs, there is also

How do you change the size of figures drawn with matplotlib?

USING plt.rcParams

There is also this workaround in case you want to change the size without using the figure environment. So in case you are using plt.plot() for example, you can set a tuple with width and height.

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)

This is very useful when you plot inline (e.g. with IPython Notebook). As @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.

Conversion to cm

The figsize tuple accepts inches so if you want to set it in centimetres you have to divide them by 2.54 have a look to this question.

How to show x and y axes in a MATLAB graph?

The poor man's solution is to simply graph the lines x=0 and y=0. You can adjust the thickness and color of the lines to differentiate them from the graph.

Export a graph to .eps file with R

If you are using ggplot2 to generate a figure, then a ggsave(file="name.eps") will also work.

matplotlib savefig() plots different from show()

savefig specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the dpi kwarg to savefig). It doesn't inheret it from the DPI of the original figure.

The DPI affects the relative size of the text and width of the stroke on lines, etc. If you want things to look identical, then pass fig.dpi to fig.savefig.

E.g.

import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', dpi=fig.dpi)

Matplotlib/pyplot: How to enforce axis range?

Try putting the call to axis after all plotting commands.

What is the difference between dynamic programming and greedy approach?

With the reference of Biswajit Roy: Dynamic Programming firstly plans then Go. and Greedy algorithm uses greedy choice, it firstly Go then continuously Plans.

Good Java graph algorithm library?

Summary:

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Cycles in an Undirected Graph

I believe that the assumption that the graph is connected can be handful. thus, you can use the proof shown above, that the running time is O(|V|). if not, then |E|>|V|. reminder: the running time of DFS is O(|V|+|E|).

What is the maximum number of edges in a directed graph with n nodes?

In a directed graph having N vertices, each vertex can connect to N-1 other vertices in the graph(Assuming, no self loop). Hence, the total number of edges can be are N(N-1).

Python equivalent of D3.js

One recipe that I have used (described here: Co-Director Network Data Files in GEXF and JSON from OpenCorporates Data via Scraperwiki and networkx ) runs as follows:

  • generate a network representation using networkx
  • export the network as a JSON file
  • import that JSON into to d3.js. (networkx can export both the tree and graph/network representations that d3.js can import).

The networkx JSON exporter takes the form:

from networkx.readwrite import json_graph
import json
print json.dumps(json_graph.node_link_data(G))

Alternatively you can export the network as a GEXF XML file and then import this representation into the sigma.js Javascript visualisation library.

from xml.etree.cElementTree import tostring
writer=gf.GEXFWriter(encoding='utf-8',prettyprint=True,version='1.1draft')
writer.add_graph(G)
print tostring(writer.xml)

Command-line Unix ASCII-based charting / plotting tool

Check the package plotext which allows to plot data directly on terminal using python3. It is very intuitive as its use is very similar to the matplotlib package.

Here is a basic example:

enter image description here

You can install it with the following command:

sudo -H pip install plotext

As for matplotlib, the main functions are scatter (for single points), plot (for points joined by lines) and show (to actually print the plot on terminal). It is easy to specify the plot dimensions, the point and line styles and whatever to show the axes, number ticks and final equations, which are used to convert the plotted coordinates to the original real values.

Here is the code to produce the plot shown above:

import plotext.plot as plx
import numpy as np

l=3000
x=np.arange(0, l)
y=np.sin(4*np.pi/l*np.array(x))*np.exp(-0.5*np.pi/l*x)

plx.scatter(x, y, rows = 17, cols = 70)
plx.show(clear = 0)

The option clear=True inside show is used to clear the terminal before plotting: this is useful, for example, when plotting a continuous flow of data. An example of plotting a continuous data flow is shown here: enter image description here

The package description provides more information how to customize the plot. The package has been tested on Ubuntu 16 where it works perfectly. Possible future developments (upon request) could involve extension to python2 and to other graphical interfaces (e.g. jupiter). Please let me know if you have any issues using it. Thanks.

I hope this answers your problem.

Generating a PNG with matplotlib when DISPLAY is undefined

To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:

import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if os.name == 'posix' and "DISPLAY" not in os.environ:
    matplotlib.use('Agg')

# now import other things from matplotlib
import matplotlib.pyplot as plt

Credit: https://stackoverflow.com/a/45756291/207661

Plotting time in Python with Matplotlib

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)

Java: how to represent graphs?

If you need weighted edges and multigraphs, you might want to add another class Edge.

I would also recommend using generics to allow specifying which sub-class of Vertex and Edge are currently used. For example:

public class Graph<V extends Vertex> {
List<V> vertices;
...
}

When it comes to implementing graph algorithms, you could also define interfaces for your graph classes on which the algorithms can operate, so that you can play around with different implementations of the actual graph representation. For example, simple graphs that are well-connected might be better implemented by an adjacency matrix, sparser graphs might be represented by adjacency lists - it all depends...

BTW Building such structures efficiently can be quite challenging, so maybe you could give us some more details on what kind of job you would want to use them for? For more complex tasks I would suggest you have a look at the various Java graph libraries, to get some inspiration.

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

Plotting two variables as lines using ggplot2 on the same graph

You need the data to be in "tall" format instead of "wide" for ggplot2. "wide" means having an observation per row with each variable as a different column (like you have now). You need to convert it to a "tall" format where you have a column that tells you the name of the variable and another column that tells you the value of the variable. The process of passing from wide to tall is usually called "melting". You can use tidyr::gather to melt your data frame:

library(ggplot2)
library(tidyr)

test_data <-
  data.frame(
    var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
    var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
    date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
  )
test_data %>%
    gather(key,value, var0, var1) %>%
    ggplot(aes(x=date, y=value, colour=key)) +
    geom_line()

multiple series ggplot2

Just to be clear the data that ggplot is consuming after piping it via gather looks like this:

date        key     value
2002-01-01  var0    100.00000
2002-02-01  var0    115.16388 
...
2007-11-01  var1    114.86302
2007-12-01  var1    119.30996

Graph implementation C++

I prefer using an adjacency list of Indices ( not pointers )

typedef std::vector< Vertex > Vertices;
typedef std::set <int> Neighbours;


struct Vertex {
private:
   int data;
public:
   Neighbours neighbours;

   Vertex( int d ): data(d) {}
   Vertex( ): data(-1) {}

   bool operator<( const Vertex& ref ) const {
      return ( ref.data < data );
   }
   bool operator==( const Vertex& ref ) const {
      return ( ref.data == data );
   }
};

class Graph
{
private :
   Vertices vertices;
}

void Graph::addEdgeIndices ( int index1, int index2 ) {
  vertices[ index1 ].neighbours.insert( index2 );
}


Vertices::iterator Graph::findVertexIndex( int val, bool& res )
{
   std::vector<Vertex>::iterator it;
   Vertex v(val);
   it = std::find( vertices.begin(), vertices.end(), v );
   if (it != vertices.end()){
        res = true;
       return it;
   } else {
       res = false;
       return vertices.end();
   }
}

void Graph::addEdge ( int n1, int n2 ) {

   bool foundNet1 = false, foundNet2 = false;
   Vertices::iterator vit1 = findVertexIndex( n1, foundNet1 );
   int node1Index = -1, node2Index = -1;
   if ( !foundNet1 ) {
      Vertex v1( n1 );
      vertices.push_back( v1 );
      node1Index = vertices.size() - 1;
   } else {
      node1Index = vit1 - vertices.begin();
   }
   Vertices::iterator vit2 = findVertexIndex( n2, foundNet2);
   if ( !foundNet2 ) {
      Vertex v2( n2 );
      vertices.push_back( v2 );
      node2Index = vertices.size() - 1;
   } else {
      node2Index = vit2 - vertices.begin();
   }

   assert( ( node1Index > -1 ) && ( node1Index <  vertices.size()));
   assert( ( node2Index > -1 ) && ( node2Index <  vertices.size()));

   addEdgeIndices( node1Index, node2Index );
}

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

AntiGrain Geometry (AGG). http://www.antigrain.com/. Its an opensource 2D vector graphics library. Its a standalone library with no additional dependencies. Has good documentation. Python plotting library matplotlib uses AGG as one of backends.

Rotating x axis labels in R for barplot

Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:

par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels

#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"

end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)

barplot(mtcars$qsec, col = "grey50", 
        main = "",
        ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
        xlab = "",
        space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25, 
     srt = 60, adj = 1, xpd = TRUE,
     labels = paste(rownames(mtcars)), cex = 0.65)

enter image description here

Validate a username and password against Active Directory?

If you work on .NET 3.5 or newer, you can use the System.DirectoryServices.AccountManagement namespace and easily verify your credentials:

// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}

It's simple, it's reliable, it's 100% C# managed code on your end - what more can you ask for? :-)

Read all about it here:

Update:

As outlined in this other SO question (and its answers), there is an issue with this call possibly returning True for old passwords of a user. Just be aware of this behavior and don't be too surprised if this happens :-) (thanks to @MikeGledhill for pointing this out!)

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

Rather than creating empty directories in source to exclude, you can supply the full destination path to the /XD switch to have the destination directories untouched

robocopy "%SOURCE_PATH%" "%DEST_PATH%" /MIR /XD "%DEST_PATH%"\hq04s2dba301

How to get All input of POST in Laravel

It should be at least this:

public function login(Request $loginCredentials){
     $data = $loginCredentials->all();
     return $data['username'];
}

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

Modifying a subset of rows in a pandas dataframe

Use .loc for label based indexing:

df.loc[df.A==0, 'B'] = np.nan

The df.A==0 expression creates a boolean series that indexes the rows, 'B' selects the column. You can also use this to transform a subset of a column, e.g.:

df.loc[df.A==0, 'B'] = df.loc[df.A==0, 'B'] / 2

I don't know enough about pandas internals to know exactly why that works, but the basic issue is that sometimes indexing into a DataFrame returns a copy of the result, and sometimes it returns a view on the original object. According to documentation here, this behavior depends on the underlying numpy behavior. I've found that accessing everything in one operation (rather than [one][two]) is more likely to work for setting.

Changing every value in a hash in Ruby

In Ruby 2.1 and higher you can do

{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h

Is there a way to call a stored procedure with Dapper?

I think the answer depends on which features of stored procedures you need to use.

Stored procedures returning a result set can be run using Query; stored procedures which don't return a result set can be run using Execute - in both cases (using EXEC <procname>) as the SQL command (plus input parameters as necessary). See the documentation for more details.

As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT parameters; you could add this, or alternatively construct a more complex Query command which declared TSQL variables, executed the SP collecting OUTPUT parameters into the local variables and finallyreturned them in a result set:

DECLARE @output int

EXEC <some stored proc> @i = @output OUTPUT

SELECT @output AS output1

Reading HTTP headers in a Spring REST controller

I'm going to give you an example of how I read REST headers for my controllers. My controllers only accept application/json as a request type if I have data that needs to be read. I suspect that your problem is that you have an application/octet-stream that Spring doesn't know how to handle.

Normally my controllers look like this:

@Controller
public class FooController {
    @Autowired
    private DataService dataService;

    @RequestMapping(value="/foo/", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Data> getData(@RequestHeader String dataId){
        return ResponseEntity.newInstance(dataService.getData(dataId);
    }

Now there is a lot of code doing stuff in the background here so I will break it down for you.

ResponseEntity is a custom object that every controller returns. It contains a static factory allowing the creation of new instances. My Data Service is a standard service class.

The magic happens behind the scenes, because you are working with JSON, you need to tell Spring to use Jackson to map HttpRequest objects so that it knows what you are dealing with.

You do this by specifying this inside your <mvc:annotation-driven> block of your config

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

ObjectMapper is simply an extension of com.fasterxml.jackson.databind.ObjectMapper and is what Jackson uses to actually map your request from JSON into an object.

I suspect you are getting your exception because you haven't specified a mapper that can read an Octet-Stream into an object, or something that Spring can handle. If you are trying to do a file upload, that is something else entirely.

So my request that gets sent to my controller looks something like this simply has an extra header called dataId.

If you wanted to change that to a request parameter and use @RequestParam String dataId to read the ID out of the request your request would look similar to this:

contactId : {"fooId"} 

This request parameter can be as complex as you like. You can serialize an entire object into JSON, send it as a request parameter and Spring will serialize it (using Jackson) back into a Java Object ready for you to use.

Example In Controller:

@RequestMapping(value = "/penguin Details/", method = RequestMethod.GET)
@ResponseBody
public DataProcessingResponseDTO<Pengin> getPenguinDetailsFromList(
        @RequestParam DataProcessingRequestDTO jsonPenguinRequestDTO)

Request Sent:

jsonPengiunRequestDTO: {
    "draw": 1,
    "columns": [
        {
            "data": {
                "_": "toAddress",
                "header": "toAddress"
            },
            "name": "toAddress",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "fromAddress",
                "header": "fromAddress"
            },
            "name": "fromAddress",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "customerCampaignId",
                "header": "customerCampaignId"
            },
            "name": "customerCampaignId",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "penguinId",
                "header": "penguinId"
            },
            "name": "penguinId",
            "searchable": false,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "validpenguin",
                "header": "validpenguin"
            },
            "name": "validpenguin",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "",
                "header": ""
            },
            "name": "",
            "searchable": false,
            "orderable": false,
            "search": {
                "value": "",
                "regex": false
            }
        }
    ],
    "order": [
        {
            "column": 0,
            "dir": "asc"
        }
    ],
    "start": 0,
    "length": 10,
    "search": {
        "value": "",
        "regex": false
    },
    "objectId": "30"
}

which gets automatically serialized back into an DataProcessingRequestDTO object before being given to the controller ready for me to use.

As you can see, this is quite powerful allowing you to serialize your data from JSON to an object without having to write a single line of code. You can do this for @RequestParam and @RequestBody which allows you to access JSON inside your parameters or request body respectively.

Now that you have a concrete example to go off, you shouldn't have any problems once you change your request type to application/json.

Why does dividing two int not yield the right value when assigned to double?

In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.

One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading

void foo(int);
void foo(double);

void (*p)(double) = &foo; // automatically selects `foo(fouble)`

This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.

Correct path for img on React.js

Place the logo in your public folder under e.g. public/img/logo.png and then refer to the public folder as %PUBLIC_URL%:

<img src="%PUBLIC_URL%/img/logo.png"/>

The use of %PUBLIC_URL% in the above will be replaced with the URL of the public folder during the build. Only files inside the public folder can be referenced from the HTML.

Unlike "/img/logo.png" or "logo.png", "%PUBLIC_URL%/img/logo.png" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running npm run build.

Javascript: how to validate dates in format MM-DD-YYYY?

You can simplify it somewhat by changing the first two lines of the function to this:

var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);

Or, just change the parameter to the RegExp constructor to be

^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$

jQuery ajax request being block because Cross-Origin

I solved this by changing the file path in the browser:

  • Instead of: c/XAMPP/htdocs/myfile.html
  • I wrote: localhost/myfile.html

How to name and retrieve a stash by name in git?

Use a small bash script to look up the number of the stash. Call it "gitapply":

NAME="$1"
if [[ -z "$NAME" ]]; then echo "usage: gitapply [name]"; exit; fi
git stash apply $(git stash list | grep "$NAME" | cut -d: -f1)

Usage:

gitapply foo

...where foo is a substring of the name of the stash you want.

Table overflowing outside of div

You can prevent tables from expanding beyond their parent div by using table-layout:fixed.

The CSS below will make your tables expand to the width of the div surrounding it.

table 
{
    table-layout:fixed;
    width:100%;
}

I found this trick here.

Adding a user on .htpasswd

Exact same thing, just omit the -c option. Apache's docs on it here.

htpasswd /etc/apache2/.htpasswd newuser

Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).

React native text going off my screen, refusing to wrap. What to do?

<View style={{flexDirection:'row'}}> 
   <Text style={{ flex: number }}> You miss fdddddd dddddddd 
     You miss fdd
   </Text>
</View>

{ flex: aNumber } is all you need!

Just set 'flex' to a number that suit for you. And then the text will wrap.

PermissionError: [Errno 13] in python

I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32 instead of the usual directory from which I run my python module

Function or sub to add new row and data to table

I needed this same solution, but if you use the native ListObject.Add() method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:

Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        For col = 1 To lastRow.Columns.Count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design tab of the ribbon, in Excel 2013 at least: enter image description here

Example code for a table with three columns:

Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x

What is the function __construct used for?

Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();

CSS Background Opacity

Just make sure to put width and height for the foreground the same with the background, or try to have top, bottom, left and right properties.

<style>
    .foreground, .background {
        position: absolute;
    }
    .foreground {
        z-index: 1;
    }
    .background {
        background-image: url(your/image/here.jpg);
        opacity: 0.4;
    }
</style>

<div class="foreground"></div>
<div class="background"></div>

Java: Convert String to TimeStamp

This is what I did:

Timestamp timestamp = Timestamp.valueOf(stringValue);

where stringValue can be any format of Date/Time.

How to force uninstallation of windows service

Unfortunately, you need to restart the server. That should remove the "deleted" service.

Disable submit button ONLY after submit

Reading the comments, it seems that these solutions are not consistent across browsers. Decided then to think how I would have done this 10 years ago before the advent of jQuery and event function binding.

So here is my retro hipster solution:

<script type="text/javascript">
var _formConfirm_submitted = false;
</script>
<form name="frmConfirm" onsubmit="if( _formConfirm_submitted == false ){ _formConfirm_submitted = true;return true }else{ alert('your request is being processed!'); return false;  }" action="" method="GET">

<input type="submit" value="submit - but only once!"/>
</form>

The main point of difference is that I am relying on the ability to stop a form submitting through returning false on the submit handler, and I am using a global flag variable - which will make me go straight to hell!

But on the plus side, I cannot imagine any browser compatibility issues - hey, it would probably even work in Netscape!

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

i don't see any for loop to initalize the variables.you can do something like this.

for(i=0;i<50;i++){
 /* Code which is necessary with a simple if statement*/

   }

What is the cleanest way to ssh and run multiple commands in Bash?

This works well for creating scripts, as you do not have to include other files:

#!/bin/bash
ssh <my_user>@<my_host> "bash -s" << EOF
    # here you just type all your commmands, as you can see, i.e.
    touch /tmp/test1;
    touch /tmp/test2;
    touch /tmp/test3;
EOF

# you can use '$(which bash) -s' instead of my "bash -s" as well
# but bash is usually being found in a standard location
# so for easier memorizing it i leave that out
# since i dont fat-finger my $PATH that bad so it cant even find /bin/bash ..

Kubernetes how to make Deployment to update image

I am using Azure DevOps to deploy the containerize applications, I am easily manage to overcome this problem by using the build ID

Everytime its builds and generate the new Build ID, I use this build ID as tag for docker image here is example

imagename:buildID

once your image is build (CI) successfully, in CD pipeline in deployment yml file I have give image name as

imagename:env:buildID

here evn:buildid is the azure devops variable which having value of build ID.

so now every time I have new changes to build(CI) and deploy(CD).

please comment if you need build definition for CI/CD.

How to redirect to Index from another controller?

Tag helpers:

<a asp-controller="OtherController" asp-action="Index" class="btn btn-primary"> Back to Other Controller View </a>

In the controller.cs have a method:

public async Task<IActionResult> Index()
{
    ViewBag.Title = "Titles";
    return View(await Your_Model or Service method);
}

StringBuilder vs String concatenation in toString() in Java

I also had clash with my boss on the fact whether to use append or +.As they are using Append(I still cant figure out as they say every time a new object is created). So I thought to do some R&D.Although I love Michael Borgwardt explaination but just wanted to show an explanation if somebody will really need to know in future.

/**
 *
 * @author Perilbrain
 */
public class Appc {
    public Appc() {
        String x = "no name";
        x += "I have Added a name" + "We May need few more names" + Appc.this;
        x.concat(x);
        // x+=x.toString(); --It creates new StringBuilder object before concatenation so avoid if possible
        //System.out.println(x);
    }

    public void Sb() {
        StringBuilder sbb = new StringBuilder("no name");
        sbb.append("I have Added a name");
        sbb.append("We May need few more names");
        sbb.append(Appc.this);
        sbb.append(sbb.toString());
        // System.out.println(sbb.toString());
    }
}

and disassembly of above class comes out as

 .method public <init>()V //public Appc()
  .limit stack 2
  .limit locals 2
met001_begin:                                  ; DATA XREF: met001_slot000i
  .line 12
    aload_0 ; met001_slot000
    invokespecial java/lang/Object.<init>()V
  .line 13
    ldc "no name"
    astore_1 ; met001_slot001
  .line 14

met001_7:                                      ; DATA XREF: met001_slot001i
    new java/lang/StringBuilder //1st object of SB
    dup
    invokespecial java/lang/StringBuilder.<init>()V
    aload_1 ; met001_slot001
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    ldc "I have Added a nameWe May need few more names"
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    aload_0 ; met001_slot000
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/Object;)Ljava/lan\
g/StringBuilder;
    invokevirtual java/lang/StringBuilder.toString()Ljava/lang/String;
    astore_1 ; met001_slot001
  .line 15
    aload_1 ; met001_slot001
    aload_1 ; met001_slot001
    invokevirtual java/lang/String.concat(Ljava/lang/String;)Ljava/lang/Strin\
g;
    pop
  .line 18
    return //no more SB created
met001_end:                                    ; DATA XREF: met001_slot000i ...

; ===========================================================================

;met001_slot000                                ; DATA XREF: <init>r ...
    .var 0 is this LAppc; from met001_begin to met001_end
;met001_slot001                                ; DATA XREF: <init>+6w ...
    .var 1 is x Ljava/lang/String; from met001_7 to met001_end
  .end method
;44-1=44
; ---------------------------------------------------------------------------


; Segment type: Pure code
  .method public Sb()V //public void Sb
  .limit stack 3
  .limit locals 2
met002_begin:                                  ; DATA XREF: met002_slot000i
  .line 21
    new java/lang/StringBuilder
    dup
    ldc "no name"
    invokespecial java/lang/StringBuilder.<init>(Ljava/lang/String;)V
    astore_1 ; met002_slot001
  .line 22

met002_10:                                     ; DATA XREF: met002_slot001i
    aload_1 ; met002_slot001
    ldc "I have Added a name"
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    pop
  .line 23
    aload_1 ; met002_slot001
    ldc "We May need few more names"
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    pop
  .line 24
    aload_1 ; met002_slot001
    aload_0 ; met002_slot000
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/Object;)Ljava/lan\
g/StringBuilder;
    pop
  .line 25
    aload_1 ; met002_slot001
    aload_1 ; met002_slot001
    invokevirtual java/lang/StringBuilder.toString()Ljava/lang/String;
    invokevirtual java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lan\
g/StringBuilder;
    pop
  .line 28
    return
met002_end:                                    ; DATA XREF: met002_slot000i ...


;met002_slot000                                ; DATA XREF: Sb+25r
    .var 0 is this LAppc; from met002_begin to met002_end
;met002_slot001                                ; DATA XREF: Sb+9w ...
    .var 1 is sbb Ljava/lang/StringBuilder; from met002_10 to met002_end
  .end method
;96-49=48
; ---------------------------------------------------------------------------

From the above two codes you can see Michael is right.In each case only one SB object is created.

UL has margin on the left

I don't see any margin or margin-left declarations for #footer-wrap li.

This ought to do the trick:

#footer-wrap ul,
#footer-wrap li {
    margin-left: 0;
    list-style-type: none;
}

How to set up Automapper in ASP.NET Core

services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)

After configuring as below

   var config = new AutoMapper.MapperConfiguration(cfg =>
   {                 
       cfg.CreateMap<ClientCustomer, Models.Customer>();
   });

initialize the mapper IMapper mapper = config.CreateMapper();

and add the mapper object to services as a singleton services.AddSingleton(mapper);

this way I am able to add a DI to controller

  private IMapper autoMapper = null;

  public VerifyController(IMapper mapper)
  {              
   autoMapper = mapper;  
  }

and I have used as below in my action methods

  ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);

How to return JSon object

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}

Android: How to add R.raw to project?

The R class is written when you build the project in gradle. You should add the raw folder, then build the project. After that, the R class will be able to identify R.raw.*.

How to make html <select> element look like "disabled", but pass values?

You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.

$('#myForm').submit(function() {
    $('select').removeAttr('disabled');
});

Note that if you rely on this method, you'll want to disable it programmatically as well, because if JS is disabled or not supported, you'll be stuck with the disabled select.

$(document).ready(function() {
    $('select').attr('disabled', 'disabled');
});

Using ORDER BY and GROUP BY together

Here is the simplest solution

select m_id,v_id,max(timestamp) from table group by m_id;

Group by m_id but get max of timestamp for each m_id.

How to use makefiles in Visual Studio?

The Microsoft Program Maintenance Utility (NMAKE.EXE) is a tool that builds projects based on commands contained in a description file.

NMAKE Reference

How can I find a file/directory that could be anywhere on linux command line?

If it is a command file you are looking for, the fastest and most accurate way is with

which "commandname"

That will show you the actual file being used for the command, even if you have many files with the same name on the system.

How to center horizontal table-cell

Short snippet for future visitors - how to center horizontal table-cell (+ vertically)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  text-align: center; /* the key */_x000D_
  background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: inline-block; /* important !! */_x000D_
  width: 100px;_x000D_
  background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
  <div class="cell">_x000D_
    <div class="content" id="a">_x000D_
      <p>Content</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to prevent caching of my Javascript file?

You can append a queryString to your src and change it only when you will release an updated version:

<script src="test.js?v=1"></script>

In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

How to force IE10 to render page in IE9 document mode

there are many ways can do this:

add X-UA-Compatible tag to head http response header

using IE tools F12

change windows Registry

Structs data type in php?

I recommend 2 things. First is associative array.

$person = Array();
$person['name'] = "Joe";
$person['age'] = 22;

Second is classes.

Detailed documentation here: http://php.net/manual/en/language.oop5.php

Why std::cout instead of simply cout?

Everything in the Standard Template/Iostream Library resides in namespace std. You've probably used:

using namespace std;

In your classes, and that's why it worked.

How can I simulate an anchor click via jquery?

What worked for me was:

$('a.mylink')[0].click()

How to open my files in data_folder with pandas using relative path?

With python or pandas when you use read_csv or pd.read_csv, both of them look into current working directory, by default where the python process have started. So you need to use os module to chdir() and take it from there.

import pandas as pd 
import os
print(os.getcwd())
os.chdir("D:/01Coding/Python/data_sets/myowndata")
print(os.getcwd())
df = pd.read_csv('data.csv',nrows=10)
print(df.head())

How do I pass command-line arguments to a WinForms application?

This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.

Add a reference to Microsoft.VisualBasic

Create a class called WindowsFormsApplication

public class WindowsFormsApplication : WindowsFormsApplicationBase
{

    /// <summary>
    /// Runs the specified mainForm in this application context.
    /// </summary>
    /// <param name="mainForm">Form that is run.</param>
    public virtual void Run(Form mainForm)
    {
        // set up the main form.
        this.MainForm = mainForm;

        // Example code
        ((Form1)mainForm).FileName = this.CommandLineArgs[0];

        // then, run the the main form.
        this.Run(this.CommandLineArgs);
    }

    /// <summary>
    /// Runs this.MainForm in this application context. Converts the command
    /// line arguments correctly for the base this.Run method.
    /// </summary>
    /// <param name="commandLineArgs">Command line collection.</param>
    private void Run(ReadOnlyCollection<string> commandLineArgs)
    {
        // convert the Collection<string> to string[], so that it can be used
        // in the Run method.
        ArrayList list = new ArrayList(commandLineArgs);
        string[] commandLine = (string[])list.ToArray(typeof(string));
        this.Run(commandLine);
    }

}

Modify your Main() routine to look like this

static class Program
{

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var application = new WindowsFormsApplication();
        application.Run(new Form1());
    }
}

This method offers some additional usefull features (like SplashScreen support and some usefull events)

public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
public event ShutdownEventHandler Shutdown;
public event StartupEventHandler Startup;
public event StartupNextInstanceEventHandler StartupNextInstance;
public event UnhandledExceptionEventHandler UnhandledException;

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

MassAssignmentException in Laravel

I am using Laravel 4.2.

the error you are seeing

[Illuminate\Database\Eloquent\MassAssignmentException]
username

indeed is because the database is protected from filling en masse, which is what you are doing when you are executing a seeder. However, in my opinion, it's not necessary (and might be insecure) to declare which fields should be fillable in your model if you only need to execute a seeder.

In your seeding folder you have the DatabaseSeeder class:

class DatabaseSeeder extends Seeder {

    /**
    * Run the database seeds.
    *
    * @return void
    */

    public function run()
    {
        Eloquent::unguard();

        //$this->call('UserTableSeeder');
    }
}

This class acts as a facade, listing all the seeders that need to be executed. If you call the UsersTableSeeder seeder manually through artisan, like you did with the php artisan db:seed --class="UsersTableSeeder" command, you bypass this DatabaseSeeder class.

In this DatabaseSeeder class the command Eloquent::unguard(); allows temporary mass assignment on all tables, which is exactly what you need when you are seeding a database. This unguard method is only executed when you run the php aristan db:seed command, hence it being temporary as opposed to making the fields fillable in your model (as stated in the accepted and other answers).

All you need to do is add the $this->call('UsersTableSeeder'); to the run method in the DatabaseSeeder class and run php aristan db:seed in your CLI which by default will execute DatabaseSeeder.

Also note that you are using a plural classname Users, while Laraval uses the the singular form User. If you decide to change your class to the conventional singular form, you can simply uncomment the //$this->call('UserTableSeeder'); which has already been assigned but commented out by default in the DatabaseSeeder class.

How do I use the lines of a file as arguments of a command?

If all you need to do is to turn file arguments.txt with contents

arg1
arg2
argN

into my_command arg1 arg2 argN then you can simply use xargs:

xargs -a arguments.txt my_command

You can put additional static arguments in the xargs call, like xargs -a arguments.txt my_command staticArg which will call my_command staticArg arg1 arg2 argN

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

Fast way to concatenate strings in nodeJS/JavaScript

You asked about performance. See this perf test comparing 'concat', '+' and 'join' - in short the + operator wins by far.

Check if value exists in the array (AngularJS)

You could use indexOf function.

if(list.indexOf(createItem.artNr) !== -1) {
  $scope.message = 'artNr already exists!';
}

More about indexOf:

join list of lists in python

For one-level flatten, if you care about speed, this is faster than any of the previous answers under all conditions I tried. (That is, if you need the result as a list. If you only need to iterate through it on the fly then the chain example is probably better.) It works by pre-allocating a list of the final size and copying the parts in by slice (which is a lower-level block copy than any of the iterator methods):

def join(a):
    """Joins a sequence of sequences into a single sequence.  (One-level flattening.)
    E.g., join([(1,2,3), [4, 5], [6, (7, 8, 9), 10]]) = [1,2,3,4,5,6,(7,8,9),10]
    This is very efficient, especially when the subsequences are long.
    """
    n = sum([len(b) for b in a])
    l = [None]*n
    i = 0
    for b in a:
        j = i+len(b)
        l[i:j] = b
        i = j
    return l

Sorted times list with comments:

[(0.5391559600830078, 'flatten4b'), # join() above. 
(0.5400412082672119, 'flatten4c'), # Same, with sum(len(b) for b in a) 
(0.5419249534606934, 'flatten4a'), # Similar, using zip() 
(0.7351131439208984, 'flatten1b'), # list(itertools.chain.from_iterable(a)) 
(0.7472689151763916, 'flatten1'), # list(itertools.chain(*a)) 
(1.5468521118164062, 'flatten3'), # [i for j in a for i in j] 
(26.696547985076904, 'flatten2')] # sum(a, [])

Jquery select this + class

Well using find is the best option here

just simply use like this

$(".class").click(function(){
        $("this").find('.subclass').css("visibility","visible");
})

and if there are many classes with the same name class its always better to give the class name of parent class like this

$(".parent .class").click(function(){
            $("this").find('.subclass').css("visibility","visible");
    })

How can I Convert HTML to Text in C#?

This is another solution to convert HTML to Text or RTF in C#:

    SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
    h.OutputFormat = HtmlToRtf.eOutputFormat.TextUnicode;
    string text = h.ConvertString(htmlString);

This library is not free, this is commercial product and it is my own product.

Optional Parameters in Go?

You can pass arbitrary named parameters with a map. You will have to assert types with "aType = map[key].(*foo.type)" if the parameters have non-uniform types.

type varArgs map[string]interface{}

func myFunc(args varArgs) {

    arg1 := "default"
    if val, ok := args["arg1"]; ok {
        arg1 = val.(string)
    }

    arg2 := 123
    if val, ok := args["arg2"]; ok {
        arg2 = val.(int)
    }

    fmt.Println(arg1, arg2)
}

func Test_test() {
    myFunc(varArgs{"arg1": "value", "arg2": 1234})
}

How to replace substrings in windows batch file

SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%

EDIT

Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.

Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:

@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
  SET "line=%%L"
  SETLOCAL ENABLEDELAYEDEXPANSION
  ECHO !line:bath=hello!
  ENDLOCAL
)
ENDLOCAL

You can add a redirection to a file:

  ECHO !line:bath=hello!>>file2.txt

Or you can apply the redirection to the batch file. It must be a different file.

EDIT 2

Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !, ^ et al. (Thanks, jeb!)

VBA: Selecting range by variables

I recorded a macro with 'Relative References' and this is what I got :

Range("F10").Select
ActiveCell.Offset(0, 3).Range("A1:D11").Select

Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following:

Dim MyRange as String
MyRange = "A1:D11"
Range(MyRange).Select

And it worked :) ie.. just create a string using your variables, make sure to dimension it as a STRING variables and Excel will read right off of it ;)

Following tested and found working :

Sub Macro04()

Dim Copyrange As String

Startrow = 1
Lastrow = 11
Let Copyrange = "A" & Startrow & ":" & "D" & Lastrow
Range(Copyrange).Select
End Sub

npm throws error without sudo

Other answers are suggesting to change ownerships or permissions of system directories to a specific user. I highly disadvise from doing so, this can become very awkward and might mess up the entire system!

Here is a more generic and safer approach that supports multi-user as well.

Create a new group for node-users and add the required users to this group. Then set the ownership of node-dependant files/directories to this group.

# Create new group
sudo groupadd nodegrp 

# Add user to group (logname is a variable and gets replaced by the currently logged in user)
sudo usermod -a -G nodegrp `logname`

# Instant access to group without re-login
newgrp nodegrp

# Check group - nodegrp should be listed as well now
groups

# Change group of node_modules, node, npm to new group 
sudo chgrp -R nodegrp /usr/lib/node_modules/
sudo chgrp nodegrp /usr/bin/node
sudo chgrp nodegrp /usr/bin/npm

# (You may want to change a couple of more files (like grunt etc) in your /usr/bin/ directory.)

Now you can easily install your modules as user

npm install -g generator-angular

Some modules (grunt, bower, yo etc.) will still need to be installed as root. This is because they create symlinks in /user/bin/.

Edit

3 years later I'd recommend to use Node Version Manager. It safes you a lot of time and trouble.

Java 8 lambda get and remove element from list

As others have suggested, this might be a use case for loops and iterables. In my opinion, this is the simplest approach. If you want to modify the list in-place, it cannot be considered "real" functional programming anyway. But you could use Collectors.partitioningBy() in order to get a new list with elements which satisfy your condition, and a new list of those which don't. Of course with this approach, if you have multiple elements satisfying the condition, all of those will be in that list and not only the first.

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

You can use another driver

<dependency>
    <groupId>net.sourceforge.jtds</groupId>
    <artifactId>jtds</artifactId>
    <version>1.3.1</version>
</dependency>

and in xml

<bean id="idNameDb" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
        <property name="url" value="jdbc:jtds:sqlserver://[ip]:1433;DatabaseName=[name]" />
        <property name="username" value="user" />
        <property name="password" value="password" />
</bean>

How to avoid annoying error "declared and not used"

As far as I can tell, these lines in the Go compiler look like the ones to comment out. You should be able to build your own toolchain that ignores these counterproductive warnings.

Remove characters after specific character in string, then remove substring?

To remove everything before a specific char, use below.

string1 = string1.Substring(string1.IndexOf('$') + 1);

What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!

But for a URL, I would use the built in .NET class to take of that.

Using StringWriter for XML Serialization

First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.

Here's an example of serializing an object into an XML column:

public void SerializeToXmlColumn(object obj)
{
    using (var outputStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(outputStream))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj);
        }

        outputStream.Position = 0;
        using (var conn = new SqlConnection(Settings.Default.ConnectionString))
        {
            conn.Open();

            const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
            using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
            {
                using (var reader = XmlReader.Create(outputStream))
                {
                    var xml = new SqlXml(reader);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Data", xml);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

Throwing exceptions from constructors

It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:

class A
{
public:
  A () {
    throw int ();
  }
};

A a;     // Implementation defined behaviour if exception is thrown (15.3/13)

int main ()
{
  try
  {
    // Exception for 'a' not caught here.
  }
  catch (int)
  {
  }
}

Check/Uncheck a checkbox on datagridview

Looking at this MSDN Forum Posting it suggests comparing the Cell's value with Cell.TrueValue.

So going by its example your code should looks something like this:(this is completely untested)

Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.

private void chkItems_CheckedChanged(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
        if (chk.Value  == chk.TrueValue)
        {
            chk.Value = chk.FalseValue;
        }
        else
        {
            chk.Value = chk.TrueValue;
        }
    }
}

This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
        CheckboxColumn.TrueValue = true;
        CheckboxColumn.FalseValue = false;
        CheckboxColumn.Width = 100;
        dataGridView1.Columns.Add(CheckboxColumn);
        dataGridView1.Rows.Add(4);
    }

    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
            if (chk.Value == chk.FalseValue || chk.Value == null)
            {
                chk.Value = chk.TrueValue;
            }
            else
            {
                chk.Value = chk.FalseValue;
            }

        }
        dataGridView1.EndEdit();
    }
}

jQuery how to find an element based on a data-attribute value?

$("ul").find("li[data-slide='" + current + "']");

I hope this may work better

thanks

Can we define min-margin and max-margin, max-padding and min-padding in css?

I think I just ran into a similar issue where I was trying to center a login box (like the gmail login box). When resizing the window, the center box would overflow out of the browser window (top) as soon as the browser window became smaller than the box. Because of this, in a small window, even when scrolling up, the top content was lost.

I was able to fix this by replacing the centering method I used by the "margin: auto" way of centering the box in its container. This prevents the box from overflowing in my case, keeping all content available. (minimum margin seems to be 0).

Good Luck !

edit: margin: auto only works to vertically center something if the parent element has its display property set to "flex".

How can I extract audio from video with ffmpeg?

If the audio wrapped into the avi is not mp3-format to start with, you may need to specify -acodec mp3 as an additional parameter. Or whatever your mp3 codec is (on Linux systems its probably -acodec libmp3lame). You may also get the same effect, platform-agnostic, by instead specifying -f mp3 to "force" the format to mp3, although not all versions of ffmpeg still support that switch. Your Mileage May Vary.

Sum of two input value by jquery

use parseInt

   var total = parseInt(a) + parseInt(b);


    $('#total_price').val(total);

LINQ: Select where object does not contain items from list

I have not tried this, so I am not guarantueeing anything, however

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

How to get the fragment instance from the FragmentActivity?

You can use use findFragmentById in FragmentManager.

Since you are using the Support library (you are extending FragmentActivity) you can use:

getSupportFragmentManager().findFragmentById(R.id.pageview)

If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):

getFragmentManager().findFragmentById(R.id.pageview)

Please consider that using the support library is recommended even on Honeycomb+.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

For the second part of your question, see the array page of the manual, which states (quoting) :

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

And the given example :

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


For the first part, the best way to be sure is to try ;-)

Consider this example of code :

function my_func($a) {
    $a[] = 30;
}

$arr = array(10, 20);
my_func($arr);
var_dump($arr);

It'll give this output :

array
  0 => int 10
  1 => int 20

Which indicates the function has not modified the "outside" array that was passed as a parameter : it's passed as a copy, and not a reference.

If you want it passed by reference, you'll have to modify the function, this way :

function my_func(& $a) {
    $a[] = 30;
}

And the output will become :

array
  0 => int 10
  1 => int 20
  2 => int 30

As, this time, the array has been passed "by reference".


Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)

How to get a list of properties with a given attribute?

There's always LINQ:

t.GetProperties().Where(
    p=>p.GetCustomAttributes(typeof(MyAttribute), true).Length != 0)

How to track untracked content?

This worked out just fine for me:

git update-index --skip-worktree

If it doesn't work with the pathname, try the filename. Let me know if this worked for you too.

Bye!

Last Run Date on a Stored Procedure in SQL Server

I use this:

use YourDB;

SELECT 
    object_name(object_id), 
    last_execution_time, 
    last_elapsed_time, 
    execution_count
FROM   
     sys.dm_exec_procedure_stats ps 
where 
      lower(object_name(object_id)) like 'Appl-Name%'
order by 1

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

How to parse a CSV file using PHP

Just use the function for parsing a CSV file

http://php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
  }
  fclose($handle);
}

How to write a JSON file in C#?

The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.

The following adds basic JSON indentation:

 string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);

Cloning specific branch

You can use the following flags --single-branch && --depth to download the specific branch and to limit the amount of history which will be downloaded.

You will clone the repo from a certain point in time and only for the given branch

git clone -b <branch> --single-branch <url> --depth <number of commits>

--[no-]single-branch


Clone only the history leading to the tip of a single branch, either specified by the --branch option or the primary branch remote’s HEAD points at.

Further fetches into the resulting repository will only update the remote-tracking branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when --single-branch clone was made, no remote-tracking branch is created.


--depth

Create a shallow clone with a history truncated to the specified number of commits

How to create an array containing 1...N

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

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

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

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

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

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

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

How to save a PNG image server-side, from a base64 data string

If you want to randomly rename images, and store both the image path on database as blob and the image itself on folders this solution will help you. Your website users can store as many images as they want while the images will be randomly renamed for security purposes.

Php code

Generate random varchars to use as image name.

function genhash($strlen) {
        $h_len = $len;
        $cstrong = TRUE;
        $sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
        return bin2hex($sslkey);
}
$randName = genhash(3); 
#You can increase or decrease length of the image name (1, 2, 3 or more).

Get image data extension and base_64 part (part after data:image/png;base64,) from image .

$pos  = strpos($base64_img, ';');
$imgExten = explode('/', substr($base64_img, 0, $pos))[1];
$extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];

if(in_array($imgExten, $extens)) {

   $imgNewName = $randName. '.' . $imgExten;
   $filepath = "resources/images/govdoc/".$imgNewName;
   $fileP = fopen($filepath, 'wb');
   $imgCont = explode(',', $base64_img);
   fwrite($fileP, base64_decode($imgCont[1]));
   fclose($fileP);

}

# => $filepath <= This path will be stored as blob type in database.
# base64_decoded images will be written in folder too.

# Please don't forget to up vote if you like my solution. :)

JavaScript private methods

Here is the class which I created to understand what Douglas Crockford's has suggested in his site Private Members in JavaScript

function Employee(id, name) { //Constructor
    //Public member variables
    this.id = id;
    this.name = name;
    //Private member variables
    var fName;
    var lName;
    var that = this;
    //By convention, we create a private variable 'that'. This is used to     
    //make the object available to the private methods. 

    //Private function
    function setFName(pfname) {
        fName = pfname;
        alert('setFName called');
    }
    //Privileged function
    this.setLName = function (plName, pfname) {
        lName = plName;  //Has access to private variables
        setFName(pfname); //Has access to private function
        alert('setLName called ' + this.id); //Has access to member variables
    }
    //Another privileged member has access to both member variables and private variables
    //Note access of this.dataOfBirth created by public member setDateOfBirth
    this.toString = function () {
        return 'toString called ' + this.id + ' ' + this.name + ' ' + fName + ' ' + lName + ' ' + this.dataOfBirth; 
    }
}
//Public function has access to member variable and can create on too but does not have access to private variable
Employee.prototype.setDateOfBirth = function (dob) {
    alert('setDateOfBirth called ' + this.id);
    this.dataOfBirth = dob;   //Creates new public member note this is accessed by toString
    //alert(fName); //Does not have access to private member
}
$(document).ready()
{
    var employee = new Employee(5, 'Shyam'); //Create a new object and initialize it with constructor
    employee.setLName('Bhaskar', 'Ram');  //Call privileged function
    employee.setDateOfBirth('1/1/2000');  //Call public function
    employee.id = 9;                     //Set up member value
    //employee.setFName('Ram');  //can not call Private Privileged method
    alert(employee.toString());  //See the changed object

}

jdk7 32 bit windows version to download

Look for "Windows x86", it's the 32 bit version.

Moment Js UTC to Local Time

Here is what I do using Intl api:

let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney

this will return a time zone name. Pass this parameter to the following function to get the time

let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});

let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});

you can also format the time with moment like this:

moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');

What does "O(1) access time" mean?

The easiest way to differentiate O(1) and O(n) is comparing array and list.

For array, if you have the right index value, you can access the data instantly. (If you don't know the index and have to loop through the array, then it won't be O(1) anymore)

For list, you always need to loop through it whether you know the index or not.

How do I fix MSB3073 error in my post-build event?

I've found the issue happens when you have multiple projects building in parallel and one or more of the projects are attempting to copy the same files, creating race conditions that will result in occasional errors. So how to solve it?

There's a lot of options, as above just changing things around could solve the issue for some people. More robust solutions would be...

  • Restrict the files being copied i.e. instead of xcopy $(TargetDir)*.*"... instead do xcopy "$(TargetDir)$(TargetName).*"...

  • Catch the error and retry i.e:

    :loop
    xcopy /Y /R /S /J /Q  "$(TargetDir)$(TargetName).*" "somewhere"
    if ErrorLevel 1 goto loop
  • Use robocopy instead of xcopy

  • You probably won't want to do this as it will increase your build times, but you could reduce the maximum number of parallel project builds to 1 ...

enter image description here

Check play state of AVPlayer

Swift extension based on the answer by maz

extension AVPlayer {

    var isPlaying: Bool {
        return ((rate != 0) && (error == nil))
    }
}

How to compile makefile using MinGW?

Please learn about automake and autoconf.

Makefile.am is processed by automake to generate a Makefile that is processed by make in order to build your sources.

http://www.gnu.org/software/automake/

Docker - Container is not running

docker run -it <image_id> /bin/bash

Run in interactive mode executing then bash shell

datetime dtypes in pandas read_csv

You might try passing actual types instead of strings.

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

But it's going to be really hard to diagnose this without any of your data to tinker with.

And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:

pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)

Get current location of user in Android without using GPS or internet

What you are looking to do is get the position using the LocationManager.NETWORK_PROVIDER instead of LocationManager.GPS_PROVIDER. The NETWORK_PROVIDER will resolve on the GSM or wifi, which ever available. Obviously with wifi off, GSM will be used. Keep in mind that using the cell network is accurate to basically 500m.

http://developer.android.com/guide/topics/location/obtaining-user-location.html has some really great information and sample code.

After you get done with most of the code in OnCreate(), add this:

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

You could also have your activity implement the LocationListener class and thus implement onLocationChanged() in your activity.

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

JavaScript Regular Expression Email Validation

Simple but powerful email validation for check email syntax :

var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
    msg+= "Enter the valid email address!<br />";
}

jQuery Remove string from string

To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace function since it is not a mutator function:

myString = myString.replace('username1','');

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Here is the solution which worked for me.

OUTPUT: State of Cart Widget is updated, upon addition of items.

enter image description here

Create a globalKey for the widget you want to update by calling the trigger from anywhere

final GlobalKey<CartWidgetState> cartKey = GlobalKey();

Make sure it's saved in a file have global access such that, it can be accessed from anywhere. I save it in globalClass where is save commonly used variables through the app's state.

class CartWidget extends StatefulWidget {

  CartWidget({Key key}) : super(key: key);
  @override
  CartWidgetState createState() => CartWidgetState();
}

class CartWidgetState extends State<CartWidget> {
  @override
  Widget build(BuildContext context) {
    //return your widget
    return Container();
  }
}

Call your widget from some other class.

class HomeScreen extends StatefulWidget {

  HomeScreen ({Key key}) : super(key: key);
  @override
  HomeScreenState createState() => HomeScreen State();
}

class HomeScreen State extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return ListView(
              children:[
                 ChildScreen(), 
                 CartWidget(key:cartKey)
              ]
            );
  }
}



class ChildScreen extends StatefulWidget {

  ChildScreen ({Key key}) : super(key: key);
  @override
  ChildScreenState createState() => ChildScreen State();
}

class ChildScreen State extends State<ChildScreen> {
  @override
  Widget build(BuildContext context) {
    return InkWell(
              onTap: (){
                // This will update the state of your inherited widget/ class
                if (cartKey.currentState != null)
                    cartKey.currentState.setState(() {});
              },
              child: Text("Update The State of external Widget"),
           );
  }
}

How can getContentResolver() be called in Android?

A solution would be to get the ContentResolver from the context

ContentResolver contentResolver = getContext().getContentResolver();

Link to the documentation : ContentResolver

Displaying splash screen for longer than default seconds

Use following line in didFinishLaunchingWithOptions: delegate method:

[NSThread sleepForTimeInterval:5.0];

It will stop splash screen for 5.0 seconds.

java.util.regex - importance of Pattern.compile()?

Compile parses the regular expression and builds an in-memory representation. The overhead to compile is significant compared to a match. If you're using a pattern repeatedly it will gain some performance to cache the compiled pattern.

What is a serialVersionUID and why should I use it?

Field data represents some information stored in the class. Class implements the Serializable interface, so eclipse automatically offered to declare the serialVersionUID field. Lets start with value 1 set there.

If you don't want that warning to come, use this:

@SuppressWarnings("serial")

Launch Bootstrap Modal on page load

Heres a solution [without javascript initialization!]

I couldn't find an example without initializing your modal with javascript, $('#myModal').modal('show'), so heres a suggestion on how you could implement it without javascript delay on page load.

  1. Edit your modal container div with class and style:

<div class="modal in" id="MyModal" tabindex="-1" role="dialog" style="display: block; padding-right: 17px;">

  1. Edit your body with class and style:

    <body class="modal-open" style="padding-right:17px;">

  2. Add modal-backdrop div

    <div class="modal-backdrop in"></div>

  3. Add script

    $(document).ready(function() {
        $('body').css('padding-right', '0px');
        $('body').removeClass('modal-open');
        $('.modal-backdrop').remove();
    
        $('#MyModal').modal('show'); });
    

    What will happen is that the html for your modal will be loaded on page load without any javascript, (no delay). At this point you can't close the modal, so that is why we have the document.ready script, to load the modal properly when everything is loaded. We will actually remove the custom code and then initialize the modal, (again), with the .modal('show').

How do I get hour and minutes from NSDate?

This seems to me to be what the question is after, no need for formatters:

NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Call Jquery function

calling a function is simple ..

 myFunction();

so your code will be something like..

 $(function(){
     $('#elementID').click(function(){
         myFuntion();  //this will call your function
    });
 });

  $(function(){
     $('#elementID').click( myFuntion );

 });

or with some condition

if(something){
   myFunction();  //this will call your function
}

Java 8 Lambda Stream forEach with multiple statements

In the first case alternatively to multiline forEach you can use the peek stream operation:

entryList.stream()
         .peek(entry -> entry.setTempId(tempId))
         .forEach(updatedEntries.add(entityManager.update(entry, entry.getId())));

In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.

Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.

Leading zeros for Int in Swift

For left padding add a string extension like this:

Swift 2.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".stringByPaddingToLength(toPad, withString: with, startingAtIndex: 0) + self
    }
}

Swift 3.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
    }
}

Using this method:

for myInt in 1...3 {
    print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}

How can I declare a two dimensional string array?

you can also write the code below.

Array lbl_array = Array.CreateInstance(typeof(string), i, j);

where 'i' is the number of rows and 'j' is the number of columns. using the 'typeof(..)' method you can choose the type of your array i.e. int, string, double

GitHub: invalid username or password

You might be getting this error because you have updated your password. So on Terminal first make sure you clear your GitHub credentials from the keychain and then push your changes to your repo, terminal will ask for your username and password.

How to add new column to an dataframe (to the front not end)?

If you want to do it in a tidyverse manner, try add_column from tibble, which allows you to specifiy where to place the new column with .before or .after parameter:

library(tibble)

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
add_column(df, a = 0, .before = 1)

#   a b c d
# 1 0 1 2 3
# 2 0 1 2 3
# 3 0 1 2 3

database vs. flat files

What about a non-relational (NoSQL) database such as Amazon's SimpleDB, Tokio Cabinet, etc? I've heard that Google, Facebook, LinkedIn are using these to store their huge datasets.

Can you tell us if your data is structured, if your schema is fixed, if you need easy replicability, if access times are important, etc?

How do you run a command as an administrator from the Windows command line?

Although @amr ali's code was great, I had an instance where my bat file contained > < signs, and it choked on them for some reason.

I found this instead. Just put it all before your code, and it works perfectly.

REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

How often does python flush to a file?

You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.

import io
print (io.DEFAULT_BUFFER_SIZE)

Share application "link" in Android

Thomas,

You would want to provide your users with a market:// link which will bring them directly to the details page of your app. The following is from developer.android.com:

Loading an application's Details page

In Android Market, every application has a Details page that provides an overview of the application for users. For example, the page includes a short description of the app and screen shots of it in use, if supplied by the developer, as well as feedback from users and information about the developer. The Details page also includes an "Install" button that lets the user trigger the download/purchase of the application.

If you want to refer the user to a specific application, your application can take the user directly to the application's Details page. To do so, your application sends an ACTION_VIEW Intent that includes a URI and query parameter in this format:

market://details?id=

In this case, the packagename parameter is target application's fully qualified package name, as declared in the package attribute of the manifest element in the application's manifest file. For example:

market://details?id=com.example.android.jetboy

Source: http://developer.android.com/guide/publishing/publishing.html

WPF Button with Image

Most simple approach would be using the Image tag.

<Button Name="btn" Width="26" Height="26" Click="btnClick"> 
   <Image Source="Resource/btn-icon.png"/>
</Button>

Suppose your image file is added in Resource folder

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

Getting Python error "from: can't read /var/mail/Bio"

Put this at the top of your .py file (for python 2.x)

#!/usr/bin/env python 

or for python 3.x

#!/usr/bin/env python3

This should look up the python environment, without it, it will execute the code as if it were not python code, but straight to the CLI. If you need to specify a manual location of python environment put

#!/#path/#to/#python

How to create a Java cron job

You can use TimerTask for Cronjobs.

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);
   }

}

MyTask.java

class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
     System.out.println("Hi see you after 10 seconds");
   }

}

Alternative You can also use ScheduledExecutorService.

How to install the JDK on Ubuntu Linux

You can use the sudo apt-get install default-jdk terminal command to install the default JDK version.

Before installing Java, type the sudo apt-get update terminal command and then type the install terminal command. You can get more information from here.

Setting up an MS-Access DB for multi-user access

I find the answers to this question to be problematic, confusing and incomplete, so I'll make an effort to do better.

Q1: How can we make sure that the write-user can make changes to the table data while other users use the data? Do the read-users put locks on tables? Does the write-user have to put locks on the table? Does Access do this for us or do we have to explicitly code this?

Nobody has really answered this in any complete fashion. The information on setting locks in the Access options has nothing to do with read vs. write locking. No Locks vs. All Records vs. Edited Record is how you set the default record locking for WRITES.

  • No locks means you are using OPTIMISTIC locking, which means you allow multiple users to edit the record and then inform them after the fact if the record has changed since they launched their own edits. Optimistic locking is what you should start with as it requires no coding to implement it, and for small users populations it hardly ever causes a problem.

  • All Records means that the whole table is locked any time an edit is launched.

  • Edited Record means that fewer records are locked, but whether or not it's a single record or more than one record depends on whether your database is set up to use record-level locking (first added in Jet 4) or page-level locking. Frankly, I've never thought it worth the trouble to set up record-level locking, as optimistic locking takes care of most of the problems.

One might think that you want to use record-level pessimistic locking, but the fact is that in the vast majority of apps, two users are almost never editing the same record. Now, obviously, certain kinds of apps might be exceptions to that, but if I ran into such an app, I'd likely try to engineer it away by redesigning the schema so that it would be very uncommon for two users to edit the same record (usually by going to some form of transactional editing instead, where changes are made by adding records, rather than editing the existing data).

Now, for your actual question, there are a number of ways to accomplish restricting some users to read-only and granting others write privileges. Jet user-level security was intended for this purpose and works fine insofar as it's "security" for any meaningful definition of the term. In general, as long as you're using a Jet/ACE data store, the best security you're going to get is that provided by Jet ULS. It's crackable, yes, but your users would be committing a firable offense by breaking it, so it might be sufficient.

I would tend to not implement Jet ULS at all and instead just architect the data editing forms such that they checked the user's Windows logon and made the forms read-only or writable depending on which users are supposed to get which access. Whether or not you want to record group membership in a data table, or maintain Windows security groups for this purpose is up to you. You could also use a Jet workgroup file to deal with it, and provide a different system.mdw file for the write users. The read-only users would log on transparently as admin, and those logged on as admin would be granted only read-only access. The write users would log on as some other username (transparently, in the shortcut you provide them for launching the app, supplying no password), and that would be used to set up the forms as read or write.

If you use Jet ULS, it can become really hairy to get it right. It involves locking down all the tables as read-only (or maybe not even that) and then using RWOP queries to provide access to the data. I haven't done but one such app in my 14 years of professional Access development.

To summarize my answers to the parts of your question:

How can we make sure that the write-user can make changes to the table data while other users use the data?

I would recommend doing this in the application, setting forms to read/only or editable at runtime depending on the user logon. The easiest approach is to set your forms to be read-only and change to editable for the write users when they open the form.

Do the read-users put locks on tables?

Not in any meaningful sense. Jet/ACE does have read locks, but they are there only for the purpose of maintaining state for individual views, and for refreshing data for the user. They do not lock out write operations of any kind, though the overhead of tracking them theoretically slows things down. It's not enough to worry about.

Does the write-user have to put locks on the table?

Access in combination with Jet/ACE does this for you automatically, particularly if you choose optimistic locking as your default. The key point here is that Access apps are databound, so as soon as a form is loaded, the record has a read lock, and as soon as the record is edited, whether or not it is write-locked for other users is determined by whether you are using optimistic or pessimistic locking. Again, this is the kind of thing Access takes care of for you with its default behaviors in bound forms. You don't worry about any of it until the point at which you encounter problems.

Does Access do this for us or do we have to explicitly code this?

Basically, other than setting editability at runtime (according to who has write access), there is no coding necessary if you're using optimistic locking. With pessimistic locking, you don't have to code, but you will almost always need to, as you can't just leave the user stuck with the default behaviors and error messages.

Q2: Are there any common problems with "MS Access transactions" that we should be aware of?

Jet/ACE has support for commit/rollback transactions, but it's not clear to me if that's what you mean in this question. In general, I don't use transactions except for maintaining atomicity, e.g., when creating an invoice, or doing any update that involves multiple tables. It works about the way you'd expect it to but is not really necessary for the vast majority of operations in an Access application.

Perhaps one of the issues here (particularly in light of the first question) is that you may not quite grasp that Access is designed for creating apps with data bound to the forms. "Transactions" is a topic of great importance for unbound and stateless apps (e.g., browser-based), but for data bound apps, the editing and saving all happens transparently.

For certain kinds of operations this can be problematic, and occasionally it's appropriate to edit data in Access with unbound forms. But that's very seldom the case, in my experience. It's not that I don't use unbound forms -- I use lots of them for dialogs and the like -- it's just that my apps don't edit data tables with unbound forms. With almost no exceptions, all my apps edit data with bound forms.

Now, unbound forms are actually fairly easy to implement in Access (particularly if you name your editing controls the same as the underlying fields), but going with unbound data editing forms is really missing the point of using Access, which is that the binding is all done for you. And the main drawback of going unbound is that you lose all the record-level form events, such as OnInsert, BeforeUpdate and so forth.

Q3. Can we work on forms, queries etc. while they are being used? How can we "program" without being in the way of the users?

This is one of the questions that's been well-addressed. All multi-user or replicated Access apps should be split, and most single-user apps should be, too. It's good design and also makes the apps more stable, as only the data tables end up being opened by more than one user at a time.

Q4. Which settings in MS Access have an influence on how things are handled?

"Things?" What things?

Q5. Our background is mostly in Oracle, where is Access different in handling multiple users? Is there such thing as "isolation levels" in Access?

I don't know anything specifically about Oracle (none of my clients could afford it even if they wanted to), but asking for a comparison of Access and Oracle betrays a fundamental misunderstanding somewhere along the line.

Access is an application development tool.

Oracle is an industrial strength database server.

Apples and oranges.

Now, of course, Access ships with a default database engine, originally called Jet and now revised and renamed ACE, but there are many levels at which Access the development platform can be entirely decoupled from Jet/ACE, the default database engine.

In this case, you've chosen to use a Jet/ACE back end, which will likely be just fine for small user populations, i.e., under 25. Jet/ACE can also be fine up to 50 or 100, particularly when only a few of the simultaneous users have write permission. While the 255-user limit in Jet/ACE includes both read-only and write users, it's the number of write users that really controls how many simultaneous users you can support, and in your case, you've got an app with mostly read-only users, so it oughtn't be terribly difficult to engineer a good app that has no problems with the back end.

Basically, I think your Oracle background is likely leading you to misunderstand how to develop in Access, where the expected approach is to bind your forms to recordsources that are updated without any need to write code. Now, for efficiency's sake it's a good idea to bind your forms to subsets of records, rather than to whole tables, but even with an entire table in the recordsource behind a data editing form, Access is going to be fairly efficient in editing Jet/ACE tables (the old myth about pulling the whole table across the wire is still out there) as long your data tables are efficiently indexed.

Record locking is something you mostly shouldn't have any cause to worry about, and one of the reasons for that is because of bound editing, where the form knows what's going on in the back end at all times (well, at intervals about a second apart, the default refresh interval). That is, it's not like a web page where you retrieve a copy of the data and then post your edits back to the server in a transaction completely unconnected to the original data retrieval operation. In a bound environment like Access, the locking file on the back-end data file is always going to be keeping track of the fact that someone has the record open for editing. This prevents a user's edits from stomping on someone else's edits, because Access knows the state and informs the user. This all happens without any coding on the part of the developer and is one of the great advantages of the bound editing model (aside from not having to write code to post the edits).

For all those who are experienced database programmers familiar with other platforms who are coming to Access for the first time, I strongly suggest using Access like an end user. Try out all the point and click features. Run the form and report wizards and check out the results that they produce. I can't vouch for all of them as demonstrating good practices, but they definitely demonstrate the default assumptions behind the way Access is intended to be used.

If you find yourself writing a lot of code, then you're likely missing the point of Access.

Sum of Numbers C++

I have the following formula that works without loops. I discovered it while trying to find a formula for factorials:

#include <iostream>
using namespace std;

int main() {
    unsigned int positiveInteger;
    cout << "Please input an integer up to 100." << endl;
    cin >> positiveInteger;

    cout << (positiveInteger * (positiveInteger + 1)) / 2;
    return 0;
}

How to use JavaScript source maps (.map files)?

Just to add to how to use map files. I use chrome for ubuntu and if I go to sources and click on a file, if there is a map file a message comes up telling me that I can view the original file and how to do it.

For the Angular files that I worked with today I click

Ctrl-P and a list of original files comes up in a small window.

I can then browse through the list to view the file that I would like to inspect and check where the issue might be.

Is it possible to read from a InputStream with a timeout?

Inspired in this answer I came up with a bit more object-oriented solution.

This is only valid if you're intending to read characters

You can override BufferedReader and implement something like this:

public class SafeBufferedReader extends BufferedReader{

    private long millisTimeout;

    ( . . . )

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return 0;
        }
        return super.read(cbuf, off, len);
    }

    protected void waitReady() throws IllegalThreadStateException, IOException {
        if(ready()) return;
        long timeout = System.currentTimeMillis() + millisTimeout;
        while(System.currentTimeMillis() < timeout) {
            if(ready()) return;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                break; // Should restore flag
            }
        }
        if(ready()) return; // Just in case.
        throw new IllegalThreadStateException("Read timed out");
    }
}

Here's an almost complete example.

I'm returning 0 on some methods, you should change it to -2 to meet your needs, but I think that 0 is more suitable with BufferedReader contract. Nothing wrong happened, it just read 0 chars. readLine method is a horrible performance killer. You should create a entirely new BufferedReader if you actually want to use readLine. Right now, it is not thread safe. If someone invokes an operation while readLines is waiting for a line, it will produce unexpected results

I don't like returning -2 where I am. I'd throw an exception because some people may just be checking if int < 0 to consider EOS. Anyway, those methods claim that "can't block", you should check if that statement is actually true and just don't override'em.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * 
 * readLine
 * 
 * @author Dario
 *
 */
public class SafeBufferedReader extends BufferedReader{

    private long millisTimeout;

    private long millisInterval = 100;

    private int lookAheadLine;

    public SafeBufferedReader(Reader in, int sz, long millisTimeout) {
        super(in, sz);
        this.millisTimeout = millisTimeout;
    }

    public SafeBufferedReader(Reader in, long millisTimeout) {
        super(in);
        this.millisTimeout = millisTimeout;
    }



    /**
     * This is probably going to kill readLine performance. You should study BufferedReader and completly override the method.
     * 
     * It should mark the position, then perform its normal operation in a nonblocking way, and if it reaches the timeout then reset position and throw IllegalThreadStateException
     * 
     */
    @Override
    public String readLine() throws IOException {
        try {
            waitReadyLine();
        } catch(IllegalThreadStateException e) {
            //return null; //Null usually means EOS here, so we can't.
            throw e;
        }
        return super.readLine();
    }

    @Override
    public int read() throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return -2; // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
        }
        return super.read();
    }

    @Override
    public int read(char[] cbuf) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return -2;  // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
        }
        return super.read(cbuf);
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return 0;
        }
        return super.read(cbuf, off, len);
    }

    @Override
    public int read(CharBuffer target) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return 0;
        }
        return super.read(target);
    }

    @Override
    public void mark(int readAheadLimit) throws IOException {
        super.mark(readAheadLimit);
    }

    @Override
    public Stream<String> lines() {
        return super.lines();
    }

    @Override
    public void reset() throws IOException {
        super.reset();
    }

    @Override
    public long skip(long n) throws IOException {
        return super.skip(n);
    }

    public long getMillisTimeout() {
        return millisTimeout;
    }

    public void setMillisTimeout(long millisTimeout) {
        this.millisTimeout = millisTimeout;
    }

    public void setTimeout(long timeout, TimeUnit unit) {
        this.millisTimeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
    }

    public long getMillisInterval() {
        return millisInterval;
    }

    public void setMillisInterval(long millisInterval) {
        this.millisInterval = millisInterval;
    }

    public void setInterval(long time, TimeUnit unit) {
        this.millisInterval = TimeUnit.MILLISECONDS.convert(time, unit);
    }

    /**
     * This is actually forcing us to read the buffer twice in order to determine a line is actually ready.
     * 
     * @throws IllegalThreadStateException
     * @throws IOException
     */
    protected void waitReadyLine() throws IllegalThreadStateException, IOException {
        long timeout = System.currentTimeMillis() + millisTimeout;
        waitReady();

        super.mark(lookAheadLine);
        try {
            while(System.currentTimeMillis() < timeout) {
                while(ready()) {
                    int charInt = super.read();
                    if(charInt==-1) return; // EOS reached
                    char character = (char) charInt;
                    if(character == '\n' || character == '\r' ) return;
                }
                try {
                    Thread.sleep(millisInterval);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // Restore flag
                    break;
                }
            }
        } finally {
            super.reset();
        }
        throw new IllegalThreadStateException("readLine timed out");

    }

    protected void waitReady() throws IllegalThreadStateException, IOException {
        if(ready()) return;
        long timeout = System.currentTimeMillis() + millisTimeout;
        while(System.currentTimeMillis() < timeout) {
            if(ready()) return;
            try {
                Thread.sleep(millisInterval);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // Restore flag
                break;
            }
        }
        if(ready()) return; // Just in case.
        throw new IllegalThreadStateException("read timed out");
    }

}

How do I fetch lines before/after the grep result in bash?

This prints 10 lines of trailing context after matching lines

grep -i "my_regex" -A 10

If you need to print 10 lines of leading context before matching lines,

grep -i "my_regex" -B 10

And if you need to print 10 lines of leading and trailing output context.

grep -i "my_regex" -C 10

Example

user@box:~$ cat out 
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
user@box:~$

Normal grep

user@box:~$ grep my_regex out 
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines after

user@box:~$ grep -A 2 my_regex out   
line 5 my_regex
line 6
line 7
user@box:~$ 

Grep exact matching lines and 2 lines before

user@box:~$ grep -B 2 my_regex out  
line 3
line 4
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines before and after

user@box:~$ grep -C 2 my_regex out  
line 3
line 4
line 5 my_regex
line 6
line 7
user@box:~$ 

Reference: manpage grep

-A num
--after-context=num

    Print num lines of trailing context after matching lines.
-B num
--before-context=num

    Print num lines of leading context before matching lines.
-C num
-num
--context=num

    Print num lines of leading and trailing output context.

Checking Date format from a string in C#

you can use DateTime.ParseExact with the format string

DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);

Above will throw an exception if the given string not in given format.

use DateTime.TryParseExact if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.

check Custom Date and Time Format Strings

How to add pandas data to an existing csv file?

A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.

from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
     file_to=open(path,mode)
     yield file_to
     file_to.close()


##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
      saved_df.to_csv('yourcsv.csv',mode='a',header=False)`

How can I pass a parameter to a Java Thread?

To create a thread you normally create your own implementation of Runnable. Pass the parameters to the thread in the constructor of this class.

class MyThread implements Runnable{
   private int a;
   private String b;
   private double c;

   public MyThread(int a, String b, double c){
      this.a = a;
      this.b = b;
      this.c = c;
   }

   public void run(){
      doSomething(a, b, c);
   }
}

Printing out a linked list using toString

As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.

LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());

This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:

  1. Add a toString() method to your LinkedListNode class.
  2. Update the toString() method in your LinkedList class to be more concise.
  3. Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.

In LinkedListNode:

public String toString(){
   return "LinkedListNode with data: " + getData();
}

In LinkedList:

public int size(){
    int currentSize = 0;
    LinkedListNode current = head;
    while(current != null){
        currentSize = currentSize + 1;
        current = current.getNext();
    }

    return currentSize;
}

public String toString(){
    return "LinkedList with " + size() + "elements.";
}

public void printList(){
    System.out.println("Contents of " + toString());

    LinkedListNode current = head;
    while(current != null){
        System.out.println(current.toString());
        current = current.getNext();
    }

}

The 'json' native gem requires installed build tools

Follow the Instructions from the Ruby Installer Developer Kit Wiki:

  1. Download Ruby 1.9.3 from rubyinstaller.org
  2. Download DevKit file from rubyinstaller.org
  3. Extract DevKit to path C:\Ruby193\DevKit
  4. Run cd C:\Ruby193\DevKit
  5. Run ruby dk.rb init
  6. Run ruby dk.rb review
  7. Run ruby dk.rb install

To return to the problem at hand, you should be able to install JSON (or otherwise test that your DevKit successfully installed) by running the following commands which will perform an install of the JSON gem and then use it:

gem install json --platform=ruby
ruby -rubygems -e "require 'json'; puts JSON.load('[42]').inspect"

View content of H2 or HSQLDB in-memory database

I don't know why is it working fine at yours machines, but I had to spend a day in order to get it is working.

The server works with Intellij Idea U via url "jdbc:h2:tcp://localhost:9092/~/default".

"localhost:8082" in the browser alse works fine.

I added this into the mvc-dispatcher-servlet.xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" depends-on="h2Server">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:tcp://localhost:9092/~/default"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
</bean>

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg>
        <array>
            <value>-tcp</value>
            <value>-tcpAllowOthers</value>
            <value>-tcpPort</value>
            <value>9092</value>
        </array>
    </constructor-arg>
</bean>

<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg>
        <array>
            <value>-web</value>
            <value>-webAllowOthers</value>
            <value>-webPort</value>
            <value>8082</value>
        </array>
    </constructor-arg>
</bean>

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 to set border's thickness in percentages?

Take a look at calc() specification. Here is an example of usage:

border-right:1px solid;
border-left:1px solid;
width:calc(100% - 2px);

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

How to check if a service is running on Android?

Please use this code.

if (isMyServiceRunning(MainActivity.this, xyzService.class)) { // Service class name
    // Service running
} else {
    // Service Stop
}


public static boolean isMyServiceRunning(Activity activity, Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

How to count string occurrence in string?

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

_x000D_
_x000D_
var temp = "This is a string.";_x000D_
var count = (temp.match(/is/g) || []).length;_x000D_
console.log(count);
_x000D_
_x000D_
_x000D_

And, if there are no matches, it returns 0:

_x000D_
_x000D_
var temp = "Hello World!";_x000D_
var count = (temp.match(/is/g) || []).length;_x000D_
console.log(count);
_x000D_
_x000D_
_x000D_

Select from one table matching criteria in another?

You should make tags their own table with a linking table.

items:
id    object
1     lamp  
2     table   
3     stool  
4     bench 

tags:
id     tag
1      furniture
2      chair

items_tags:
item_id tag_id
1       1
2       1
3       1
4       1
3       2
4       2

android get real path by Uri.getPath()

This is what I do:

Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

and:

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

NOTE: managedQuery() method is deprecated, so I am not using it.

Last edit: Improvement. We should close cursor!!

How can I select rows by range?

Assuming id is the primary key of table :

SELECT * FROM table WHERE id BETWEEN 10 AND 50

For first 20 results

SELECT * FROM table order by id limit 20;

SQL update fields of one table from fields of another one

Not necessarily what you asked, but maybe using postgres inheritance might help?

CREATE TABLE A (
    ID            int,
    column1       text,
    column2       text,
    column3       text
);

CREATE TABLE B (
    column4       text
) INHERITS (A);

This avoids the need to update B.

But be sure to read all the details.

Otherwise, what you ask for is not considered a good practice - dynamic stuff such as views with SELECT * ... are discouraged (as such slight convenience might break more things than help things), and what you ask for would be equivalent for the UPDATE ... SET command.

Entity Framework change connection at runtime

The created class is 'partial'!

public partial class Database1Entities1 : DbContext
{
    public Database1Entities1()
        : base("name=Database1Entities1")
    {
    }

... and you call it like this:

using (var ctx = new Database1Entities1())
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.

After it you able to use parametrized constructor against original. :-)

example:

using (var ctx = new Database1Entities1(myOwnConnectionString))
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

read file from assets

cityfile.txt

   public void getCityStateFromLocal() {
        AssetManager am = getAssets();
        InputStream inputStream = null;
        try {
            inputStream = am.open("city_state.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String[]> map = new HashMap<String, String[]>();
        try {
            map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        ConstantValues.arrayListStateName.clear();
        ConstantValues.arrayListCityByState.clear();
        if (map.size() > 0)
        {
            for (Map.Entry<String, String[]> e : map.entrySet()) {
                CityByState cityByState = new CityByState();
                String key = e.getKey();
                String[] value = e.getValue();
                ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
                ConstantValues.arrayListStateName.add(key);
                s.add(0,"Select City");
                cityByState.addValue(s);
                ConstantValues.arrayListCityByState.add(cityByState);
            }
        }
        ConstantValues.arrayListStateName.add(0,"Select States");
    }
 // Convert InputStream to String
    public String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb + "";

    }

How do I comment out a block of tags in XML?

You can use that style of comment across multiple lines (which exists also in HTML)

<detail>
    <band height="20">
    <!--
      Hello,
         I am a multi-line XML comment
         <staticText>
            <reportElement x="180" y="0" width="200" height="20"/>
            <text><![CDATA[Hello World!]]></text>
          </staticText>
      -->
     </band>
</detail>

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

How do I get the total Json record count using JQuery?

What you're looking for is

j.d.length

The d is the key. At least it is in my case, I'm using a .NET webservice.

 $.ajax({
            type: "POST",
            url: "CantTellU.asmx",
            data: "{'userID' : " + parseInt($.query.get('ID')) + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg, status) {
                ApplyTemplate(msg);
                alert(msg.d.length);
            }
        });

Pandas DataFrame Groupby two columns and get counts

Should you want to add a new column (say 'count_column') containing the groups' counts into the dataframe:

df.count_column=df.groupby(['col5','col2']).col5.transform('count')

(I picked 'col5' as it contains no nan)

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

javascript date + 7 days

_x000D_
_x000D_
var future = new Date(); // get today date_x000D_
future.setDate(future.getDate() + 7); // add 7 days_x000D_
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();_x000D_
console.log(finalDate);
_x000D_
_x000D_
_x000D_

JavaFX How to set scene background image

One of the approaches may be like this:

1) Create a CSS file with name "style.css" and define an id selector in it:

#pane{
    -fx-background-image: url("background_image.jpg");
    -fx-background-repeat: stretch;   
    -fx-background-size: 900 506;
    -fx-background-position: center center;
    -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); 
}

2) Set the id of the most top control (or any control) in the scene with value defined in CSS and load this CSS file into the scene:

  public class Test extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        root.setId("pane");
        Scene scene = new Scene(root, 300, 250);
        scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

You can also give an id to the control in a FXML file:

<StackPane id="pane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="demo.Sample">
    <children>
    </children>
</StackPane>

For more info about JavaFX CSS Styling refer to this guide.

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

Copy Paste Values only( xlPasteValues )

If you are wanting to just copy the whole column, you can simplify the code a lot by doing something like this:

Sub CopyCol()

    Sheets("Sheet1").Columns(1).Copy

    Sheets("Sheet2").Columns(2).PasteSpecial xlPasteValues

End Sub

Or

Sub CopyCol()

    Sheets("Sheet1").Columns("A").Copy

    Sheets("Sheet2").Columns("B").PasteSpecial xlPasteValues

End Sub

Or if you want to keep the loop

Public Sub CopyrangeA()

    Dim firstrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    firstrowDB = 1
    arr1 = Array("BJ", "BK")
    arr2 = Array("A", "B")

    For i = LBound(arr1) To UBound(arr1)

        Sheets("Sheet1").Columns(arr1(i)).Copy

        Sheets("Sheet2").Columns(arr2(i)).PasteSpecial xlPasteValues

    Next
    Application.CutCopyMode = False

End Sub

How is Docker different from a virtual machine?

This is how Docker introduces itself:

Docker is the company driving the container movement and the only container platform provider to address every application across the hybrid cloud. Today’s businesses are under pressure to digitally transform but are constrained by existing applications and infrastructure while rationalizing an increasingly diverse portfolio of clouds, datacenters and application architectures. Docker enables true independence between applications and infrastructure and developers and IT ops to unlock their potential and creates a model for better collaboration and innovation.

So Docker is container based, meaning you have images and containers which can be run on your current machine. It's not including the operating system like VMs, but like a pack of different working packs like Java, Tomcat, etc.

If you understand containers, you get what Docker is and how it's different from VMs...

So, what's a container?

A container image is a lightweight, stand-alone, executable package of a piece of software that includes everything needed to run it: code, runtime, system tools, system libraries, settings. Available for both Linux and Windows based apps, containerized software will always run the same, regardless of the environment. Containers isolate software from its surroundings, for example differences between development and staging environments and help reduce conflicts between teams running different software on the same infrastructure.

Docker

So as you see in the image below, each container has a separate pack and running on a single machine share that machine's operating system... They are secure and easy to ship...

How do you create a hidden div that doesn't create a line break or horizontal space?

Since you should focus on usability and generalities in CSS, rather than use an id to point to a specific layout element (which results in huge or multiple css files) you should probably instead use a true class in your linked .css file:

.hidden {
visibility: hidden;
display: none;
}

or for the minimalist:

.hidden {
display: none;
}

Now you can simply apply it via:

<div class="hidden"> content </div>

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

What are the specific differences between .msi and setup.exe file?

.msi files are windows installer files without the windows installer runtime, setup.exe can be any executable programm (probably one that installs stuff on your computer)

How to tell git to use the correct identity (name and email) for a given project?

git config user.email "[email protected]"

Doing that one inside a repo will set the configuration on THAT repo, and not globally.

Seems like that's pretty much what you're after, unless I'm misreading you.

Is there a concise way to iterate over a stream with indices in Java 8?

If you need the index in the forEach then this provides a way.

  public class IndexedValue {

    private final int    index;
    private final Object value;

    public IndexedValue(final int index, final Object value) { 
        this.index = index;
        this.value = value;
    }

    public int getIndex() {
        return index;
    }

    public Object getValue() {
        return value;
    }
}

Then use it as follows.

@Test
public void withIndex() {
    final List<String> list = Arrays.asList("a", "b");
    IntStream.range(0, list.size())
             .mapToObj(index -> new IndexedValue(index, list.get(index)))
             .forEach(indexValue -> {
                 System.out.println(String.format("%d, %s",
                                                  indexValue.getIndex(),
                                                  indexValue.getValue().toString()));
             });
}

What is the significance of load factor in HashMap?

Actually, from my calculations, the "perfect" load factor is closer to log 2 (~ 0.7). Although any load factor less than this will yield better performance. I think that .75 was probably pulled out of a hat.

Proof:

Chaining can be avoided and branch prediction exploited by predicting if a bucket is empty or not. A bucket is probably empty if the probability of it being empty exceeds .5.

Let s represent the size and n the number of keys added. Using the binomial theorem, the probability of a bucket being empty is:

P(0) = C(n, 0) * (1/s)^0 * (1 - 1/s)^(n - 0)

Thus, a bucket is probably empty if there are less than

log(2)/log(s/(s - 1)) keys

As s reaches infinity and if the number of keys added is such that P(0) = .5, then n/s approaches log(2) rapidly:

lim (log(2)/log(s/(s - 1)))/s as s -> infinity = log(2) ~ 0.693...

Core dumped, but core file is not in the current directory?

If you use Fedora, in order to generate core dump file in the same directory of binary file:

echo "core.%e.%p" > /proc/sys/kernel/core_pattern

And

ulimit -c unlimited

POSTing JsonObject With HttpClient From Web API

The easiest way is to use a StringContent, with the JSON representation of your JSON object.

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

You are all good at Angular side even postman not raise the cors policy issue. This type of issue is solved at back-end side in major cases.

If you are using Spring boot the you can avoid this issue by placing this annotation at your controller class or at any particular method.

@CrossOrigin(origins = "http://localhost:4200")

In case of global configuration with spring boot configure following two class:

`

@EnableWebSecurity
@AllArgsConstructor

public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
    public void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.csrf().disable()
        .authorizeRequests()
        .antMatchers("/api1/**").permitAll()
        .antMatchers("/api2/**").permitAll()
        .antMatchers("/api3/**").permitAll()
        
}
`

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("*")
                .maxAge(3600L)
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true);
    }

How get total sum from input box values using Javascript?

Here's a simpler solution using what Akhil Sekharan has provided but with a little change.

var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i += 1) {
if(parseInt(inputs[i].value)){
        inputs[i].value = '';
       }
    }????
document.getElementById('total').value = total;

a page can have only one server-side form tag

Sometime when you render the current page as shown in below code will generate the same error

StringWriter str_wrt = new StringWriter();
HtmlTextWriter html_wrt = new HtmlTextWriter(str_wrt);
Page.RenderControl(html_wrt);
String HTML = str_wrt.ToString();

so how can we sort it?

Get first date of current month in java

Calendar date = Calendar.getInstance();
date.set(Calendar.DAY_OF_MONTH, 1);

How to extract numbers from string in c?

Make a state machine that operates on one basic principle: is the current character a number.

  • When transitioning from non-digit to digit, you initialize your current_number := number.
  • when transitioning from digit to digit, you "shift" the new digit in:
    current_number := current_number * 10 + number;
  • when transitioning from digit to non-digit, you output the current_number
  • when from non-digit to non-digit, you do nothing.

Optimizations are possible.

Vim: faster way to select blocks of text in visual mode

In addition to what others have said, you can also expand your selection using pattern searches.

For example, v/foo will select from your current position to the next instance of "foo." If you actually wanted to expand to the next instance of "foo," on line 35, for example, just press n to expand selection to the next instance, and so on.

update

I don't often do it, but I know that some people use marks extensively to make visual selections. For example, if I'm on line 5 and I want to select to line 35, I might press ma to place mark a on line 5, then :35 to move to line 35. Shift + v to enter linewise visual mode, and finally `a to select back to mark a.

Group by multiple field names in java 8

This is how I did grouping by multiple fields branchCode and prdId, Just posting it for someone in need

    import java.math.BigDecimal;
    import java.math.BigInteger;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;

    /**
     *
     * @author charudatta.joshi
     */
    public class Product1 {

        public BigInteger branchCode;
        public BigInteger prdId;
        public String accountCode;
        public BigDecimal actualBalance;
        public BigDecimal sumActBal;
        public BigInteger countOfAccts;

        public Product1() {
        }

        public Product1(BigInteger branchCode, BigInteger prdId, String accountCode, BigDecimal actualBalance) {
            this.branchCode = branchCode;
            this.prdId = prdId;
            this.accountCode = accountCode;
            this.actualBalance = actualBalance;
        }

        public BigInteger getCountOfAccts() {
            return countOfAccts;
        }

        public void setCountOfAccts(BigInteger countOfAccts) {
            this.countOfAccts = countOfAccts;
        }

        public BigDecimal getSumActBal() {
            return sumActBal;
        }

        public void setSumActBal(BigDecimal sumActBal) {
            this.sumActBal = sumActBal;
        }

        public BigInteger getBranchCode() {
            return branchCode;
        }

        public void setBranchCode(BigInteger branchCode) {
            this.branchCode = branchCode;
        }

        public BigInteger getPrdId() {
            return prdId;
        }

        public void setPrdId(BigInteger prdId) {
            this.prdId = prdId;
        }

        public String getAccountCode() {
            return accountCode;
        }

        public void setAccountCode(String accountCode) {
            this.accountCode = accountCode;
        }

        public BigDecimal getActualBalance() {
            return actualBalance;
        }

        public void setActualBalance(BigDecimal actualBalance) {
            this.actualBalance = actualBalance;
        }

        @Override
        public String toString() {
            return "Product{" + "branchCode:" + branchCode + ", prdId:" + prdId + ", accountCode:" + accountCode + ", actualBalance:" + actualBalance + ", sumActBal:" + sumActBal + ", countOfAccts:" + countOfAccts + '}';
        }

        public static void main(String[] args) {
            List<Product1> al = new ArrayList<Product1>();
            System.out.println(al);
            al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "001", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "002", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "003", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "004", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "005", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("01"), new BigInteger("13"), "006", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "007", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "008", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "009", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "010", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "011", new BigDecimal("10")));
            al.add(new Product1(new BigInteger("02"), new BigInteger("13"), "012", new BigDecimal("10")));
            //Map<BigInteger, Long> counting = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.counting()));
            // System.out.println(counting);

            //group by branch code
            Map<BigInteger, List<Product1>> groupByBrCd = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.toList()));
            System.out.println("\n\n\n" + groupByBrCd);

             Map<BigInteger, List<Product1>> groupByPrId = null;
              // Create a final List to show for output containing one element of each group
            List<Product> finalOutputList = new LinkedList<Product>();
            Product newPrd = null;
            // Iterate over resultant  Map Of List
            Iterator<BigInteger> brItr = groupByBrCd.keySet().iterator();
            Iterator<BigInteger> prdidItr = null;    



            BigInteger brCode = null;
            BigInteger prdId = null;

            Map<BigInteger, List<Product>> tempMap = null;
            List<Product1> accListPerBr = null;
            List<Product1> accListPerBrPerPrd = null;

            Product1 tempPrd = null;
            Double sum = null;
            while (brItr.hasNext()) {
                brCode = brItr.next();
                //get  list per branch
                accListPerBr = groupByBrCd.get(brCode);

                // group by br wise product wise
                groupByPrId=accListPerBr.stream().collect(Collectors.groupingBy(Product1::getPrdId, Collectors.toList()));

                System.out.println("====================");
                System.out.println(groupByPrId);

                prdidItr = groupByPrId.keySet().iterator();
                while(prdidItr.hasNext()){
                    prdId=prdidItr.next();
                    // get list per brcode+product code
                    accListPerBrPerPrd=groupByPrId.get(prdId);
                    newPrd = new Product();
                     // Extract zeroth element to put in Output List to represent this group
                    tempPrd = accListPerBrPerPrd.get(0);
                    newPrd.setBranchCode(tempPrd.getBranchCode());
                    newPrd.setPrdId(tempPrd.getPrdId());

                    //Set accCOunt by using size of list of our group
                    newPrd.setCountOfAccts(BigInteger.valueOf(accListPerBrPerPrd.size()));
                    //Sum actual balance of our  of list of our group 
                    sum = accListPerBrPerPrd.stream().filter(o -> o.getActualBalance() != null).mapToDouble(o -> o.getActualBalance().doubleValue()).sum();
                    newPrd.setSumActBal(BigDecimal.valueOf(sum));
                    // Add product element in final output list

                    finalOutputList.add(newPrd);

                }

            }

            System.out.println("+++++++++++++++++++++++");
            System.out.println(finalOutputList);

        }
    }

Output is as below:

+++++++++++++++++++++++
[Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}, Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}]

After Formatting it :

[
Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, 
Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, 
Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}, 
Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, 
Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, 
Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}
]

getActivity() returns null in Fragment function

The other answers that suggest keeping a reference to the activity in onAttach are just suggesting a bandaid to the real problem. When getActivity returns null it means that the Fragment is not attached to the Activity. Most commonly this happens when the Activity has gone away due to rotation or the Activity being finished but the Fragment still has some kind of callback listener registered. When the listener gets called if you need to do something with the Activity but the Activity is gone there isn't much you can do. In your code you should just check getActivity() != null and if it's not there then don't do anything. If you keep a reference to the Activity that is gone you are preventing the Activity from being garbage collected. Any UI things you might try to do won't be seen by the user. I can imagine some situations where in the callback listener you want to have a Context for something non-UI related, in those cases it probably makes more sense to get the Application context. Note that the only reason that the onAttach trick isn't a big memory leak is because normally after the callback listener executes it won't be needed anymore and can be garbage collected along with the Fragment, all its View's and the Activity context. If you setRetainInstance(true) there is a bigger chance of a memory leak because the Activity field will also be retained but after rotation that could be the previous Activity not the current one.

How to install python-dateutil on Windows?

I followed several suggestions in this list without success. Finally got it installed on Windows using this method: I extracted the zip file and placed the folders under my python27 folder. In a DOS window, I navigated to the installed root folder from extracting the zip file (python-dateutil-2.6.0), then issued this command:

.\python setup.py install

Whammo-bammo it all worked.

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

Keep the h2 at the top, then pull-left on the p and pull-right on the login-box

<div class='container'>
  <div class='hero-unit'>

    <h2>Welcome</h2>

    <div class="pull-left">
      <p>Please log in</p>
    </div>

    <div id='login-box' class='pull-right control-group'>
        <div class='clearfix'>
            <input type='text' placeholder='Username' />
        </div>
        <div class='clearfix'>
            <input type='password' placeholder='Password' />
        </div>
        <button type='button' class='btn btn-primary'>Log in</button>
    </div>

    <div class="clearfix"></div>

  </div>
</div>

the default vertical-align on floated boxes is baseline, so the "Please log in" exactly lines up with the "Username" (check by changing the pull-right to pull-left).

Is there an equivalent to background-size: cover and contain for image elements?

I know this is old, however many solutions I see above have an issue with the image/video being too large for the container so not actually acting like background-size cover. However, I decided to make "utility classes" so that it would work for images and videos. You simply give the container the class .media-cover-wrapper and the media item itself the class .media-cover

Then you have the following jQuery:

function adjustDimensions(item, minW, minH, maxW, maxH) {
  item.css({
  minWidth: minW,
  minHeight: minH,
  maxWidth: maxW,
  maxHeight: maxH
  });
} // end function adjustDimensions

function mediaCoverBounds() {
  var mediaCover = $('.media-cover');

  mediaCover.each(function() {
   adjustDimensions($(this), '', '', '', '');
   var mediaWrapper = $(this).parent();
   var mediaWrapperWidth = mediaWrapper.width();
   var mediaWrapperHeight = mediaWrapper.height();
   var mediaCoverWidth = $(this).width();
   var mediaCoverHeight = $(this).height();
   var maxCoverWidth;
   var maxCoverHeight;

   if (mediaCoverWidth > mediaWrapperWidth && mediaCoverHeight > mediaWrapperHeight) {

     if (mediaWrapperHeight/mediaWrapperWidth > mediaCoverHeight/mediaCoverWidth) {
       maxCoverWidth = '';
       maxCoverHeight = '100%';
     } else {
       maxCoverWidth = '100%';
       maxCoverHeight = '';
     } // end if

     adjustDimensions($(this), '', '', maxCoverWidth, maxCoverHeight);
   } else {
     adjustDimensions($(this), '100%', '100%', '', '');
   } // end if
 }); // end mediaCover.each
} // end function mediaCoverBounds

When calling it make sure to take care of page resizing:

mediaCoverBounds();

$(window).on('resize', function(){
  mediaCoverBounds();
});

Then the following CSS:

.media-cover-wrapper {
  position: relative;
  overflow: hidden;
}

.media-cover-wrapper .media-cover {
  position: absolute;
  z-index: -1;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

Yeah it may require jQuery but it responds quite well and acts exactly like background-size: cover and you can use it on image and/or videos to get that extra SEO value.

Face recognition Library

I would think Eigenface, which you are doing already, is the way to go if you want to calculate the distance between faces. You could try out different approaches like Support Vector Machine or Hidden Markov Model. I found a page that lists major algorithms that could be used for facial recognition: Face Recognition Homepage.

Also, when you say "better performance," do you mean speed or accuracy? What kind of problem are you having? How varying are the data? Are they mostly frontal face or do they include profiles?

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Try to enter the full-path of the dll. If it doesn't work, try to copy the dll into the system32 folder.

Spring - applicationContext.xml cannot be opened because it does not exist

enter image description here

I was struggling since a couple of hours for this issue because i was putting that file under resources folder but it didn't help me, finally i realized my mistake. Put it directly under src/main/java.

Changing image on hover with CSS/HTML

The problem with all the previous answers is that the hover image isn't loaded with the page so when the browser calls it, it takes time to load and the whole thing doesn't look really good.

What I do is that I put the original image and the hover image in 1 element and hide the hover image at first. Then at hover in I display the hover image and hide the old one, and at hover out I do the opposite.

HTML:

<span id="bellLogo" onmouseover="hvr(this, 'in')" onmouseleave="hvr(this, 'out')">
  <img src="stylesheets/images/bell.png" class=bell col="g">
  <img src="stylesheets/images/bell_hover.png" class=bell style="display:none" col="b">
</span>

JavaScript/jQuery:

function hvr(dom, action)
{
    if (action == 'in')
    {
        $(dom).find("[col=g]").css("display", "none");
        $(dom).find("[col=b]").css("display", "inline-block");
    }

    else
    {
        $(dom).find("[col=b]").css("display", "none");
        $(dom).find("[col=g]").css("display", "inline-block");
    }
}

This to me is the easiest and most efficient way to do it.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Microsoft itself posted a KB article about this, and that article has a service pack that they claim fixes the problem. See below.

http://support.microsoft.com/kb/959417/

It took a while for the associated update to install itself, but once it did, I was able to run the Visual Studio setup successfully from the Add/Remove Programs control panel.

SQL Server JOIN missing NULL values

Dirty and quick hack:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN Table2 ON Table1.Col1 = Table2.Col1
 AND ((Table1.Col2 = Table2.Col2) OR (Table1.Col2 IS NULL AND Table2.Col2 IS NULL))

How to increase icons size on Android Home Screen?

If you want to change settings in the launcher, change icon size, or grid size just hold down on an empty part of your home screen. Tap the three Dots and there you go.

From https://forums.oneplus.net/threads/how-to-change-icon-and-grid-size-trebuchet-settings.84820/

When configuring the phone for first time I saw something about a grid somewhere, but couldn't find it again. Luckily I found the answer on the link above.

Insert text with single quotes in PostgreSQL

This is so many worlds of bad, because your question implies that you probably have gaping SQL injection holes in your application.

You should be using parameterized statements. For Java, use PreparedStatement with placeholders. You say you don't want to use parameterised statements, but you don't explain why, and frankly it has to be a very good reason not to use them because they're the simplest, safest way to fix the problem you are trying to solve.

See Preventing SQL Injection in Java. Don't be Bobby's next victim.

There is no public function in PgJDBC for string quoting and escaping. That's partly because it might make it seem like a good idea.

There are built-in quoting functions quote_literal and quote_ident in PostgreSQL, but they are for PL/PgSQL functions that use EXECUTE. These days quote_literal is mostly obsoleted by EXECUTE ... USING, which is the parameterised version, because it's safer and easier. You cannot use them for the purpose you explain here, because they're server-side functions.


Imagine what happens if you get the value ');DROP SCHEMA public;-- from a malicious user. You'd produce:

insert into test values (1,'');DROP SCHEMA public;--');

which breaks down to two statements and a comment that gets ignored:

insert into test values (1,'');
DROP SCHEMA public;
--');

Whoops, there goes your database.

How to set corner radius of imageView?

Swift 3, Xcode 8, iOS 10

DispatchQueue.main.async {
  self.mainImageView.layer.cornerRadius = self.mainImageView.bounds.size.width / 2.0
  self.mainImageView.clipsToBounds = true
}

php $_GET and undefined index

I always use a utility function/class for reading from the $_GET and $_POST arrays to avoid having to always check the index exists... Something like this will do the trick.

class Input {
function get($name) {
    return isset($_GET[$name]) ? $_GET[$name] : null;
}

function post($name) {
    return isset($_POST[$name]) ? $_POST[$name] : null;
}

function get_post($name) {
    return $this->get($name) ? $this->get($name) : $this->post($name);
}
}
$input = new Input;
$page = $input->get_post('page');

Make Iframe to fit 100% of container's remaining height

It's right, you are showing an iframe with 100% height respect to its container: the body.

Try this:

<body>
  <div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
  <div style="width:100%; height:90%; background-color:transparent;">
    <iframe src="http: //www.google.com.tw" style="width:100%; height:100%;">
    </iframe> 
  </div>
</body>

Of course, change the height of the second div to the height you want.

How to change background and text colors in Sublime Text 3

Steps I followed for an overall dark theme including file browser:

  1. Goto Preferences->Theme...
  2. Choose Adaptive.sublime-theme

"Invalid signature file" when attempting to run a .jar

The solution listed here might provide a pointer.

Invalid signature file digest for Manifest main attributes

Bottom line :

It's probably best to keep the official jar as is and just add it as a dependency in the manifest file for your application jar file.

JQuery get all elements by class name

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:

var mvar = "";
$(".mbox").each(function() {
    console.log($(this).html());
    mvar += $(this).html();
});
console.log(mvar);

Two's Complement in Python

No, there is no builtin function that converts two's complement binary strings into decimals.

A simple user defined function that does this:

def two2dec(s):
  if s[0] == '1':
    return -1 * (int(''.join('1' if x == '0' else '0' for x in s), 2) + 1)
  else:
    return int(s, 2)

Note that this function doesn't take the bit width as parameter, instead positive input values have to be specified with one or more leading zero bits.

Examples:

In [2]: two2dec('1111')
Out[2]: -1

In [3]: two2dec('111111111111')
Out[3]: -1

In [4]: two2dec('0101')
Out[4]: 5

In [5]: two2dec('10000000')
Out[5]: -128

In [6]: two2dec('11111110')
Out[6]: -2

In [7]: two2dec('01111111')
Out[7]: 127

Calculate difference between two dates (number of days)?

The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:

(EndDate.Date - StartDate.Date).Days

Again assuming StartDate and EndDate are of type DateTime.

Group by with union mysql select query

This may be what your after:

SELECT Count(Owner_ID), Name
FROM (
    SELECT M.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Motorbike As M
    WHERE T.Type = 'Motorbike'
    AND O.Owner_ID = M.Owner_ID
    AND T.Type_ID = M.Motorbike_ID

    UNION ALL

    SELECT C.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Car As C
    WHERE T.Type = 'Car'
    AND O.Owner_ID = C.Owner_ID
    AND T.Type_ID = C.Car_ID
)
GROUP BY Owner_ID

Why are static variables considered evil?

The issue of 'Statics being evil' is more of an issue about global state. The appropriate time for a variable to be static, is if it does not ever have more than one state; IE tools that should be accessible by the entire framework and always return the same results for the same method calls are never 'evil' as statics. As to your comment:

I find static variables more convenient to use. And I presume that they are efficient too

Statics are the ideal and efficient choice for variables/classes that do not ever change.

The problem with global state is the inherent inconsistency that it can create. Documentation about unit tests often address this issue, since any time there is a global state that can be accessed by more than multiple unrelated objects, your unit tests will be incomplete, and not 'unit' grained. As mentioned in this article about global state and singletons, if object A and B are unrelated (as in one is not expressly given reference to another), then A should not be able to affect the state of B.

There are some exceptions to the ban global state in good code, such as the clock. Time is global, and--in some sense--it changes the state of objects without having a coded relationship.

Finding square root without using sqrt function?

This a very simple recursive approach.

double mySqrt(double v, double test) {
    if (abs(test * test - v) < 0.0001) {
        return test;
    }

    double highOrLow = v / test;
    return mySqrt(v, (test + highOrLow) / 2.0);
}
double mySqrt(double v) {
    return mySqrt(v, v/2.0);
}

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

Why is Maven downloading the maven-metadata.xml every time?

I haven't studied yet, when Maven does which look-up, but to get stable and reproducible builds, I strongly recommend not to access Maven Respositories directly but to use a Maven Repository Manager such as Nexus.

Here is the tutorial how to set up your settings file:

http://books.sonatype.com/nexus-book/reference/maven-sect-single-group.html

http://maven.apache.org/repository-management.html

JavaScript for detecting browser language preference

If you are using ASP .NET MVC and you want to get the Accepted-Languages header from JavaScript then here is a workaround example that does not involve any asynchronous requests.

In your .cshtml file, store the header securely in a div's data- attribute:

<div data-languages="@Json.Encode(HttpContext.Current.Request.UserLanguages)"></div>

Then your JavaScript code can access the info, e.g. using JQuery:

<script type="text/javascript">
$('[data-languages]').each(function () {
    var languages = $(this).data("languages");
    for (var i = 0; i < languages.length; i++) {
        var regex = /[-;]/;
        console.log(languages[i].split(regex)[0]);
    }
});
</script>

Of course you can use a similar approach with other server technologies as others have mentioned.

How to Compare two strings using a if in a stored procedure in sql server 2008?

declare @temp as varchar
  set @temp='Measure'
  if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Setting the focus to a text field

This is an easy one:

textField.setFocus();