text:
Q: What does "get" really mean in "I get you want to help"?
I get you want to help.

Does get in this context mean "know"? Or "understand"?

A: When you "get it", you understand something, therefore, in this context:

I get = I understand

A: In this case, "get" means to understand something said (or hinted) by someone else.
Normally, "get" means to receive something from another person: "I got your letter" means "I received the letter that you gave me.
Therefore, the sentence "I get you want to help" means "I received the information that you told (or implied to) me, which is that you want to help."


text:
Q: Continental Card Game probability So, in my family we play a card game called Continental, on each round one card is added to the initial cards until you are dealt 13 cards (the rules of the game are not important as my question is at the time the cards are dealt) we usually combine 3 decks (1 deck = 13 cards per suit x 4 suits + 2 jokers).
The other day while playing, my brother got all 3 heart-suit Aces available on this 13 cards stage, so we asked ourselves, what are the odds? and I've been trying to figure it out but my combinatorics are very basic. My attempt to resolve it was:
$$\frac{12×\binom{13}{1}}{\binom{158}{3}}$$
Any help with this will be very much appreciated.

A: As I understand it, you want to find the probability of having three $A\heartsuit$ in a thirteen card hand drawn from three standard decks. The number of such hands would be $\binom{159}{10}\approx 2.1\times 10^{15}$, since any hand with those three aces would be completed by $10$ cards from the remaining $3\times 54-3=159$ cards. The total number of possible hands is clearly $\binom{162}{13}\approx 5.2\times 10^{18}$. Therefore, the probability of drawing such a hand is
$$\frac{\binom{159}{10}}{\binom{162}{13}}\approx 0.000411203\approx 0.04\%,$$
which is roughly similar to the odds of getting drafted to the NBA... Good luck to your brother!

redpajama_set_name: RedPajamaStackExchange


text:
Q: No Audio recorded with FFMPEG ALSA Loopback I am trying to record screen with audio. I played an mp4 file with audio and video in browser and I tried the command specified here, and tried to save output to mp4 as well as mkv files. But the screen records with no audio. I have installed Alsa loopback with

sudo apt-get install linux-image-extra-virtual
modprobe snd-aloop

The outputs of arecord -l and aplay -l are arecord -l aplay -l
I have tried all hw devices like hw:0, hw:2, hw:0,1, hw:0,1,0
I am using Ubuntu 18.04 with FFMPEG version 4.0.3-1~18.04.york0
I have faced same issue with FFMPEG version 3.4.4-0ubuntu0.18.04.1
The same issue is also faced in Ubuntu 16.04 with FFMPEG version 4.0.3-1~16.04.york0.
Please help me solve this. I can not use any other packages like Simple-Screen-Recorder or PulseAudio, as the command which I am trying to run for an application uses only FFMPEG and Alsa Loopback, and is not changeable.

A: I was looking for an answer to record the alsa Loopback with ffmpeg.
This finally did the trick:
ffmpeg -f alsa -i hw:Loopback,1,0 rec.wav

I have to admit i use pavcontrol to send audio to the Loopback device.


text:
Q: Polygon border / border radius of a button I am trying to make polygon border shape like image below.

The code i have tried is below.

@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');

.p-button{
  background: transparent;
  text-decoration: none;
  background: #5344c6;
  color: white;
  padding: 15px 50px;
  border-radius: 27px;
  text-transform: uppercase;
  font-family: "Poppins";
  letter-spacing: 0.5px;
}

body{
  display: flex;
  height: 100vh;
  align-items: center;
  justify-content: center;

}
Explore The Tech

A: Use clip-path:

@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');

.p-button{
  background: transparent;
  text-decoration: none;
  background: #5344c6;
  color: white;
  padding: 15px 50px;
  text-transform: uppercase;
  font-family: "Poppins";
  font-size:40px;
  --h:45px; /* this is half the height, adjust it based on your code */
  clip-path:polygon(
    0 50%,
    calc(0.134*var(--h))  25%,   /* 0.134 = 1 - cos(30)   */
    calc(  0.5*var(--h))  6.7%,  /* 6.7% = 0.134/2 * 100% */
    var(--h) 0,
    calc(100% - var(--h)) 0,
    calc(100% - 0.5*var(--h))   6.7%,
    calc(100% - 0.134*var(--h)) 25%,
    100% 50%,
    calc(100% - 0.134*var(--h)) 75%,
    calc(100% - 0.5*var(--h))   93.3%, /* 93.3% = 100% - 6.7% */
    calc(100% - var(--h)) 100%,
    var(--h) 100%,
    calc(  0.5*var(--h))  93.3%,
    calc(0.134*var(--h))  75%);
}

body{
  display: flex;
  height: 100vh;
  align-items: center;
  justify-content: center;

}
Explore The Tech


text:
Q: How to get rid of skeleton line except contour? I want to get rid of the skeletonized lines except the contours using python.
And, want to extract only the largest contour.
(Actually, I tried to make skeletonized line from the segmented mask. And, I got the main stem with contour like above picture. Among the contours, I want to extract only the contour with largest area.)
I don't know how to do it.
Please help me if you have any idea.
Thanks in advance.

import os
import numpy as np
import cv2
from plantcv.plantcv import find_objects
from plantcv.plantcv import image_subtract
from plantcv.plantcv.morphology import segment_sort
from plantcv.plantcv.morphology import segment_skeleton
from plantcv.plantcv.morphology import _iterative_prune
from plantcv.plantcv import print_image
from plantcv.plantcv import plot_image
from plantcv.plantcv import params
from cv2.ximgproc import thinning

def find_large_contour(img, mask):
    params.device += 1
    mask1 = np.copy(mask)
    ori_img = np.copy(img)
    # If the reference image is grayscale convert it to color
    if len(np.shape(ori_img)) == 2:
        ori_img = cv2.cvtColor(ori_img, cv2.COLOR_GRAY2BGR)
    objects, hierarchy = cv2.findContours(mask1, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]
    for i, cnt in enumerate(objects):
        cv2.drawContours(ori_img, objects, i, (255, 102, 255), -1, lineType=8, hierarchy=hierarchy)
    if params.debug == 'print':
        print_image(ori_img, os.path.join(params.debug_outdir, str(params.device) + '_id_objects.png'))
    elif params.debug == 'plot':
        plot_image(ori_img)

    return objects, hierarchy, ori_img

def prune(skel_img, size=2, mask=None):

    # Store debug
    debug = params.debug
    params.debug = None

    pruned_img = skel_img.copy()

    # Check to see if the skeleton has multiple objects
    skel_objects, _ = find_objects(skel_img, skel_img)

    _, objects = segment_skeleton(skel_img)
    kept_segments = []
    removed_segments = []

    if size > 0:
        # If size>0 then check for segments that are smaller than size pixels long

        # Sort through segments since we don't want to remove primary segments
        secondary_objects, primary_objects = segment_sort(skel_img, objects)

        # Keep segments longer than specified size
        for i in range(0, len(secondary_objects)):
            if len(secondary_objects[i]) > size:
                kept_segments.append(secondary_objects[i])
            else:
                removed_segments.append(secondary_objects[i])

        # Draw the contours that got removed
        removed_barbs = np.zeros(skel_img.shape[:2], np.uint8)
        cv2.drawContours(removed_barbs, removed_segments, -1, 255, 1,
                         lineType=8)

        # Subtract all short segments from the skeleton image
        pruned_img = image_subtract(pruned_img, removed_barbs)
        pruned_contour_img = image_subtract(pruned_img, removed_barbs)
        pruned_img = _iterative_prune(pruned_img, 1)

    # Reset debug mode
    params.debug = debug

    # Make debugging image
    if mask is None:
        pruned_plot = np.zeros(skel_img.shape[:2], np.uint8)
    else:
        pruned_plot = mask.copy()
    pruned_plot = cv2.cvtColor(pruned_plot, cv2.COLOR_GRAY2RGB)
    pruned_obj, pruned_hierarchy, large_contour = find_large_contour(pruned_img, pruned_img)
    cv2.drawContours(pruned_plot, removed_segments, -1, (0, 0, 255), params.line_thickness, lineType=8)
    cv2.drawContours(pruned_plot, pruned_obj, -1, (150, 150, 150), params.line_thickness, lineType=8)

    # Auto-increment device
    params.device += 1

    if params.debug == 'print':
        print_image(pruned_img, os.path.join(params.debug_outdir, str(params.device) + '_pruned.png'))
        print_image(pruned_plot, os.path.join(params.debug_outdir, str(params.device) + '_pruned_debug.png'))

    elif params.debug == 'plot':
        plot_image(pruned_img, cmap='gray')
        plot_image(pruned_plot)

    # Segment the pruned skeleton
    segmented_img, segment_objects = segment_skeleton(pruned_img, mask)

    return pruned_img, segmented_img, segment_objects, large_contour

vseg = cv2.imread("vseg.png", cv2.IMREAD_GRAYSCALE)
gray = thinning(vseg, thinningType=cv2.ximgproc.THINNING_GUOHALL)
pruned, seg_img, edge_objects, large_contour = prune(skel_img=gray, size=3, mask=vseg)

img_cont_gray = cv2.cvtColor(large_contour, cv2.COLOR_BGR2GRAY)

ret_cont, thresh_cont = cv2.threshold(img_cont_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

cv2.imwrite("first_cont111.png", thresh_cont)

## then I want to extract the only contour with largest area

A: Use morphology as  the first step
ret,thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
rect=cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, rect)

Then find the  conneсted component of maximal area
max_component=np.full(opening.shape, 0, np.uint8)
nb_components,labels,stats,centroids= cv2.connectedComponentsWithStats(opening,8)
max_component[labels == np.argmax(stats[1:, -1])+1]=255

A: using skimage (if you don't have it: conda install scikit-image)
import scipy.ndimage as ndi
from skimage.morphology import binary_erosion, binary_dilation
from skimage.measure import regionprops
from skimage import io
#
img = io.imread("first_cont111.png") > 0 # open image and ensure 0,1 data

# get rid of 1-pixel lines
img = binary_erosion(img)
img = binary_dilation(img)

# find individual objects and give them unique labels
label_img, _ = ndi.label(img)

props = regionprops(label_img)

# find the label that corresponds to the object with maximum area:
objects = sorted([(p.label, p.area) for p in props], key=lambda x: x[1], reverse=True)
obj = objects[0][0]

# make an image of the same size as the input image:
output_img = np.zeros_like(img)

# and use fancy indexing to copy the largest object
output_img[label_img==obj] = 1

# now make the contour by subtracting the eroded shape
output_img = output_img - binary_erosion(output_image)


text:
Q: Adding grouping in framing clause window while creating partitions Using the dataset hosted on Google (MBL Data) as an example, here is what I am accomplishing to do - obtain last 3 weeks score run for a given Venue.
My aggregated dataset looks like this without the strikes_3wk column -

Logic for strikes_3wk column is to partition the aggregated dataset by venueName, order by YearWeek column and then obtain the last 3 weeks aggregated strikes data.
Here is the query I have written so far. I see that the windowing function is where I need to modify the logic. So, is there a way to add grouping within the windowing function? Is there any alternative way of doing this?
In the image I added a new column 'expected', showing values for two weeks.
select inr.*
       ,sum(inr.strikes) over (Venue_Week rows between current row and 2 following) as strikes_3wk
from
(
    select seasonType
        ,gameStatus
        ,homeTeamName
        ,awayTeamName
        ,venueName
        ,CAST(
        CONCAT(
            CAST(EXTRACT(YEAR FROM createdAt) as string)
            ,CAST(EXTRACT(WEEK(Monday) FROM createdAt) as string)
            ) as INT64)
            as YearWeek
        ,sum(homeFinalRuns) as homeFinalRuns
        ,sum(strikes) as strikes
    from  `bigquery-public-data.baseball.games_wide`
    where   createdAt is not null
    group by seasonType
        ,gameStatus
        ,homeTeamName
        ,awayTeamName
        ,venueName
        ,YearWeek
)inr
window Venue_Week as (
    partition by inr.venueName
    order by inr.YearWeek desc
)

A: So you are looking for strikes per venue regardless of who did them, right?
May be something like:
SELECT INR.*, STATS.strikes_3wk
FROM `bigquery-public-data.baseball.games_wide` INR
  LEFT JOIN (
    SELECT venueName, SUM(strikes) as strikes_3wk
    FROM `bigquery-public-data.baseball.games_wide` INR2
    WHERE YearWeek IN (
      SELECT TOP 3 YearWeek
      FROM `bigquery-public-data.baseball.games_wide`
      WHERE venueName = INR2.venueName
      ORDER BY YearWeek DESC
    )
    GROUP BY venueName
  ) STATS
    ON INR.venueName = STATS.venueName


text:
Q: How to do a dplyr inner_join col1 > col2 I am having difficulty with getting dplyr joins to work when I am not using the standard "col1" = "col2" join. Here are two examples of what I am experiencing.
Firstly:
library(dplyr)

tableA <- data.frame(col1= c("a","b","c","d"),
                     col2 = c(1,2,3,4))

inner_join(tableA, tableA, by = c("col1"!="col1")) %>%
  select(col1, col2.x) %>%
  arrange(col1, col2.x)

Error: by must be a (named) character vector, list, or NULL for
  natural joins (not recommended in production code), not logical

When I replicate this code but using sql I get the following:
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")

copy_to(con, tableA)

tbl(con, sql("select a.col1, b.col2
              from
              tableA as a
              inner join
              tableA as b
              on a.col1 <> b.col1")) %>%
  arrange(col1, col2)

Results from sql query:
# Source:     SQL [?? x 2]
# Database:   sqlite 3.19.3 [:memory:]
# Ordered by: col1, col2
     col1  col2
     <chr> <dbl>
 1     a     2
 2     a     3
 3     a     4
 4     b     1
 5     b     3
 6     b     4
 7     c     1
 8     c     2
 9     c     4
10     d     1
# ... with more rows

Second part is similar to the last:
inner_join(tableA, tableA, by = c("col1" > "col1")) %>%
   select(col1, col2.x) %>%
   arrange(col1, col2.x)

Error: by must be a (named) character vector, list, or NULL for
  natural joins (not recommended in production code), not logical

Sql equivalent:
tbl(con, sql("select a.col1, b.col2
              from tableA as a
              inner join tableA as b
              on a.col1 > b.col1")) %>%
   arrange(col1, col2)

Results from second sql query:
# Source:     SQL [?? x 2]
# Database:   sqlite 3.19.3 [:memory:]
# Ordered by: col1, col2
   col1  col2
  <chr> <dbl>
1     b     1
2     c     1
3     c     2
4     d     1
5     d     2
6     d     3

Does anyone know how to create these sql examples but using dplyr code?

A: For your first case:
library(dplyr)
library(tidyr)

expand(tableA, col1, col2) %>%
  left_join(tableA, by = 'col1') %>%
  filter(col2.x != col2.y) %>%
  select(col1, col2 = col2.x)

The result:
# A tibble: 12 x 2
     col1  col2
   <fctr> <dbl>
 1      a     2
 2      a     3
 3      a     4
 4      b     1
 5      b     3
 6      b     4
 7      c     1
 8      c     2
 9      c     4
10      d     1
11      d     2
12      d     3

For your second case:
expand(tableA, col1, col2) %>%
  left_join(tableA, by = 'col1') %>%
  filter(col2.x < col2.y) %>%
  select(col1, col2 = col2.x)

The result:
# A tibble: 6 x 2
    col1  col2
  <fctr> <dbl>
1      b     1
2      c     1
3      c     2
4      d     1
5      d     2
6      d     3

A: A solution using dplyr and tidyr. The idea is to expand the data frame and then perform join to the original data frame. After that, use fill from tidyr to fill in NA to previous records. Finally, filter out records with the same values and NA.
library(dplyr)
library(tidyr)

tableB <- tableA %>%
  complete(col1, col2) %>%
  left_join(tableA %>% mutate(col3 = col2), by = c("col1", "col2")) %>%
  group_by(col1) %>%
  fill(col3, .direction = "up") %>%
  filter(col2 != col3, !is.na(col3)) %>%
  select(-col3) %>%
  ungroup()
tableB
# # A tibble: 6 x 2
#    col1  col2
#   <chr> <dbl>
# 1     b     1
# 2     c     1
# 3     c     2
# 4     d     1
# 5     d     2
# 6     d     3

DATA
tableA <- data.frame(col1= c("a","b","c","d"),
                     col2 = c(1,2,3,4), stringsAsFactors = FALSE)


text:
Q: convert an std::string to a Swift String Short version:
how can I convert an std::string (object returned by a .cpp function called from a .Swift file using bridging) to a Swift String?
Long version:
I have a library written in C++ and I have to call some code using Swift. I created a bridge, adding two files in my Xcode projects:
a bridging header, which allows Swift to call C functions (afaik Swift can't call C++ functions directly, so it needs to pass through C functions)
//file bridgingHeader.h
const char * getLastOpenedFile();

and a .cpp files which can call (of course) C++ functions inside and can define C functions with extern "C"
//file wrapper.cpp
#include <string>
#include "my_library.hpp"

extern "C" const char * getStringFromLibrary()
{
    const char * s = get_string_from_library().c_str();
    return s;
}

I can access the return value from a .swift file using
let myString = String(cString: getStringFromLibrary())
Swift.print(myString)

Placing a breakpoint to check the value of s inside the function getStringFromLibrary() I can see the content of the string, so the function from the library is correctly called.
Anyway the .swift file prints some strange symbols and not the original string.
Changing getStringFromLibrary() to be the following
extern "C" const char * getStringFromLibrary()
{
    return get_string_from_library().c_str();
}

I have as a consequence that the .swift code prints a prefix of the real string. This makes me think of a problem of memory: probably when getStringFromLibrary() exits, the std::string object returned by get_string_from_library() is destroyed, and so the memory pointed by the pointer returned with .c_str() is not reliable anymore, reason why I get wrong outputs from Swift.print().
What is the correct way to access an std::string from a .swift file and then release its memory?

A: You can write an Objective-C++ wrapper to work with C++ codes.
bridging header:
#include "Wrapper.hpp"

Wrapper.hpp:
#ifndef Wrapper_hpp
#define Wrapper_hpp

#import <Foundation/Foundation.h>

#if defined(__cplusplus)
extern "C" {
#endif
    NSString * _Nonnull getStringFromLibrary();
#if defined(__cplusplus)
}
#endif

#endif /* Wrapper_hpp */

Wrapper.mm:
#include "Wrapper.hpp"

#include <string>
#include "my_library.hpp"

NSString * _Nonnull getStringFromLibrary() {
    return [NSString stringWithUTF8String:get_string_from_library().c_str()];
}

Swift code:
print(getStringFromLibrary())

[NSString stringWithUTF8String:] copies the contents of the buffer into some internal storage and ARC manages freeing it. You have no need to define free_something().

A: The std::string object owns the buffer to which a pointer is returned via c_str.  That means that getStringFromLibrary returns a pointer to nothing.
There are several ways you could avoid that:
1) Copy the contents of the buffer somewhere long-lived, and return a pointer to that.  This usually means allocating some memory via new[] or malloc:
extern "C"
{

const char* getStringFromLibrary()
{
    std::string str = get_string_from_library();
    char* s = new char[str.size() + 1]{};
    std::copy(str.begin(), str.end(), s);
    return s;
}

void freeStringFromLibrary(char* s)
{
    delete[] s;
}

}

This method is simple, but it does incur the cost of an extra copy.  That may or may not be relevant depending on how big str is and how often getStringFromLibrary is called.  It also requires the user to deal with resource management, so it's not particularly exception-safe.
2) Return a opaque "handle" to a std::string object and let swift access its underlying buffer and free it by different functions:
extern "C"
{

void* getStringFromLibrary()
{
    std::string* s = new std::string(get_string_from_library());
    return s;
}

const char* libraryGetCString(void* s)
{
    return static_cast<std::string*>(s)->c_str();
}

void freeStringFromLibrary(void* s)
{
    delete static_cast<std::string*>(s);
}

}

Now in swift you can do something like this:
let handle: UnsafeMutablePointer<COpaquePointer> = getStringFromLibrary()
let myString = String(cString: libraryGetCString(handle))
freeStringFromLibrary(handle)

This approach eliminates the extra copy, but it's still not exception-safe since the caller has to deal with resource management.
There's likely a way to mix Objective-C++ into the solution to avoid the issue with resource management, but sadly I'm not familiar enough with Swift or Objective-C++ to tell you what that solution looks like.

A: I define a function (it could be a static String extension, if you prefer):
func getStringAndFree(_ cString: UnsafePointer<Int8>) -> String {
    let res = String(cString: cString)
    cString.deallocate()
    return res
}

and in C++,
extern "C" char *getStringFromLibrary()
{
    return strdup(get_string_from_library().c_str());
}

Now in Swift, I can simply use this in a fire-and-forget way:
print("String from C++ is: " + getStringAndFree(getStringFromLibrary()))

A: I solved, I post the solution I ended up with.
In the future I will probably write a class which will allow me to manage the delete operation in an automatic an safer way. I will update the answer.
bridging header:
//file bridgingHeader.h
char * getStringFromLibrary();
void freeString(char * string);

wrapper:
char * std_string_to_c_string(std::string s0) {
    size_t length = s0.length() + 1;
    char * s1 = new char [length];
    std::strcpy(s1, s0.c_str());
    return s1;
}

extern "C" void freeString(char * string) {
    delete [] string;
}

extern "C" char * getStringFromLibrary()
{
    return std_string_to_c_string(get_string_from_library().c_str());
}

Swift code:
let c_string: UnsafeMutablePointer<Int8>! = getStringFromLibrary()
let myString = String(cString: c_string)
freeString(c_string)

Swift.print(myString)


text:
Q: How do you measure soil moisture using a capacitive sensor? There are a number of capacitive moisture sensor designs on the internet, which use the insulated copper pads on a PCB.For example:
http://zerocharactersleft.blogspot.in/2011/11/pcb-as-capacitive-soil-moisture-sensor.html
In case the above link breaks, here is a photo of a PCB I made using the above design:

Just wondering how these work, and how they can be used with a microcontroller to calculate moisture content? I have seen methods that use a square wave, an RC network, and an ADC to do this, but I haven't seen a clear explanation of how it works.

A: It's called capacitive because the two copper planes in your sensor are the two plates of a capacitor. In a physics textbook these two plates might be drawn facing one another, with empty space in between. Put a material between the plates, and the capacitance, which is a measure of how much charge is on the plates for a given voltage, changes. This material is called the dielectric, and how much the capacitance changes for a given material is called the dielectric constant of the material.
Dry soil has a different dielectric constant than wet soil, which means that a sensor in wet soil is going to have a different capacitance than one in dry soil.
How do we measure this capacitance? One way is to use an RC circuit, and to measure the voltage on the positive terminal of the capacitor. This terminal is going to reach 63.2% of its maximum voltage \$RC\$ seconds after a voltage is applied, where \$R\$ is the resistance and \$C\$ is the capacitance. By turning on the supply voltage at a time \$t_{on}\$, checking the voltage on the positive terminal of the capacitor continuously until it exceeds 63.2% of the supply voltage, and recording the first time where that voltage was exceeded \$t_{c}\$, we can calculate the capacitance (we know the resistor value because we chose it).
That is,
C = \$(t_{on}-t_c)/R\$
This tutorial will show you how to set something like this up on an Arduino.
https://www.arduino.cc/en/Tutorial/CapacitanceMeter

A: The sensing strips have alternating A and B zones the A zones form one plate of the capacitor the B zones form the other. the coating on the circuit board and the earth surrounding the sensor forms the dielectric.
when the earth is dry it has high electrical resistance, when it is damp is has lower resistance this partially short-circuits the dielectric of the capacitor increasing its capacitance.
reading the sensor is typically done by charging the capacitor and then timing the discharge. one way to measure the charge time using a microcontroller is to
connect it to a timer capture pin, drive the pin low to discharge it, then turn the pin into an input with internal pull-up and enable the timer to measure how many cycles it takes to charge up.

A: For those still interested of a possible answer, see "Automatic watering system with capacitive probe and Arduino on the cheap" on instructables.com for one such method.
Essentially, a NE555 astable using the capacitance probe as the charge/discharge capacitor, thus translating the changes of humidity in changes of frequency. An Arduino used to count the number of pulses in a time interval and implement (in that case) the watering logic.


text:
Q: LifecycleException deploying Spring Boot WebSocket example into Tomcat After successfully running through the Spring getting started guide for WebSocket, I want desperately to build this application as a WAR and deploy it into Tomcat.  I have done my best to modify the project to build as a WAR file by following the Spring getting started guide for converting a Spring Boot JAR to a WAR, but when I deploy the resulting WAR, Tomcat throws an exception.
I'm developing using STS 3.4.0 with Gradle 1.10 (I switched to this after previously failing to successfully deploy when building with Maven in Eclipse).  Gradle reports a successfully built WAR file, but when I attempt to deploy it into Tomcat, the following exception is thrown:
09-Feb-2014 17:30:27.537 SEVERE [localhost-startStop-3] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/gs-messaging-stomp-websocket-0.1.0]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:702)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:699)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1763)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration$TomcatWebSocketConfiguration.class]: Initialization of bean failed; nested exception is java.lang.ArrayStoreException: org.apache.catalina.valves.RemoteIpValve
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:129)
    at org.springframework.boot.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:90)
    at org.springframework.boot.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:53)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:181)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5237)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 10 more
Caused by: java.lang.ArrayStoreException: org.apache.catalina.valves.RemoteIpValve
    at org.springframework.boot.autoconfigure.web.ServerProperties$Tomcat.customizeTomcat(ServerProperties.java:212)
    at org.springframework.boot.autoconfigure.web.ServerProperties.customize(ServerProperties.java:117)
    at org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizerBeanPostProcessor.postProcessBeforeInitialization(EmbeddedServletContainerCustomizerBeanPostProcessor.java:68)
    at org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizerBeanPostProcessor.postProcessBeforeInitialization(EmbeddedServletContainerCustomizerBeanPostProcessor.java:54)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    ... 27 more

I'm running Tomcat 8.0.0-RC10 on Windows 8.1 64-bit.  I believe the relevant application files are these:
Application.java:
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

HelloWebXml.java (in lieu of an actual web.xml):
package hello;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.SpringBootServletInitializer;

public class HelloWebXml extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

and finally, build.gradle:
buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-snapshot" }
        mavenLocal()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.0.RC1")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'

war {
    baseName = 'gs-messaging-stomp-websocket'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:0.5.0.BUILD-SNAPSHOT")
    compile("org.springframework.boot:spring-boot-starter-websocket:0.5.0.BUILD-SNAPSHOT")
    compile("org.springframework:spring-messaging:4.0.0.RELEASE")
    compile("com.fasterxml.jackson.core:jackson-databind")
    testCompile("junit:junit:4.11")
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.10'
}

I must say, I find it ironic and more than a little frustrating that the problem seem to lie with the tomcatEmbeddedServletContainerFactory.  Thus a feature whose sole purpose (I believe) is to allow the app to be run OUTSIDE of a servlet container --- a feature in which I have absolutely no interest --- is preventing me from properly deploying an app INTO a servlet container.
All help will be appreciated.

A: With the help of Mr. Syer's answer (sorry, I tried to upvote, but I'm too new to this forum), along with information from this post about how to mark a resource as 'provided', I finally got this building as a war which I can successfully deploy in Tomcat.
After a bit of experimentation, it appears that what is needed is to make the following changes to my build.gradle:
configurations {
    provided
}

sourceSets {
    main.compileClasspath += configurations.provided
    test.compileClasspath += configurations.provided
    test.runtimeClasspath += configurations.provided
}

eclipse.classpath.plusConfigurations += configurations.provided

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:0.5.0.BUILD-SNAPSHOT") {
        exclude module: 'spring-boot-starter-tomcat'
    }
    compile("org.springframework.boot:spring-boot-starter-websocket:0.5.0.BUILD-SNAPSHOT") {
        exclude module: 'spring-boot-starter-tomcat'
    }

    provided group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '0.5.0.BUILD-SNAPSHOT'

    compile("org.springframework:spring-messaging:4.0.0.RELEASE")
    compile("com.fasterxml.jackson.core:jackson-databind")
    testCompile("junit:junit:4.11")
}

When I applied only the 'exclude module' changes, I got a compile-time error complaining that "class file for javax.servlet.ServletException not found" --- which confuses me, since I believe that is part of my Java 7 JDK.
When I applied only the 'provided group' change, it didn't actually remove the spring-boot-starter-tomcat jar(s) from my war.

A: You need to make the embedded tomcat dependency "provided" (right now you have spring-boot-starter-tomcat in the "compile" configuration, transitively through spring-boot-starter-web). If you really have no use for an embedded server you can remove it completely. Gradle has standard idioms for excluding transitive dependencies, and for adding them in different configurations, I believe.


text:
Q: jquery Datepicker date range, wont shows years/months outside of it Currently I have a datepicker that sets a range of dates using minDate and maxDate, however the date picker will only let me see the dates within those ranges. If for example the min/max was 2017-2018, it won't let me view 2019 dates or 2016 dates.
I have tried yearRange but this has no effect.


text:
Q: how to group xsd:elements of an xsd:choice together and outsource them? I'm working with XSD and I have a xsd:choice with many xsd:elements in it. Now I want to simplify it a little bit and therefore I've grouped the xsd:elements, so that I can outsource (and reuse) them in separate xsd:elements.
Before:
<!-- main.xsd -->
<xsd:element name="account">
    <xsd:complexType>
        <xsd:choice>
            <xsd:element name="login-id" type="xsd:string" />
            <xsd:element name="login-username" type="xsd:string" />
            <xsd:element name="login-password" type="xsd:string" />
            <xsd:element name="login-note" type="xsd:string" />

            <xsd:element name="contact-name" type="xsd:string" />
            <xsd:element name="contact-address" type="xsd:string" />
            <xsd:element name="contact-phone" type="xsd:string" />
            <xsd:element name="contact-note" type="xsd:string" />
        </xsd:choice>
    </xsd:complexType>
</xsd:element>

After:
<!-- main.xsd -->
<xsd:include schemaLocation="outsourced.xsd" />

<xsd:element name="account">
    <xsd:complexType>
       <xsd:choice>
           <xsd:element ref="login" />

           <xsd:element ref="contact" />
        </xsd:choice>
    </xsd:complexType>
</xsd:element>

<!-- outsourced.xsd -->
<xsd:element name="login">
    <xsd:complexType>
        <xsd:choice>
            <xsd:element name="login-id" type="xsd:string" />
            <xsd:element name="login-username" type="xsd:string" />
            <xsd:element name="login-password" type="xsd:string" />
            <xsd:element name="login-note" type="xsd:string" />
        </xsd:choice>
    </xsd:complexType>
</xsd:element>

<xsd:element name="contact">
    <xsd:complexType>
        <xsd:choice>
            <xsd:element name="contact-name" type="xsd:string" />
            <xsd:element name="contact-address" type="xsd:string" />
            <xsd:element name="contact-phone" type="xsd:string" />
            <xsd:element name="contact-note" type="xsd:string" />
        </xsd:choice>
    </xsd:complexType>
</xsd:element>

Sadly this creates a new Classes 'login' and 'contact' when generating Java-Source from it, what I want to avoid. Is there any way to outsource the grouped xsd:elements to simplify the xsd:choice?

A: I'm not sure exactly what you're looking for, but it should be one of the following:

*

*you either want to simplify the name of the generated field so instead of n1n2n3 you get something more readable; in this case I suggest to go with this solution presented here

*I suggest you to read Blaise's blog here and here - it should help understand your solution or at least how to better formulate your question.

UPDATE: Ok, what you need to do is to wrap those two groups of xsd:elements with an xsd:sequence and then play with the bindings file to get what you want (I assume you're using JAXB).
UPDATE 2: So it sounds like you are using JAXB. Then if you take the schema below, I believe it gives you what you want, reuse (by referencing model groups) and no new classes. I'll post both artifacts but I suggest you also try it (I've used NetBeans) to see what's going on (also write a test client in Java that uses the class, look at what a developer will see, etc.)  and if it is still not what you want, use the results of your attempt to illustrate some more your question.
XSD:
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XMLSchema.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="account">
        <xsd:complexType>
            <xsd:choice>
                <xsd:group ref="login"/>
                <xsd:group ref="contact"/>
            </xsd:choice>
        </xsd:complexType>
    </xsd:element>

    <xsd:group name="login">
        <xsd:sequence>
            <xsd:element name="login-id" type="xsd:string"/>
            <xsd:element name="login-username" type="xsd:string"/>
            <xsd:element name="login-password" type="xsd:string"/>
            <xsd:element name="login-note" type="xsd:string"/>
        </xsd:sequence>

    </xsd:group>

    <xsd:group name="contact">
        <xsd:sequence>
            <xsd:element name="contact-name" type="xsd:string"/>
            <xsd:element name="contact-address" type="xsd:string"/>
            <xsd:element name="contact-phone" type="xsd:string"/>
            <xsd:element name="contact-note" type="xsd:string"/>
        </xsd:sequence>
    </xsd:group>
</xsd:schema>

Java Generated class (default, no custom bindings, removed irrelevant content):
package sequnderchoice;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "loginId",
    "loginUsername",
    "loginPassword",
    "loginNote",
    "contactName",
    "contactAddress",
    "contactPhone",
    "contactNote"
})
@XmlRootElement(name = "account")
public class Account {

    @XmlElement(name = "login-id")
    protected String loginId;
    @XmlElement(name = "login-username")
    protected String loginUsername;
    @XmlElement(name = "login-password")
    protected String loginPassword;
    @XmlElement(name = "login-note")
    protected String loginNote;
    @XmlElement(name = "contact-name")
    protected String contactName;
    @XmlElement(name = "contact-address")
    protected String contactAddress;
    @XmlElement(name = "contact-phone")
    protected String contactPhone;
    @XmlElement(name = "contact-note")
    protected String contactNote;

    public String getLoginId() {
        return loginId;
    }

    public void setLoginId(String value) {
        this.loginId = value;
    }

    public String getLoginUsername() {
        return loginUsername;
    }

    public void setLoginUsername(String value) {
        this.loginUsername = value;
    }

    public String getLoginPassword() {
        return loginPassword;
    }

    public void setLoginPassword(String value) {
        this.loginPassword = value;
    }

    public String getLoginNote() {
        return loginNote;
    }

    public void setLoginNote(String value) {
        this.loginNote = value;
    }

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String value) {
        this.contactName = value;
    }

    public String getContactAddress() {
        return contactAddress;
    }

    public void setContactAddress(String value) {
        this.contactAddress = value;
    }

    public String getContactPhone() {
        return contactPhone;
    }

    public void setContactPhone(String value) {
        this.contactPhone = value;
    }

    public String getContactNote() {
        return contactNote;
    }

    public void setContactNote(String value) {
        this.contactNote = value;
    }
}


text:
Q: How to restore previous colormap in matlab? I have some images in some range of numbers. Here's an example of an image:

This is a level in a Laplacian Pyramid of an image. (It's not necessary to understand what a Laplacian Pyramid is...)
Now I need to make some operations on those images, and I need to change the colormap for that. I changed it to gray(256) and made the operations i need. So now I have different images in colormap(gray(256)).
Now I need to scale back to the previous range. But I don't know the previous range or colormap. I tried saving the colormap before the operations.
I tried this:
imwrite(img,colormap(gray(256)),str);

but that changed the whole matrix to 255.
What's the right way to do it?

A: imwrite(img,colormap(gray(256)),str);

colormap only sets the color of a figure, so you don't need it in imwrite.  In fact, it does nothing of value here.  If you pass a map, gray(256), it will write this as an indexed image.  That is, it saves in the file both the values of the pixels and the map which says what those values mean.
However, it doesn't scale the input image to match the colormap neatly.  As stated in the docs:

If A is an indexed image of data type double or single, then imwrite
  converts the indices to zero-based indices by subtracting 1 from each
  element, and then writes the data as uint8. If the data in A is
  single, convert A to double before writing to a GIF or TIFF file.

What this means is if your img contains all values of 256 or above, imwrite will subtract one, and write as uint8, clipping values over 255 to 255 (and below 0 to 0).  So your image appears as all 255.
You need to first scale img to an appropriate range (e.g. record the max and min values of your input matrix - not the colormap! - before you do anything to it).  This is just math - e.g. something like img = img/256 may be all you need.  It is unnecessary to save it with a map in most cases - you're just writing your values as grayscale, you can save them with imwrite into a normal image.
imwrite generally expects double to be in the range of 0 to 1 and uint8 in the range of 0 to 255. If your values don't match up to this, you will get clipping/"blank" images, etc.
However, because values are stored as integers (uint8) in most image formats, I don't see how you can use imwrite to save the sort of values you display in your example without losing precision.  You also won't be able to save any negative values.  So it would be best to save your real values in a different format (*.mat file, csv, etc.) and save an image if you need it for visualisation, but not for storing calculated values.


text:
Q: manipulating the css in Wordpress blog I am developing the following wordpress blog to put into my site: http://moreformymac.com/blog/ I am new to CSS and HTML so making the wordpress blog match my website is taking all of my knowledge and then some.  for the life of me I can't find the css responsible for causing the main grey transparent content box to run into my navigation bar.  I just want to move the main content box down 50 px or so.

A: In your style.css,  line 1745
body .site {
padding: 0 40px;
padding: 0 2.857142857rem;
margin-top: 48px;
margin-top: 3.428571rem;
margin-bottom: 48px;
margin-bottom: 3.428571429rem;
box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3);

adjsut the "margin-top" entries. (the first is for older browsers, the second for newer browsers)


text:
Q: Failed writing received data to disk/application on libcurl I'm using VC++ 2015 (v140) with QT MSVC 2015. My project is 32-bit(x86) and libcurl is compiled as is, I mean I just downloaded from official website and compiled it, no OpenSSL or other fancy extensions were added.
The code I'm trying to run is here:
#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <string>

class Essentials {
private:
    CURL *curl;
    CURLcode res;

public:
    std::string SSLInternetConnection(char* url) {
        curl = curl_easy_init();
        if (curl) {
            curl_easy_setopt(curl, CURLOPT_URL, "http://google.com");
            curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
            res = curl_easy_perform(curl);
            curl_easy_cleanup(curl);
            if (res == CURLE_OK) {
                return "CONNECTED";
            }
            else {
                fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
                return curl_easy_strerror(res);
            }
        }
    }
};

I'm calling it from a function that creates a dialog, and I'm writing the result to the label in the dialog.
#include <QtWidgets/QDialog>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <DH_loginView.h>
#include <chrono>
#include <thread>
#include "Essentials.cpp"

class Dialogs {
    public:
        void loginDialog(const QString uname, QMainWindow *a) { // this function is where I'm calling the curl lib.
            Ui::loginView loginViewer;
            loginViewer.setupUi(a);
            Essentials e;
            std::string asd = e.SSLInternetConnection("http://google.com/");
            QString aaa = QString::fromStdString(asd);
            loginViewer.label->setText(aaa);
            //QString utf8Dialog = uname + QStringLiteral(" kullanıcısı giriş yapıyor");
            a->setWindowTitle(aaa);
        }
        void loginErr1() {
            QMessageBox mbox;
            QSpacerItem* horizontalSpacer = new QSpacerItem(500, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
            mbox.setWindowTitle("HATA");
            QGridLayout* layout = (QGridLayout*)mbox.layout();
            layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());
            mbox.setText(QStringLiteral("Kullanıcı adı ve şifre boş olamaz!"));
            mbox.exec();
        }
};

And the issue is, http://google.com is reachable on every app on my PC. However, I used to have "Couldn''t resolve hostname" error for a while, and when I turned on my PC today, it was throwing a different error.  I have no idea why is this happening, because I'm working with curl on php for years and I acknowledge that this issue is out of my knowledge, since I'm newbie on C++.

Thank you for your help!


text:
Q: PgJDBC: "no suitable driver found" when following tutorial, why? I'm writing a Java program that queries a PostgreSQL database. I'm following this example and have trouble here:
        connection = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/testdb", "mkyong",
                "123456");

According to the JavaDoc for DriverManager the first string is "a database url of the form jdbc:subprotocol:subname. When I connect to the server I type in psql -h dataserv.abc.company.com -d app -U emp24 and give the password qwe123 (for example sake). What should the first argument of getConnection be?
I've tried
connection = DriverManager.getConnection(
                    "jdbc:postgresql://dataserv.abc.company.com",  "emp24",
                    "qwe123");

and get the run time error: no suitable driver found.
I've download JDBC4 Postgresql Driver, Version 9.2-1000.

After I fixed my program to load the driver with Class.forName("org.postgresql.Driver"); it recognises the JDBC URL but it still doesn't connect. I now have a new error.
When I run the program there is an error and here is the output with the stack trace:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
Connection Failed! Check output consoleorg.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:207)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
    at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:140)
    at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
    at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
    at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
    at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:23)
    at org.postgresql.Driver.makeConnection(Driver.java:393)
    at org.postgresql.Driver.connect(Driver.java:267)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at DatabaseConnect.main(DatabaseConnect.java:32)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at org.postgresql.core.PGStream.<init>(PGStream.java:60)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:101)
    ... 11 more

I format the URL for the getConnection like this:
"jdbc:postgresql://dataserv.abc.company.com:5432/app"

A: Most likely you have failed to register the JDBC driver with the DriverManager, so JDBC doesn't know how to handle jdbc:postgresql:. Try Class.forName("org.postgresql.Driver"); before you try to use DriverManager.getConnection. That is shown in the example code you linked to (it's the very first line), is explained in the preamble of the DriverManager documentation, and is also explained in detail in the PgJDBC documentation linked below.
Alternately, maybe you've typo'd jdbc:postgresql: so the DriverManager is looking for a driver named postgrsql or Postgresql or something, which won't be registered.
Finally, you could be swallowing a class loading exception so the driver load fails and you don't see it, like this (extremely bad) code:
// Very bad code, never do this
try {
    Class.forName("org.postgresql.Driver");
} catch (ClasNotFoundException ex) {}

Never do the above. Either wrap the exception in an unchecked runtime exception or just add throws ClasNotFoundException to your method definition.

As per the PgJDBC documentation and FAQ, to use the driver you must:

*

*Download the JDBC driver;

*Ensure that the JDBC driver is on your CLASSPATH;

*Load/register the driver by passing a JVM parameter or using Class.forName("org.postgresql.Driver"); so it's registered with the DriverManager;

*Connect to the database
These are all links to the manual.
For more on the CLASSPATH, see wikipedia
The JDBC DriverManager is discussed in the JavaDoc and the JDBC tutorial.

As for the JDBC URL format for PostgreSQL, that's in the documentation too.

With JDBC, a database is represented by a URL (Uniform Resource
  Locator). With PostgreSQL™, this takes one of the following forms:
jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database

The docs go on to explain what each parameter means and the optional connection parameters.
From this you can see, in answer to your comment on John Woo's answer, that you do not have to specify the port if your server is listening on the default PostgreSQL port, which it is if you don't have to specify the port when connecting with psql.
That makes your getConnection arguments correct, the problem is that you didn't register the driver first.

A: Make sure your pg_hba.conf file has an entry for local connections, something like this:
local      mydatabasename  myusername  password


text:
Q: Dynamic Chart from selection of any KPI boxes in Qlik I am new to the development of Qlik and I am in the middle of building my first dashboard in Qlik. I currently have a dashboard that I am developing that has 11 Multi KPIs added on its Main Sheet  that shows various Summarised Values for the Measures that it is showing and that works very well.
What I am looking to do now is to add a single chart with the space that I have left (GRAPH 1) (attached image of example of dashboard) but what I would like is to default the chart to show the first KPI's trend over a 13 week period (will create this). My main question is, is it possible for this chart to be dynamic so that I am able to single click on any of the KPI's to change the chart to show the clicked KPI's chart?
As when the KPI is double clicked this will go onto a separate dashboard so I'm not sure if this is possible.
Would appreciate if somebody could clarify if this is something that can be achieved as not sure if it's something I will have to do using some Javascript or if there is a feature that will allow me to build this in Qlik itself.

A: I have attached an example that includes 2 solutions:

*

*First one is made using alternative measures, so for every KPI I made an alternative measure. In my previous comment I mentioned there might be a limit to the amount of alternative dimensions/measures, but after some testing it doesn't seem like it (at least 12 work). The downside to this method is that it doesn't save the order of the alternative measures, but it changes every time you make a selection.

*Second solution is made using a filter object, as explained in my previous comment:

Make a single line chart that depends on a variable for it's
  title/measure/dimension and combine this with a filter object where
  you can change this variable (all options are one of your KPI's). This
  does change your page a little since you need to have a filter object
  as well;

Both should work, but in the end it comes down to personal preference.
Attachment: https://drive.google.com/file/d/1wRgStl23DfcI5arQTZmt3w_0DEtW5iuf/view?usp=sharing
Since I can't garantee this google drive link will be up forever, here is it in steps:
Solution 1: Alternative measures:
In the Data load editor I made a new section with the following dummy data:
    LOAD * Inline [
Weeks, KPI1, KPI2, KPI3, KPI4, KPI5, KPI6, KPI7, KPI8, KPI9, KPI10, KPI11, KPI12
1, 1, 2, 0, 3, 5, 1, 1, 2, 0, 3, 5, 3
2, 2, 4, 0, 8, 5, 2, 2, 4, 0, 8, 5, 3
3, 3, 6, 1, 4, 5, 3, 3, 6, 1, 4, 5, 3
4, 4, 8, 1, 7, 6, 4, 4, 8, 1, 7, 6, 3
5, 5, 10, 2, 0, 7, 5, 5, 10, 2, 0, 7, 3
6, 6, 12, 2, 9, 7, 6, 6, 12, 2, 9, 7, 3
7, 7, 14, 3, 13, 7, 7, 7, 14, 3, 13, 7, 3
8, 8, 16, 3, 6, 8, 8, 8, 16, 3, 6, 8, 3
9, 9, 18, 4, 1, 8, 9, 9, 18, 4, 1, 8, 3
10, 10, 4, 3, 9, 10, 10, 10, 4, 3, 9, 10, 3
11, 11, 5, 3, 9, 10, 11, 11, 5, 3, 9, 10, 3
12, 12, 5, 8, 9, 10, 12, 12, 5, 8, 9, 10, 3
];

Then I added a "Line chart" object to a page and gave it the measure "Weeks". I also added a measure with expression: KPI1. Then I added 11 alternatives measures the exact same way for every KPI. So like this:

This should result in this:

Solution 2: Filter object
In the Data load editor I made a new section with the following dummy data:
LOAD * Inline [
Weeks, KPI1, KPI2, KPI3, KPI4, KPI5, KPI6, KPI7, KPI8, KPI9, KPI10, KPI11, KPI12
1, 1, 2, 0, 3, 5, 1, 1, 2, 0, 3, 5, 3
2, 2, 4, 0, 8, 5, 2, 2, 4, 0, 8, 5, 3
3, 3, 6, 1, 4, 5, 3, 3, 6, 1, 4, 5, 3
4, 4, 8, 1, 7, 6, 4, 4, 8, 1, 7, 6, 3
5, 5, 10, 2, 0, 7, 5, 5, 10, 2, 0, 7, 3
6, 6, 12, 2, 9, 7, 6, 6, 12, 2, 9, 7, 3
7, 7, 14, 3, 13, 7, 7, 7, 14, 3, 13, 7, 3
8, 8, 16, 3, 6, 8, 8, 8, 16, 3, 6, 8, 3
9, 9, 18, 4, 1, 8, 9, 9, 18, 4, 1, 8, 3
10, 10, 4, 3, 9, 10, 10, 10, 4, 3, 9, 10, 3
11, 11, 5, 3, 9, 10, 11, 11, 5, 3, 9, 10, 3
12, 12, 5, 8, 9, 10, 12, 12, 5, 8, 9, 10, 3
];

LOAD * Inline [
KPI,
KPI1,
KPI2,
KPI3,
KPI4,
KPI5,
KPI6,
KPI7,
KPI8,
KPI9,
KPI10,
KPI11,
KPI12
];

Then I added a "Line chart" object to a page and gave it the measure "Weeks". I also added a measure with the following expression:
= if(WildMatch(GetFieldSelections(KPI), 'KPI1') = 1, KPI1,
  if(WildMatch(GetFieldSelections(KPI), 'KPI2') = 1, KPI2,
  if(WildMatch(GetFieldSelections(KPI), 'KPI3') = 1, KPI3,
  if(WildMatch(GetFieldSelections(KPI), 'KPI4') = 1, KPI4,
  if(WildMatch(GetFieldSelections(KPI), 'KPI5') = 1, KPI5,
  if(WildMatch(GetFieldSelections(KPI), 'KPI6') = 1, KPI6,
  if(WildMatch(GetFieldSelections(KPI), 'KPI7') = 1, KPI7,
  if(WildMatch(GetFieldSelections(KPI), 'KPI8') = 1, KPI8,
  if(WildMatch(GetFieldSelections(KPI), 'KPI9') = 1, KPI9,
  if(WildMatch(GetFieldSelections(KPI), 'KPI10') = 1, KPI10,
  if(WildMatch(GetFieldSelections(KPI), 'KPI11') = 1, KPI11,
  if(WildMatch(GetFieldSelections(KPI), 'KPI12') = 1, KPI12,
))))))))))))

After that I added a new "Filter object" to the page with dimension: KPI. As a final step I go to "Fields" -> right click "KPI" -> click "Field settings" -> check "Always one selected value" -> click "Save".
So like this:

And that's it, now you have a filter object that influences your line chart.
Hope it helped, if anything isn't clear, please let me know.


text:
Q: Integrate Google Chart Interactive with ASP.NET and C# I want to create chart using Google Chart Interactive with ASP.NET and C#
I was found this example http://code.google.com/apis/visualization/documentation/using_overview.html but i find problem how to i Integrated this with c# and how to integrate data from c# to javascript..
can someone hint me what I should do?

A: What you need to do is send the command to the google charts api and convert the response to an image like below, and then you can take the image object and write it to a file or perform any operation you want:
 string ChartURL = "http://chart.apis.google.com/chart?";
            ChartURL += "chxr=0,0," + MaxX + "";
            ChartURL += "&chxt=y";
            ChartURL += "&chbh=a";
            ChartURL += "&chs=" + ChartWidth + "x" + ChartHeight + "";
            ChartURL += "&cht=bvg";
            ChartURL += "&chco=" + ChartColors + "";
            ChartURL += "&chds=" + ChartDataRange + "";
            ChartURL += "&chd=t:" + ChartValues + "";
            ChartURL += "&chdl=" + ChartLegend + "";
            ChartURL += "&chtt=" + ChartTitle + "";

            HttpWebRequest myRequest = WebRequest.Create(ChartURL) as HttpWebRequest;
            HttpWebResponse ServerResponse = myRequest.GetResponse() as HttpWebResponse;
            Stream ResponseStream = myRequest.GetResponse().GetResponseStream();
            return System.Drawing.Image.FromStream(ResponseStream);


text:
Q: Is there a way to force the browser to always pass the Authorization header if credential is already available? Using Basic Authentication, if the user has already logged in, the browser will include the username/password in the http request in the succeeding http requests ONLY IF it receives a 401 response containing an authentication challenge. Username/password is passed via Authorization header.
Is there a way to force the browser to always include the Authorization header once the user has logged in?
The reason I'm asking for this is that I have a CGI application (separate from the main CGI app that serves my dynamic pages) that should use the Authorization info if present but should not prompt for it if it's not present.
Thanks.

A:
if the user has already logged in, the
  browser will include the
  username/password in the http request
  in the succeeding http requests ONLY
  IF it receives a 401 response
  containing an authentication challenge

This is not the behaviour I see in web browsers; once the browser has received a 401, it always includes the authorization after that. Can you perhaps provide more detail on how to reproduce the problem?

A: One solution would be to expose one handler of your CGI app, that would generate an HTML page that would do an AJAX call, prompting the 401 that would then be responded to by the browser. Would that make sense?


text:
Q: Insert empty lines without entering insert mode I often find myself bouncing on o or O and ctrl{ to insert blank lines and get back out of insert mode.
Thinking there must be a simpler way, and hoping to retain my cursor position, I hacked together these sloppy macros:
map <Leader>O :let cursorpos = getpos(".")<CR>:i<CR><CR>.<CR>:let cursorpos[1] = cursorpos[1] + 1<CR>:call setpos('.', cursorpos)<CR>
map <Leader>o :let cursorpos = getpos(".")<CR>:a<CR><CR>.<CR>:call setpos('.', cursorpos)<CR>

However, this doesn't allow for ranges. It would be nice to be able to go 5\O and get 5 blanks above my current line.
Any suggestions on how I can fix this to allow ranges and still return to the original cursor position when done?

A: The unimpaired plugin adds mappings that do what you want. You can insert a blank line above the cursor with [<space>, or below the cursor with ]<space>. Both of these mappings can be prepended with a count.

A: I added this to my .vimrc
"create new line below current line without leaving normal mode or moving cursor
noremap - m`o<Esc>``
"create new line above current line without leaving normal mode or moving cursor
noremap _ m`O<Esc>``

I prefer this solution for several reasons:

*

*I don't normally use the - or _ keys in normal mode and they are located on the same physical key on my keyboard.

*It just seems like installing a plugin for this is overkill. I avoid downloading plugins for simple things since they introduce new code to my environment that I don't yet fully understand or trust and it may interfere with other customizations or plugins.

*I tried the solution from the author of this question located in his comment under the accepted answer, but after using this, the . command does strange and disturbing things.

*I usually prefer pressing . multiple times over passing a numeric argument, so that instead of sitting there counting things on my fingers, I just keep pressing . until it looks right (less conceptual visualization and more real vision). Unfortunately even this solution does not work the way I want with the . command. However, by mapping - and _, these can be pressed repeatedly for the same effect. Just a shame it is not closer to the home row...

WARNING: Marking the ` key affects the jump list. You can use any other mark if that makes your pleasure++

A: You can use :call append(linenumber, repeat([''], 5)). It won't move the cursor.


text:
Q: Partial View doesn't see that BeginForm is part of HtmlHelper In my main app I would like to load a partial view from a plug-in DLL into the main view. Right now I am using @Html.Partial(/~bin/PluginName.dll/PluginName.ViewName.vbhtml) as my way of trying to look at the partial view. This is the error I'm getting:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET
Files\root\b3a37fd6\7fe17e9b\App_Web_cucontractnumberplugin.cucontractnumbersearch.vbhtml.1
45470.d2zb2yt5.0.vb(43): error BC30456: 'BeginForm' is not a member of
'System.Web.WebPages.Html.HtmlHelper'.

I have a class that loads the dlls into the shadow directory upon app start-up. All that is in my partial view (for now) is a text box. I eventually would like to load a plugin of a search into my main view.
Here is my partial view:
@using(Html.BeginForm("ChangeCUNumber", "PluginName"))

@Html.TextBox("strCUNumber")

End Using

If you need anything clarified please ask! Thanks!

A: Needed to add @Inherits System.Web.Mvc.WebViewPage in my plugin view


text:
Q: Have different view based on type of user I have a user model that has a few different types, i.e. there is a user attribute that is set as either a usertype1, usertype2, or usertype3.  How can I route the user to a different page based on the user type?  I am using devise for authentication.

A: If you want to redirect the user after logging in then check this devise wiki. The specific code is
# app/controllers/application_controller.rb

def after_sign_in_path_for(resource)
  if usertype1?
    some_url
  elsif usertype2?
    another_url
  elsif usertype3?
    some_other_url
  end
end

But if what you're looking for is more generic then that you probably want to define roles and give users access to certain parts of the site based on their roles - also known as authorization. For that I'd recommend using cancan. You can also watch the railscast episode if you want more info.
Edit:
See also this so question


text:
Q: Change Cache-Control nginx container on docker I installed docker on my linux and I installed nginx container like this:
docker pull nginx
docker run -it  -d -p 8081:80 --name web -v /mnt/Project/Flutter/Projects/app_web2/build/web:/usr/share/nginx/html nginx

Now I want to change Cache-Control on my nginx container. Because I write a pwa with flutter, Every time I changed my page, when I launch page I still see old version of page, Now I want to change nginx caching.
How can I change it's default?

A: I suspect that you can achieve this directly. There are two approach.

*

*Run nginx container as you running as of now. Then perform following operation.
docker exec -it <<containername>>

go to /etc/nginx/conf.d/default.conf ( Edit this file)
Note : This approach is problem as you have to do this every time.

*Another approach is create custom image based on nginx.
FROM nginx:latest
COPY ./default.conf /etc/nginx/conf.d/default.conf

This ./default.conf will reside in your directory and from where you execute following command.
   docker build . mynginx:latest

In this default.conf at your directory you can add custom header.
You can find sample over here : https://github.com/jp1482/mynginxwithcustomerheader


text:
Q: Ignore select before insert in JPA we declare some tables like this in JPA:
@Entity
@Table(name = "A")
public class A {

    public A() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "a")
    private Set<B> bs = new HashSet<>();
}

@Entity
@Table(name = "b")
public class B {

    public B() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "a_id", foreignKey = @ForeignKey(name = "FK_B_A"))
    private A a;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "c_id", foreignKey = @ForeignKey(name = "FK_B_C"))
    private C c;

}

@Entity
@Table(name = "C")
public class C {

    public C() {
    }

    @Id
    @Column(name = "id")
    private long id;
}

now I wanna insert some record in the table, we know that value of c_id is 1, and we wanna insert a record in B without select from C.
we write this code now :
a = aRepository.find(a_id);
b = new B();
b.setCId(1);
a.setBs(b);
aRepository.save(a);

but JPA, before insert record, does a select on C and get all records from c by id ==1, how can I denied this select and tell to JPA just insert without select?
console log logged something like this:
""2018-02-06 16:08:44 -
    select
        ...
    from
        c c_
    where
        c_.id=?
""2018-02-06 16:08:44 -
    insert
    into
        b
        (id, c_id, a_id)
    values
        (null, ?, ?)

A: To set C call getReference (e.g. getOne in JpaRepository) with the id like
a = aRepository.find(a_id);
b = new B();

C c = cRepository.getOne(1)
b.setC(c);

a.setBs(b);
aRepository.save(a);

With getReference aka getOne there will be no SQL statement it will just create a proxy object that you can assign to a.


text:
Q: zimbra: timezone not changing despite multiple attempts I am using Zimbra ZCS8 for my company's email service.
When any user receives or sends an email, the timezone being used is GMT-10.
My timezone (and the one I need in the email server) is GMT-5.
Despite my attempt to change this in several ways, Zimbra is still stuck on using GMT-10.
I have tried:

*

*changing the timezone in the Zimbra admin GUI

*changing the timezone via the CLI, using zimbra user: zmprov mc default zimbraPrefTimeZoneId '(GMT-05.00) Bogota / Lima / Quito / Rio Branco'

I checked the linux server's time, and it is correctly set to GMT-5.
Any thoughts?

A: You can set your timezone at different levels within Zimbra, please check:

*

*Configure -> Class of Service -> default -> Preferences: Time zone

*Configure -> Domains -> 'domainname' -> General Information: Time zone

*Manage -> Accounts -> 'account name' -> Preferences: Time zone

try the commands:

*

*date

*date -u

there should be 5 hours difference.

A: The Zimbra COS attribute zimbraPrefTimeZoneId is only applied to users if they do not have that attribute. Make sure your account doesn't have zimbraPrefTimeZoneId set like so:

zmprov ma someaccount@domain.com -zimbraPrefTimeZoneId

Also, are you certain that your account is in the default COS?


text:
Q: ASP.NET MVC call Controller Action with parameter from javascript function I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
    cache: false,
    url: this.saveUrl,
    type: 'post',
    success: this.nextStep,
    complete: this.resetLoadWaiting,
    error: Checkout.ajaxFailure
});

nextStep: function (response) {
    if (response.error) {
        if ((typeof response.message) == 'string') {
            alert(response.message);
        } else {
            alert(response.message.join("\n"));
        }

        return false;
    }

    if (response.redirect) {
        ConfirmOrder.isSuccess = true;
        location.href = response.redirect;
        return;
    }
    if (response.success) {
        ConfirmOrder.isSuccess = true;
        window.location = ConfirmOrder.successUrl;
        //window.location.href = @Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
        //window.location.href = '@Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
    }

    Checkout.setStepResponse(response);
}

in RouteProvider.cs I have:
        routes.MapLocalizedRoute("CheckoutCompleted",
                        "checkout/completed/{orderId}/{customerComment}/{customerDate}",
                        new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
                        new { orderId = @"\d+", customerComment = @"\w+", customerDate = @"\w+" },
                        new[] { "Nop.Web.Controllers" });

And finaly in Controller I have:
    public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
    {
        //some code here
    }

I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.

A: Did you add httpPost wrapper to your controller ?
[HttpPost]
     public virtual ActionResult Completed(MyClass  MyClassObj )
     {
            //some code here
     }

in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {

            try {

                var req = {
                    DeliveryCode: value,

                }

                $.ajax({
                    url: URL,
                    type: 'POST',
                    data: req,
                    dataType: "json",
                    async: true,
                    success: function (result) {

                        resetLoadWaiting()

                    },
                    error: function (e) {

                    }
                });
            }
            catch (e) {

            }
        }

A: Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.


text:
Q: FLUTTER WEB: How To Use Google Places Autocomplete In Flutter Web? I used almost every package for places auto complete, I am getting cross error. Please let me know if there is any way to use places autocomplete In Android, iOS and web together.
 var p = await PlacesAutocomplete.show(
    radius: 500000,
    strictbounds: false,
    region: "in",
    language: "en",
    context: context,
    mode: Mode.overlay,
    apiKey: "key",
    components: [new Component(Component.country, "in")],
    types: ["(cities)"],
    hint: "Search City",
);

currently I am using this function

A: You need to have separate api for this google placeAutocomple
  var response = await _client.get("https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$input"
          "&types=establishment&language=en&components=country:in&key=$kGoogleApiKey&sessiontoken=19");

and then show result in autocomplete textfield or listview.

  void getPlaces(input, lng,lat) {
    SearchLocation()
        .getPlaces(input: input, lang: lng,lat: lat)
        .then((value) => _placesResponse(value))
        .catchError((e) => _placesError(e));
  }

  _placesResponse(List<Place> v) {
    setState(() {
      addressList = v;
    });
  }

  _placesError(e) {
    errorSnackbar(context,e.toString());
  }

Listview Widget
ListView.builder(
                    itemCount: addressList.length,
                    shrinkWrap: true,
                    itemBuilder: (ctx, index) {
                      var address = addressList[index];
                      return Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 12.0),
                        child: InkWell(
                          onTap: () {
                            if(_isLoading != true) {
                              getSelectedPlace(address.placeId);
                            }
                          },
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Container(
                                      width: 25,
                                      height: 25,
                                      decoration: BoxDecoration(color: Colors.grey, borderRadius: borderRadiusAll_30),
                                      child: Center(
                                          child: Icon(
                                        CupertinoIcons.location_solid,
                                        size: 14,
                                        color: Colors.white,
                                      ))),
                                  Flexible(
                                    fit: FlexFit.tight,
                                    child: Padding(
                                      padding: const EdgeInsets.only(left: 12.0),
                                      child: Text(
                                        address.description ?? '',
                                        style: GoogleFonts.sourceSans3(textStyle: textTheme.bodyText2),
                                        textAlign: TextAlign.left,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              Padding(
                                padding: const EdgeInsets.symmetric(vertical: 4.0),
                                child: Divider(
                                  color: MyColor.kGrey,
                                ),
                              )
                            ],
                          ),
                        ),
                      );
                    }),

For this you need to have kGoogleApiKey
To get lat long u need add geolocator
  Future<void> _getCurrentPosition() async {
    setState((){
      _isLoading = true;
    });
    final hasPermission = await _handleLocationPermission();
    if (!hasPermission) {
      Geolocator.requestPermission();
      return;
    }
    await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best).then((Position position) {
      setState(() {
        _position = position;
        lang = _position?.longitude.toString() ?? '';
        lat = _position?.latitude.toString() ?? '';
      });
      Log.d("Latitude ${lat} Longitude ${lang}");
      setState((){
        _isLoading = false;
      });
    }).catchError((e) {
      setState((){
        _isLoading = false;
      });
      warning(context,e.toString());
      Geolocator.requestPermission();
      Log.d('Catch error ${e.toString()}');
    });
  }


text:
Q: Please help: android.view.InflateException: Binary XML file line #3: Error inflating class com.google.android.maps.MapView I wrote the Get Point application (https://market.android.com/details?id=jv.android.getpoint&feature=search_result) to store GPS coordinates and export a KML file to be opened in Google Earth. That application was created because I need to learn the Android platform.
Because I'm new on Android please forgive me if I'm asking for a dummy question. :)
The Google Marked Developer Console show me there is an error I can't reproduce by myself either in emulator (With Google APU , Galaxy S or Galaxy 5 :(
The error message is: android.view.InflateException: Binary XML file line #3: Error inflating class com.google.android.maps.MapView.
I was looking for a solution, but could not find an answer :(
The Stack is here:
 at android.view.InflateException: Binary XML file line #3: Error inflating class com.google.android.maps.MapView
 at android.view.LayoutInflater.createView(LayoutInflater.java:513)
 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
 at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
 at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
 at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
 at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
 at jv.android.getpoint.ListaCoordAdapter.getView(ListaCoordAdapter.java:29)
 at android.widget.AbsListView.obtainView(AbsListView.java:1315)
 at android.widget.ListView.makeAndAddView(ListView.java:1727)
 at android.widget.ListView.fillDown(ListView.java:652)
 at android.widget.ListView.fillFromTop(ListView.java:709)
 at android.widget.ListView.layoutChildren(ListView.java:1580)
 at android.widget.AbsListView.onLayout(AbsListView.java:1147)
 at android.view.View.layout(View.java:7035)
 at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
 at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
 at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
 at android.view.View.layout(View.java:7035)
 at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
 at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
 at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
 at android.view.View.layout(View.java:7035)
 at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
 at android.view.View.layout(View.java:7035)
 at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
 at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
 at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
 at android.view.View.layout(View.java:7035)
 at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
 at android.view.View.layout(View.java:7035)
 at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
 at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
 at android.os.Handler.dispatchMessage(Handler.java:99)
 at android.os.Looper.loop(Looper.java:123)
 at android.app.ActivityThread.main(ActivityThread.java:4627)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:521)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
 at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
 at com.google.android.maps.MapView.<init>(MapView.java:238)
 at java.lang.reflect.Constructor.constructNative(Native Method)
 at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
 at android.view.LayoutInflater.createView(LayoutInflater.java:500)
 ... 39 more
Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity.
 at com.google.android.maps.MapView.<init>(MapView.java:282)
 at com.google.android.maps.MapView.<init>(MapView.java:255)
 ... 43 more

The main activity has an menu option to call the MapActivity. The XML and code:
To start the map:
            Intent intent = new Intent(GetPointActivity.this, PointView.class);

            intent.putExtra("latitude", latitude);
            intent.putExtra("longitude", longitude);
            startActivity(intent);

The PointView class:
public class PointView extends MapActivity {

    MapView mv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maps);

        mv = (MapView)findViewById(R.id.mvPosicao);
        mv.setLongClickable(true);
        mv.setBuiltInZoomControls(true);

        Intent intent = getIntent();

        if (intent != null)
        {
            Bundle params = intent.getExtras();

            if (params != null) {
                Double lat = (Double) params.getDouble("latitude");
                Double lon = (Double) params.getDouble("longitude");

                markPosition (lat, lon);
            }
        }

        registerForContextMenu(mv);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu  menu) {
        //Log.i("MYINFO", "I'm in");
        MenuItem mi0 = menu.add(Menu.NONE, 0, 0, getString(R.string.mnVerMapa));
        mi0.setIcon(R.drawable.mapview);

        MenuItem mi1 = menu.add(Menu.NONE, 1, 1, getString(R.string.mnVerSatelite));
        mi1.setIcon(R.drawable.satelliteview);

        MenuItem mi2 = menu.add(Menu.NONE, 2, 2, getString(R.string.mnVerStreetView));
        mi2.setIcon(R.drawable.streetview);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            mv.setSatellite(false);
            break;
        case 1:
            mv.setSatellite(true);
            break;
        case 2:
            mv.setStreetView(true);
            break;
        }

        return true;
    }

    public void markPosition (Double lat, Double lon){
        int latE6 = (int)(lat*1E6);
        int lonE6 = (int)(lon*1E6);

        GeoPoint point = new GeoPoint(latE6, lonE6);

        ImageOverlay io = new ImageOverlay(new GeoPoint(latE6, lonE6), R.drawable.waypoint2);

        mv.getOverlays().add(io);
        mv.getController().setCenter(point);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

The PointView XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
  <com.google.android.maps.MapView
    android:id="@+id/mvPosicao"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:enabled="true"
    android:clickable="true"
    android:apiKey="<my googlemaps key" />
</LinearLayout>

My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="<package>.getpoint"
      android:versionCode="1"
      android:versionName="1.0.1">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

    <application android:label="@string/app_name" android:icon="@drawable/maps">
        <uses-library android:name="com.google.android.maps" />
        <activity android:name=".GetPointActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".PointView" android:configChanges="keyboard|keyboardHidden|orientation" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar"/>
                </application>
</manifest>

The option to show the map is called by a context menu displayed when the user long press a ListView. That ListView has a custom Adapter (the highlighted line is displayed in the stack):
public class ListaCoordAdapter extends ArrayAdapter<CoordToShow> {

    private List<CoordToShow> items;
    Context context;

    public ListaCoordAdapter(Context context, int textViewResourceId, List<CoordToShow> items) {
        super(context, textViewResourceId, items);
        this.items = items;
        this.context = context;
    }

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

        if (v == null) {
            LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            **v = vi.inflate(R.layout.rowcoord, null);**
        }

        CoordToShow it = items.get(position);
        if (it != null) {
            ImageView iv = (ImageView) v.findViewById(R.id.ivCoord);
            TextView l1 = (TextView) v.findViewById(R.id.linha1);
            TextView l2 = (TextView) v.findViewById(R.id.linha2);

            l1.setText(it.getNome());
            l2.setText(it.toString());

            if (iv != null) {
                if (it.getTipo() == CoordToShow.PONTO)
                    iv.setImageResource(R.drawable.waypoint2);
                else
                    iv.setImageResource(R.drawable.track);
            }
        }

        return v;
    }
}

The rowcoord xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:paddingTop="4dip"
     android:paddingBottom="6dip"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" android:orientation="horizontal">
    <ImageView android:src="@drawable/waypoint2" android:id="@+id/ivCoord" android:layout_width="32dp" android:layout_height="32dp"></ImageView>

     <LinearLayout
         android:id="@+id/ll2"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content" android:orientation="vertical">
         <TextView android:id="@+id/linha1"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:textAppearance="?android:attr/textAppearanceMedium" />
         <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linha2"></TextView>
     </LinearLayout>
</LinearLayout>

In Default.Property:
target=Google Inc.:Google APIs:8

Any help will be appreciated.

A: The core of your problem is at the very bottom of the stack trace: MapViews can only be created inside instances of MapActivity. Basically, the inflation is taking place from outside of your PointView for whatever reason.
Is jv.android.getpoint.ListaCoordAdapter one of your classes?  It looks from the stack trace that this is the class that's trying to inflate the layout.  If this class is yours, does it extend MapActivity?

A: I fixed it by extend MapActivity instead of Activity in the activity class that calls the MapView


text:
Q: Random number generator that generates integers for Java I want to generate some random integers in Java, but this according to some distribution laws.
More specific:

*

*I want to generate some random integers for gaussian distribution. I found out only generators which return double results for the gaussian distribution. Why is that?

*I want to generate some random integers between some limits for exponential distribution? Here I also found out only about generators which return double. I also didn't find out a way to generate some random exponential numbers only between two limits.
Can you help me? Do you know a library which can do what I want? I studied Michael Flanagan's library, colt and apache's Commons Math but they don't have what I need.
Thanks!

A: I suggest you to use the Uncommons Maths library, which comprises different random generators (e.g. Mersenne Twister, AES-based) and distributions (poisson, gaussian and so on)
As for the "double problem": almost all random generators generate double because they are the most used. If you need integers you'll need to do the rounding yourself (a call to Math.round will be enough). Let's say that you are generating random people heights with centimeter accuracy: if your random generator returns 175.234, you can just round it to 175. That's really not a problem.
As for the limits for exponential distribution: there are no generators that let you choose limits because no such limits exist for exponential distribution. An exponential distribution typically models the delays between two consecutive events in a Poisson process: the delay can be as low as 0, or can be extremely high. The extremely high outcomes are really really unlikely, but they are not impossible. you can solve the problem by getting a random number from the generator, adding your lower limit and using Math.max to trim it if it is higher than your upper limit. But this is no longer an exponential distribution.

A: If you have a double number from 0 to 1 you can scale it to the integer:
int res = lowLimit + (int)(myRandFunction() * (highLimit - lowLimit));
Edit:
Why I got a vote down? He sad he has a function that returns a double in distribution he wants (I guessed a double form 0 to 1), so this is going to do the job.

A: Just generate a double and scale it to the integer range you require. For example, if a regular (uniform) random number generator generates numbers from 0.0 to 1.0 and you want numbers from 0 to 100, you'd just multiply the generated random number by 100.

A: boost has some really nice random number generators, i know its c++ and not java, but the implementations should be a good guide to implementing them yourself.
http://www.boost.org/doc/libs/1_43_0/doc/html/boost_random.html


text:
Q: How to specify a certificate in the cert store for gRPC .NET Core? I'm trying to specify a certificate in the cert store for gRPC .NET Core 3.1.
I found a way to specify a certificate by setting the path.
https://medium.com/@mcilis/how-to-publish-net-core-grpc-server-as-a-windows-service-dd562a1e263d
    "Certificates": {
        "Default": {
            "Path": "Your_Path_To_Certificate_Pfx",
            "Password": "Pfx_File_Password"
        }
    }

But is it possible to specify one in the Windows Certificate store with appsettings.json?
Or is it possible only by code?

A: I found an answer when I saw a stack trace.
CertificateConfig
https://github.com/dotnet/aspnetcore/blob/a190fd34854542266956b1af980c19afacb95feb/src/Servers/Kestrel/Core/src/Internal/ConfigurationReader.cs
These are the parameters for the Windows certificate store.

*

*Subject

*Store

*Location

*AllowInvalid


text:
Q: Adding multiple external domains in chrome extension I'm building a Chrome extension, which uses multiple APIs. Currently I have it set up so that I can use one of these APIs, but trying to add a second to the manifest won't work. I tried a couple of things resulting in either the extension not workin or the manifest file being invalid.
"content_security_policy": "script-src 'self' https://domain-1.com; object-src 'self'",
"content_security_policy": "script-src 'self' https://domain-2.com; object-src 'self'"

Gives invalid manifest error
"content_security_policy": "script-src 'self' https://domain-1.com; https://domain-2.com; object-src 'self'",

Only works for the first domain
"content_security_policy": "script-src 'self' https://domain-1.com, https://domain-2.com; object-src 'self'",

Gives invalid manifest error

A: There can be only one content_security_policy entry. You can specify multiple domains but you have to separate them by spaces and not by commas:
"content_security_policy": "script-src 'self' https://domain-1.com https://domain-2.com; object-src 'self'",

For more information see CSP specification, in particular the examples section.


text:
Q: Reading useful data from barcode input I have interfaced a HID bar-code scanner with LPC2468. It is sending data when i scan a bar-code, it sends a lot of bytes when i make a scan, how can i know out of these bytes which are the bytes corresponding to the scanned bar-code.
For eg:If i scan a bar-code having value 2M12264185 it send following data
 1: Input Report:
    2: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    3: Input Report: 0, 0, 1F, 0, 0, 0, 0, 0,
    4: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    5: Input Report: 2, 0, 0, 0, 0, 0, 0, 0,
    6: Input Report: 2, 0, 10, 0, 0, 0, 0, 0,
    7: Input Report: 2, 0, 0, 0, 0, 0, 0, 0,
    8: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    9: Input Report: 0, 0, 1E, 0, 0, 0, 0, 0,
    10: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    11: Input Report: 0, 0, 1F, 0, 0, 0, 0, 0,
    12: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    13: Input Report: 0, 0, 1F, 0, 0, 0, 0, 0,
    14: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    15: Input Report: 0, 0, 23, 0, 0, 0, 0, 0,
    16: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    17: Input Report: 0, 0, 21, 0, 0, 0, 0, 0,
    18: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    19: Input Report: 0, 0, 1E, 0, 0, 0, 0, 0,
    20: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    21: Input Report: 0, 0, 25, 0, 0, 0, 0, 0,
    22: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    23: Input Report: 0, 0, 22, 0, 0, 0, 0, 0,
    24: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,
    25: Input Report: 0, 0, 28, 0, 0, 0, 0, 0,
    26: Input Report: 0, 0, 0, 0, 0, 0, 0, 0,

How to distinguish data bytes from other bytes.

A: While I'm not going to guess what every field is, your barcode scanner is emulating a USB HID keyboard. Each line with non-zero fields indicates a key-press, and all zeros indicates no key presses.
The third field is the USB HID key code. See this link from the USB group, starting with page 53. Note that the USB HID codes do not align with ASCII or other barcode languages. Checking the key codes versus what you say the barcode should be gives a 1:1 match.
The second field appears to be a modifier column, when it is equal to 2 the 'Shift' key is depressed. That would make your "input report 5-7" look like this:
4:
5: <Shift>
6: <Shift> <M>
7: <Shift>
8:


text:
Q: Design patterns to manage multiple windows/screens? Supposed there is an application with multiple windows, like:
Logo splashscreen
Connecting... screen
Login-usercontrols screen
Logging in... screen
etc.
Is there a design pattern, which allows to effectively manage all those windows? (to hide previous windows, display a new window etc.)

A: Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
As an example, consider the implementation of a dialog box to present a collection of widgets such as buttons, menus, and entry fields. There may be dependencies between the widgets in the dialog, e.g., selecting an entry in a list box might change the contents of an entry field.
Such dependencies can be reduced by encapsulating collective behavior in a mediator object. A mediator is responsible for controlling and coordinating the interactions of these objects. The mediator acts as an intermediary and keeps objects in the group from referring to each other explicitly. The objects only know the mediator, thus reducing the number of interconnections.