Q:

Automatic identification of lucky images for landscape photography

I recently did a trial run for a project to photograph a certain rock climbing area from a variety of directions. I took shots at a couple of different times of day from the same spot, tried different exposures, and took 16 shots for the setups that seemed the best. The best shot from the best session was this one (thumbnail below). I had originally thought that I would try stacking images, but the result of stacking the 16 shots looked worse (less detail) than the best individual shot. Atmospheric turbulence was clearly visible through the lens, as the hot afternoon sun hit the west side of the rock. Although I got some shots in the morning with indirect light, they actually showed less detail because of the lack of shadows and contrast, and the lower light levels. There is no location from which I can get the right perspective on my subject from nearby, so all my images are going to have to be shot with a 135 mm or 300 mm lens from far away.

Is there some way to automate the process of looking for the lucky images from a set of landscape photos like this? Since people doing lucky imaging with astronomical photography sometimes do hundreds of shots, I assume they automate this somehow, but I don't know if the algorithms they use are appropriate for landscape photography. This project will involve lots of driving and hiking, so I would be happy to take hundreds of exposures in a row if it would be likely to be helpful. I'm looking for an open-source solution that works on linux, preferably something I can do from the command line.
Or would I be likely to get better results by using a video technique? Impressive results are described here. But it seems like to do this you need to be able to shoot about 10 frames a second, and I haven't figured out if my camera can do this. (I have a Fuji x-e1.)
[EDIT] Having looked around on the web a little more, I think I have some partial answers to my own question. (1) Amateur astronomers using lucky imaging all seem to be using Windows and distributing "shareware" Windows software. (2) AFAICT the astronomical techniques all involve picking a "reference star," which is assumed to be a point source. If you have such a reference star, then it's fairly trivial to get a measure of image quality. A common one seems to be the Strehl ratio, which is basically the peak intensity of the image of your reference star. So if these impressions are correct, then it may make sense for me to try to roll my own image selection algorithm for landscapes.

A:

This is not a definitive answer to my own question, but it's too long for a comment.
I implemented the idea of using the RMS Laplacian. The idea is that if the brightness of the image is represented by an array of pixels a[i,j], then at any point (i,j), we have the discrete approximation to the Laplacian L=a[i-1,j]+a[i+1,j]+a[i,j-1]+a[i,j+1]-4a[i,j]. This measures the sharpness of features in the image. For example, if the image was out of focus, L would be lower. The RMS value of the Laplacian, R, is the square root of the mean of the square of the Laplacian.
Here is my code that calculates R for an input PNG image:
#!/usr/bin/ruby

# To batch convert a bunch of JPGs to png:
# perl -e '$i=0; foreach $f(<*.JPG>) {$s=sprintf("%03d",$i); $c="convert $f $s.png"; print "$c\n"; system($c); $i=$i+1;}'

require 'oily_png'

# require 'hsluv'
  # http://www.hsluv.org
  # https://github.com/hsluv/hsluv-ruby
  # sudo gem install hsluv

# Sloppy and probably not physiologically valid, but fast.
# Returns an integer from 0 to 255*3.
def color_to_brightness(c)
  return ChunkyPNG::Color::r(c)+ChunkyPNG::Color::g(c)+ChunkyPNG::Color::b(c)
end

def rms_laplacian_from_file(input_file)
  image = ChunkyPNG::Image.from_file(input_file)
  n = 0
  sum = 0
  sum_sq = 0
  w = image.width
  h = image.height
  1.upto(w-2) { |i|
    ### if i%1000==0 then print "i=#{i}\n" end # show progress
    next unless i>w/3 && i<(2*w)/3 ## for efficiency, only use center of frame
    1.upto(h-2) { |j|
      next unless j>h/3 && j<(2*h)/3 ## for efficiency, only use center of frame
      next unless rand(10)==0 # for efficiency
      a = Hash.new
      (-1).upto(1) { |k|
        (-1).upto(1) { |l|
          c = image[i+k,j+l] # color, represented as a 4-byte rgba value
          a[[k,l]] = color_to_brightness(c)
        }
      }
      laplacian = a[[1,0]]+a[[-1,0]]+a[[0,1]]+a[[0,-1]]-4*a[[0,0]]
      n = n+1
      sum = sum + laplacian
      sum_sq = sum_sq + laplacian*laplacian
    }
  }
  sum = sum.to_f/n
  sum_sq = sum_sq.to_f/n
  rms = Math::sqrt(sum_sq-sum*sum)
  return rms
end

ARGV.each { |input_file|
  rms = rms_laplacian_from_file(input_file)
  print "#{input_file} -- rms=#{rms}\n"
}

This is implemented in Ruby and runs on Linux using the open-source oily_png library. If anyone's interested in trying it, it should require almost no modification to run on other platforms, if you have Ruby and oily_png installed.
To test that it measures sharpness, I took the first image of my set of 16, measured R, and then added a 5-pixel gaussian blur using GIMP and re-measured R. The result was R=30.8 before the blur, and R=7.8 after. So this does seem to confirm that it measures sharpness.
My 16 images are numbered 000 to 015. Looking at the images by eye, I had previously picked out image 003 as the best. That was the image that I posted a link to in the question.
I ran my code on the 16 shots I had taken, and got the following output:
000.png -- rms=30.809465960392004
001.png -- rms=31.215359700578606
002.png -- rms=31.909926250066476
003.png -- rms=31.83243374839454
004.png -- rms=31.310612756003305
005.png -- rms=30.353258897447564
006.png -- rms=30.61244684985801
007.png -- rms=30.882745734215135
008.png -- rms=28.667104210689384
009.png -- rms=29.862966602367973
010.png -- rms=29.72001987743495
011.png -- rms=30.51274847773823
012.png -- rms=30.84316910530572
013.png -- rms=29.21751498027252
014.png -- rms=29.067434969521976
015.png -- rms=30.831305018709617

Of the 16 images, my choice had the second-highest R value. This would seem to confirm that this statistic could be a useful as an alternative to inspecting images and judging them subjectively by eye.
My implementation is pretty slow, and to make up for that I did some things to improve its performance. I only inspect the middle of the field, and I only sample the Laplacian at 1/10 of the points. In a more optimized implementation, these shortcuts could be eliminated if desired.
It later occurred to me that there might be a much simpler way to do this. An image with more detail should not compress as well, so the largest JPG file might simply be the best one. Sure enough, doing an ls -lS to list the files in order of decreasing size gave a list that was very nearly in the same order as the files sorted by decreasing R:
-rw-rw-r-- 1 bcrowell bcrowell 16970354 Oct 25 15:48 003.png
-rw-rw-r-- 1 bcrowell bcrowell 16927174 Oct 25 15:48 002.png
-rw-rw-r-- 1 bcrowell bcrowell 16903104 Oct 25 15:48 004.png
-rw-rw-r-- 1 bcrowell bcrowell 16882373 Oct 25 15:47 000.png
-rw-rw-r-- 1 bcrowell bcrowell 16861082 Oct 25 15:47 001.png
-rw-rw-r-- 1 bcrowell bcrowell 16817527 Oct 25 15:48 006.png
-rw-rw-r-- 1 bcrowell bcrowell 16816529 Oct 25 15:49 011.png
-rw-rw-r-- 1 bcrowell bcrowell 16793982 Oct 25 15:49 012.png
-rw-rw-r-- 1 bcrowell bcrowell 16786443 Oct 25 15:48 009.png
-rw-rw-r-- 1 bcrowell bcrowell 16773575 Oct 25 15:48 005.png
-rw-rw-r-- 1 bcrowell bcrowell 16771759 Oct 25 15:49 010.png
-rw-rw-r-- 1 bcrowell bcrowell 16765674 Oct 25 15:48 007.png
-rw-rw-r-- 1 bcrowell bcrowell 16764562 Oct 25 15:49 015.png
-rw-rw-r-- 1 bcrowell bcrowell 16750179 Oct 25 15:48 008.png
-rw-rw-r-- 1 bcrowell bcrowell 16732854 Oct 25 15:49 013.png
-rw-rw-r-- 1 bcrowell bcrowell 16684073 Oct 25 15:49 014.png

A:

Is there some way to automate the process of looking for the lucky images from a set of landscape photos like this?

As I understand it, your definition of "lucky image" is one which is sharper than the average. Since many cameras use measurement of sharpness of (a region of) an image in their autofocus mechanisms1, it's clear that there is some way to automate its measurement. However, the advantages of different approaches and the possibility of combining them is a subject of active research, so you can't expect a definitive answer. E.g. Robust Automatic Focus Algorithm for Low Contrast Images
Using a New Contrast Measure, Jinshan Tang et. al., Sensors (2011) says that

Many contrast measures have been used for passive AF ... Results indicate that 2D spatial measurement methods such as Tenengrad, Prewitt Edge
  detection, and Laplacian yield best performance in terms of accuracy and unimodality. However, they are very sensitive to noise, and not robust to different scene conditions such as low light conditions.
On the contrary, variance based methods are fast and robust. The basic idea is to calculate the variance of image intensity. The image is best focused when the variance reaches a maximum. A typical method in discrete cosine transform (DCT) domain is to compute the AC coefficients of images, which can also be used to represent information about variance function of the luminance.

Since you're not constrained to realtime performance on a low-powered processor in camera, you could probably implement multiple approaches and try to combine their scores. You talk about stacking, so I assume you have multiple shots taken from the same position in about the same light conditions: it might be worthwhile thinking about stitching rather than stacking, so that you select the photo which has the best contrast in one area, and the photo which has the best contrast in another, and stitch them together. I'm not sure to what extent existing stitching software supports this kind of contrast selection stitch.

1 To be precise, those which use contrast detection autofocus as opposed to phase detection autofocus. And yes, I know that DSLRs with live view use PDAF with the mirror down and CDAF in live view.


Q:

Restore git repo from a pack file

I am taking over some project, and I don't have a proper git repo but rather a pack-7dab97d983eeb36321c680bee7fde43688334f52.pack file. Can I restore a working git repository from it? And how?

A:

pack file contains only commits, so you don't have branch names, you have to guess them. A good starting points would be dangling commits.

create an empty repository
copy the pack to .git/objects/pack/
probably index the pack (I'm not sure if it needed or not)
run git fsck --lost-found
pick from found tips your probable branches

Note that it would fail if the pack file is only one of several from the original repository, as it may depend on objects which you don't have

A:

There are two questions you could be asking:

Can I restore the original repository, with all its branch names?
Can I restore some sort of repository, that may or may not be good enough for some purpose?

The answer to question 1 is no.
The answer to question 2 is maybe, even fairly likely yes, as long as it's not a "thin" pack.
max630's answer gives a method by which you can implement Answer 2, along with the reason you can't implement Answer 1: a repository consists, in essence, of two databases.  One of these databases is name-to-hash-ID.  You lack this database entirely: you have no names.
The other database consists of objects: commits, and supporting objects.  You do have some of these.
Specifically, a pack file is a collection of objects.  A repository may use more than one pack file, and/or may contain loose (unpacked) objects.  Having a pack file therefore does not guarantee that you have all the objects that go with that repository: you might have only some of the objects.
For most pack files, however, there's a second guarantee: pack files use delta-compression to save space, but will only delta-compress against other objects contained within the same pack file.  That means this pack file is independent of any other pack files that may have made up the complete object database: you may have an incomplete slice, but you can at least extract all the objects.
This rule is violated for thin packs: a thin pack is (defined as) a pack in which some object(s) are missing, so that the pack is not generally usable.  You may have some objects within such a file that are complete—that refer only to other objects in the same file, or aren't delta-compressed at all—but in general thin packs won't have enough objects to be useful for most purposes.


Q:

Sharepoint 2013 sign out issue on windows authentication

Scenario:

User is on default login page
User clicks on windows authentication, (s)he is prompted for
username and password
User is navigated to the home page
Click on Sign Out Link
User is navigated to the default login page
Click on windows authentication, (s)he is not prompted for username
and password, and logged in with the previous user credentials. Here
the user should be again prompted for username and password

A:

In step 5 your users should be redirected to the SignOut.aspx page telling them to close the browser.
With claims based authentication the SAML token which contains the authenticated user is stored as a session cookie.
When the user signs out there is no easy way for SharePoint to clear that cookie for all the SharePoint web applications/domains where it may have been issued.
SharePoint therefore doesn't even try to clear this cookie, but just informs the User to close the browser as this is the only way which will always work.


Q:

Custom RecyclerView is null

I'm trying to extend RecyclerView but the app crashes because the custom recycler view is null.
MyRecyclerView.kt
class MyRecyclerView @JvmOverloads constructor
    (context: Context, attrs: AttributeSet? = null, defStyle: Int = 0)
    : RecyclerView(context), RecyclerView.OnItemTouchListener {

    override fun onTouchEvent(p0: RecyclerView, p1: MotionEvent) {
        // no op
    }

    override fun onInterceptTouchEvent(rv: RecyclerView, event: MotionEvent): Boolean {
        return false
    }

    override fun onRequestDisallowInterceptTouchEvent(p0: Boolean) {
        // no op
    }
}

layout.xml
<com.myapp.view.MyRecyclerView
    android:id="@+id/my_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:itemCount="1"
    tools:listitem="@layout/row_item"
    tools:orientation="horizontal" />

Here is where it crashes in onViewCreated() in the fragment:
binding.root.myRecyclerView.adapter = adapter
binding.root.myRecyclerView.layoutManager =
        LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)

with this error:

java.lang.IllegalStateException: binding.root.myRecyclerView must not
  be null

Not sure what why this RecyclerView is null. Thanks.

A:

A View's ID defined with the android:id XML attribute is in the AttributeSet passed into the two+ parameter constructors. If you don't pass that in the super constructor call, the ID will not be set automatically in the View class, and your custom View won't be found with findViewById().
In this case, we just need to add the rest of the parameters to the super call:
RecyclerView(context, attrs, defStyle)

You might also want to set the appropriate defStyle default, which is R.attr.recyclerViewStyle, in the newest library versions, at least.


Q:

Есть ли способ присвоить вектору массив без копирования?

Хочу присвоить вектору массив, не перенося его в вектор поэлементно в цикле, а используя std::move. Такая возможность есть в классе стринг, возможно ли что то подобное в векторе?

A:

Если кратко - то нет. Но если копнуть глубже, то есть несколько различных вариантов.
Допустим, в массиве хранятся простые типы, для которых move на самом деле делает просто копирование - int, указатель, std::pair. В этом случае самым эффективным будет просто его скопировать
int * array = get_array();
vector<int> vec (array, array+length); // length - размер массива

Следующий случай. Массив хранит что то, что умеет эффективно перемещаться. Например, std::string.
const int LEN = 2;
std::string array[LEN] = {std::string("foo"), std::string("bar")};
std::vector<std::string> vec;
vec.resize(LEN);
std::move(array, array+LEN, vec.begin());

Возможно здесь можно лучше, но как по мне, resize портит все. Но если у Вас уже есть готовый вектор подходящего размера - вперед.
Потом внимательно посмотрел в документацию и понял, что есть куда проще и красивее способ (вывод - выглядит код криво - читай документацию)
const int LEN = 2;
std::string array[LEN] = {std::string("foo"), std::string("bar")};
std::vector<std::string> vec {
    std::make_move_iterator(array),
    std::make_move_iterator(array+LEN)
};

Если у Вас есть поддержка двадцатого стандарта, тогда можно использовать класс std::span. Я не понимаю, как он не появился раньше.  Если стандарт новый не доступен, можно использовать его реализацию с gsl::span - обычно пару файлов подтянуть - не проблема.
Этот класс позволяет завернуть голый сишный массив в обертку и дальше использовать вектороподобный интерфейс. Конечно, о памяти нужно побеспокоиться отдельно. Но в этом случае накладные расходы минимальны.


Q:

Is this grammar right associative (why?)

Given a grammar as follows:
$\left<stmt\right> \rightarrow \left<id\right> = \left<expr\right>$
$\left<const\right> \rightarrow A | B$
$\left<expr\right> \rightarrow \left<term\right> \times \left<expr\right> | \left<term\right>$
$\left<term\right> \rightarrow \left<factor\right> + \left<term\right> | \left<factor\right>$
$\left<factor\right> \rightarrow (\left<expr\right>) | \left<id\right>$
I think this grammar is right associative because it expands on the right. Where I am confused is it can be expanded using other non-terminals on the left. For example,
$\left<expr\right> \rightarrow \left<term\right> \times \left<expr\right> | \left<term\right>$
Could be expanded via $\left<term\right>$ on the left, I think. Does this make the associativity ambiguous? Assuming it could be ambiguous, how would I fix this to make the grammar completely right associative?

A:

$\left<expr\right> \to \left<term\right>×\left<expr\right> | \left<term\right>$
could certainly expand $\left<term\right>$. But the operator in that expansion (if there is one) is certainly not $×$; it would have to be $+$. So associativity doesn't apply, since associativity is only about expressions involving two of the same operator.
So yes, in both operator productions in that grammar, the operator is right-associative.


Q:

Responsive table height Bootstrap

How can I make table height to be responsive when displayed inside row element? In this row element there are two tables and an image, so that row height is set to fit this image. Or maybe there is another way to make labels for image with fixed size? I just found the way to set table height using something like { height: 120%; }, but its not responsive.
Code:

              Table1

            {table1Content}

              Table2

            {table2Content}

A:

Using display: flex; and also set height for .table and .table-responsive.
Add row-eq-height to your row, and remove an old class col-md-8, if you want use col-*-x, please add more row div outside, because it can be wrong with float attribute of col-*-x.
.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}
.table {
  background-color: #eee;
  height: 100%;
  margin-bottom: 0;
}
.table-responsive {
  height: 100%;
}

Check result here: https://jsfiddle.net/6eq89r4r/2/


Q:

Swt file dialog too much files selected?

the swt file dialog will give me an empty result array if I select too much files (approx. >2500files). The listing shows you how I use this dialog. If i select too many sound files, the syso will show 0. Debugging tells me, that the files array is empty in this case. Is there any way to get this work?
FileDialog fileDialog = new FileDialog(mainView.getShell(), SWT.MULTI);
  fileDialog.setText("Choose sound files");
  fileDialog.setFilterExtensions(new String[] { new String("*.wav") });
  Vector<String> result = new Vector<String>();
  fileDialog.open();

  String[] files = fileDialog.getFileNames();
  for (int i = 0, n = files.length; i < n; i++) {
   if( !files[i].contains(".wav")) {
    System.out.println(files[i]);
   }

   StringBuffer stringBuffer = new StringBuffer();
   stringBuffer.append(fileDialog.getFilterPath());
   if (stringBuffer.charAt(stringBuffer.length() - 1) != File.separatorChar) {
    stringBuffer.append(File.separatorChar);
   }
   stringBuffer.append(files[i]);
   stringBuffer.append("");

   String finalName = stringBuffer.toString();
   if( !finalName.contains(".wav")) {
    System.out.println(finalName);
   }
   result.add(finalName);
  }
  System.out.println(result.size())

;

A:

I've looked at the FileDialog source code and I'm afraid, there is an upper boundary. A 32kB byte buffer for all 0-terminated filenames (if I understood it correctly).
So calculating with your values, if the medium size of your filname strings is around 12 characters, then you've hit exactly that upper boundary.
So the only way out is to select the files in two or more steps.


Q:

How to find out when the QQuickItem-derived class object is initialized?

I've got class that inherits from QQuickItem and inside I'm operating on its width height properties. I'm also exposing my own properties.
class MyQQuickItem : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QUrl source MEMBER m_source NOTIFY sourceChanged)

    public:
    explicit MyQQuickItem(QQuickItem *a_parent = Q_NULLPTR);
     ~PDFPage();

    signals:
    void sourceChanged(const QUrl a_source);

    private:
    QUrl m_source;
};

In qml:
...
MyQQuickItem
{
    width: parent.width / 2
    height: parent.height
    source: "someSource"
    Component.onCompleted
    {
        console.log("component onCompleted");
    }
}

When sourceChanged is emmited I'm working on width height properties, but with the first emit they are not initialized yet, and Component.onCompleted is called after my NOTIFY signal.
I can check if component is ready before getting width and height by calling isComponentComplete and execute my code when it is, but I can't find out when it happens and the initial value of source is skipped when it is not.
Of course I could create slot 'itemReady' and call it from Component.onCompleted, but I have many QMLs using my class and I will create more in the future, so I don't want to make copy-paste job.
I also do not want to set the source in Component.onCompleted.
Connecting to widthChanged, and heightChanged signals isn't also good idea, because I'm resizing my item very frequently, and I don't want to execute my code then.

Is there any way to get completed signal from C++?
EDIT:
I did as @Mitch said - overriten componentComplete method and inside, called it's base class equavilent. isComponentComplete() returns true, but I'm still getting 0 from width() and height() methods:
void MyQQuickItem::componentComplete()
{
    QQuickItem::componentComplete();
    if(isComponentComplete())
    {
        qDebug() << "c++: oncompleted, width,height: " << width() << height(); //gives 0,0
    }

}

Actually I figured out that Component.onCompleted in QML prints 0's too:
...
MyQQuickItem
{
    width: parent.width / 2
    height: parent.height
    source: "someSource"
    Component.onCompleted
    {
        console.log("component onCompleted width, height: ", width, height); //it gives 0 too
    }
}

@derM Component.onCompleted is not emmited by QQuickItem::componentComplete() directly, because it prints its log after the qDebug in c++ above.
So, although it is ready, properties are not initialized.

EDIT2:
Finally I've solved it. The Window was guilty, because it uses contentItem as the parent of his childrens, and in MyQQuickItem Component.onCompleted width and height of contentItem(his parent) are 0.
When I do so:
Window
{
    id: wnd
    width: 640
    height: 480
    Component.onCompleted:
    {
        console.log("Window completed: ", this, width, height);
        console.log("windowContentItem: ", contentItem, width, height);
    }

    MyQQuickItem
    {
        width: parent.width
        height: parent.height
        Component.onCompleted:
        {
            console.log("MyQQuickItem completed: ", this, width, height);
            console.log("MyQQuickItem parent: ", parent, parent.width, parent.height);
        }
    }
}

It prints:
qml: Window completed:  QQuickWindowQmlImpl(0x345b5eb4d0) 640 480
qml: windowContentItem:  QQuickRootItem(0x345e2cdec0) 640 480
qml: MyQQuickItem completed:  MyQQuickItem(0x345b5b99e0) 0 0
qml: MyQQuickItem parent:  QQuickRootItem(0x345e2cdec0) 0 0

So MyQQuickItem parent is Window's contentItem. When I replace
width: parent.width
height: parent.height

to:
width: wnd.width
height: wnd.height

It works perfectly, and in my void MyQQuickItem::componentComplete() I've got width and height initialized as expected.
One thing that I do not understand is why in Window onCompleted, contentItem size is correct, but in MyQQuickItem onCompleted the size is 0,0. If anyone could explain it to me, I would be grateful :P

A:

Qt code uses componentComplete() like so:
void QQuickControl::componentComplete()
{
    Q_D(QQuickControl);
    QQuickItem::componentComplete();
    d->resizeContent();
    // ...
}

You can do something similar, replacing resizeContent() with your function that works on the width and height. Assuming that function is also called whenever source changes, you'd need the isComponentComplete() check. With this approach, you shouldn't have any issues.


Q:

How to solve the error 'AttValue: " or expected?

The following code uses Google API to find the distance between two locations. On running the code, it gave the error as given below. Please suggest how to solve this error.
> gmapsdistance(origin = "PAWTUCKET+LOWELL+MA", destination =
"INDUSTRIAL WAY+SALEM+NH", combinations = "all", mode = "driving", key
= "My_key")

Error:
  1: AttValue: " or ' expected
  2: attributes construct error
  3: Couldn't find end of Start Tag html line 2
  4: Extra content at the end of the document

A:

There are no issues with using spaces my googleway package
library(googleway)

apiKey <- 'your_api_key'

google_distance(origins = list("PAWTUCKET+LOWELL+MA"),
                destinations = list("INDUSTRIAL WAY+SALEM+NH"),
                mode = "driving",
                key = apiKey)

# $destination_addresses
# [1] "Industrial Way, Salem, NH 03079, USA"
#
# $origin_addresses
# [1] "Pawtucket Blvd, Lowell, MA 01854, USA"
#
# $rows
# elements
# 1 23.2 km, 23150, 27 mins, 1648, 27 mins, 1605, OK
#
# $status
# [1] "OK"

Having said that, and as Hack-R alluded to in their answer, your actual error occurs because you have a space in your destination ("INDUSTRIAL WAY+SALEM+NH"). Replace this with a + and it will work.
gmapsdistance(origin = "PAWTUCKET+LOWELL+MA",
              destination = "INDUSTRIAL+WAY+SALEM+NH",
              combinations = "all",
              mode = "driving",
              key = 'api_key')

$Time
[1] 1591

$Distance
[1] 23150

$Status
[1] "OK"

From the documentation ?gmapsdistance

If more than one word for a same location is used, they should be separated by a plus sign e.g. "Bogota+Colombia"

The actual error comes from the XML package, which is used by gmapsdistance under the hood.


Q:

searching database with mongoose api and nodejs?

im using nodejs and mongoose to build an api, im trying to do the search feature, but it deosnt seem to query anything, the code.
app.get('/search', function(req,res){
    return Questions.find({text: "noodles"}, function(err,q){
        return res.send(q);

    });
});

its not giving me any results, i know thier should be at least 4 results from this query, thiers 4 documents in the questions database with the word "noodles", everything is working the the database connection and my node server

A:

What your query is doing is finding documents where the text property matches "noodles" exactly.  Assuming you're trying to query for documents where the text property simply contains "noodles" somewhere, you should use a regular expression instead:
app.get('/search', function(req,res){
    var regex = new RegExp('noodles', 'i');  // 'i' makes it case insensitive
    return Questions.find({text: regex}, function(err,q){
        return res.send(q);
    });
});


Q:

Unable to run a simple JDBC program.

I have been trying to create a simple database application in JAVA using JDBC. So far all my attempts have been unsuccessful in even loading the driver. Understand that I'm novice in Java and just started learning. Here are my steps:

Start > System > Advanced System properties > Environment Variables:
Added CLASSPATH=[path to sqljdbc41.jar]
Added the Driver in the Netbeans
Added the following code:
public class DataSample {
  public static void main(String[] args) throws Exception{
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      Connection cnn=DriverManager.getConnection   ("jdbc:sqlserver://localhost;databaseName=AdventureWorks;");
      Statement st = cnn.createStatement();
      ResultSet rs =st.executeQuery("select * from test");

The program always give this exception:
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:260)
    at datasample.DataSample.main(DataSample.java:21)
Java Result: 1

A:

This is with the help from Mark Rotteveel. Here are the steps. maybe someone else is also having a problem in the same area:

Expand the libraries.

Right click and choose Add jar Files
Add the Sql Server jar file
Add the line to load the driver (see the code in question) and provide the connection string.
I removed the CLASSPATH variable and still works.


Q:

Regarding SEO, is repeating some content in different pages considered as keyword stuffing?

We know that repeating keywords in one page is spam and Google calls it keyword stuffing.
But, if we repeat some content in all pages of a website to help users, is it keyword stuffing too?
For example we have 200 unique words in each page and about 200 other words to describe how to download and how to buy and what other services you may get from this website and etc.
Or if we repeat some keyword in <title> of all pages like this:

Download PDF: Article one
Download PDF: Article two
Download PDF: Article three
etc.

Is repeating Download PDF : Article in titles, spam or keyword stuffing? If not, is it a positive point to get more visitor from Google?

A:

If your repeated content is used to help your users and doesn't content keywords of your website, I don't think it would be considered as keyword stuffing by search engines.
However, if you want to avoid potential duplicate content issues, you can avoid repeating this paragraph over your all pages and migrate it to a new page like an "help center to download a PDF". Then, you put a link to this new page on all your pages.
Otherwise, for repeating keywords in <title> tags, you can do it if it's relevant in relation to your page. I think that Google can understand your pages are created automatically by a script. And don't forget all your <title> tags are unique.

A:

The only consideration I see is that the words download, PDF, and article will become likely the top three or at least within the top ten keywords your site is known for therefore the site topic as seen by Google and/or Bing maybe that of article download. There may be two problems with that:

Your site is not about article downloading. It can dilute the SEO effect of the other keywords your site is known for and the performance of any page on a page by page basis depending and performance overall.
Article sharing sites have been hit hard lately and algorithms exist to identify these sites. There may be a chance that your site will fall into this category. It may be a small chance, but in is in.

Pay attention to the Content Keywords in Google Webmaster Tools. It is critically important that these keywords reflect your site topic before SEO begins. It is the foundation upon which the rest of your work will rest upon.
If you find this is the case, perhaps you can have your cake and eat it too. Only in web design does this work. You can change your links to the PDFs from a text link to an image link and if you repeat the article title in the alt text, then you should be more than okay. In this case, it may be okay to use the terms download, PDF, and article too. Just make sure you are mixing up the alt text with the article title.


Q:

my url does not return nil but empty string in swift

below is the code where based on url I need to get the image.
But url is not nil instead it is double quotes "" or empty string.
Hence how do I handle check for double quotes in swift.
DispatchQueue.global(qos: .background).async { [weak self] () -> Void in

    if let url = NSURL(string: arr[indexPath.row].imgl){

             if let data = NSData(contentsOf: url as URL) {

                  DispatchQueue.main.async {
                     cell.img.image = UIImage(data: data as Data)!
                }
              }
          }
   }

if url is "" then it should go to else part.

A:

Convert this:
NSURL(string: arr[indexPath.row].imgl)

to this:
URL(string: arr[indexPath.row].imgl)

.

how do I handle check for double quotes in swift?

if myString.isEmpty {
   print("its empty. Means it is just two double quotes without anything between")
}


Q:

strange s:url behavier

i just found something funny, i cannot explain it. can someone explain it.
I have define a url in my jsp file
<s:url var="test" action="Home.action" escapeAmp="false">
    <s:param name="departYear" value="2006"/>
    <s:param name="homeTown" value="lanzhou"/>
</s:url>

<s:property value="test"/>

and the result is /path/to/action/Home.action?departYear=2006 and if i change the second parameter <s:param name="homeTown" value="123456"/>, then it shows me properly with /path/to/action/Home.action?departYear=2006&homeTown=123456 I havn't tried to print the url and it works always fine with more parameters. it doesn't triggered any problem at all. I just curious, why it doesn't work with s:property.
btw, i changed the order of 2 parameters too, and it doesn't show the parameter in the url either.
Thanks in advance.

A:

Refer to the documentation... it says that value is an Object, not a string.
<s:param name="homeTown" value="lanzhou"/> would call the getLanzhou() method of your action class to try and populate the value.
What you want is <s:param name="homeTown" value="%{'lanzhou'}"/>
<s:param name="departYear" value="2006"/> works because non-String attribute types are not parsed, but evaluated directly as an expression.


Q:

How to go back to previous ViewController in Xamarin.IOS

I make an app in VisualStudio Xamarin (not Xamarin.Forms) with two view controller. First view controller is list of items, second contain item's detail info. When user tap item in list, second view opens with code
DetailViewController detailController = this.Storyboard.InstantiateViewController("DetailViewController") as DetailViewController;
detailController._idx = idx;
this.NavigationController.PushViewController(detailController, true);

But I don't know how to go back to first ViewController programmatically - for example there are button "Go Back" on DetailViewController
I try to use this code:
backButton.TouchUpInside += (s,e) => {
  this.NavigationController.DismissViewController(true, null)
};

But it doesn't give any result.
Can anybody help me with this?
UPDATED
I changed code to:
backButton.TouchUpInside += (s,e) => {
  this.NavigationController.DismissViewController(true, async () => { await DismissViewControllerAsync(true); });
  ListViewController listController = this.Storyboard.InstantiateViewController("ListViewController ") as ListViewController;
  this.NavigationController.PresentViewController(listController, true, null);
}

This work for "Go back", but when I try to choose same or another item in list and open new DetailViewController, it throw exception "System.NullReferenceException: Object reference not set to an instance of an object" on
this.NavigationController.PushViewController(detailController, true);

(In details - I run app, ListViewController opens, I choose item1, DetailViewController opens, I tap BackButton, ListViewController opens, I chhose any item, Exception)

A:

You got Push,Pop and Present,Dismiss mixed up.
When the viewcontroller is put inside Navigation, you should use push and pop to control the stack.
Modify your code :
backButton.TouchUpInside += (s,e) => {
  this.NavigationController.PopViewController(true);
}

Refer to
Presenting a View Controller
UINavigationController


Q:

accessing child namespaced controllers from a parent controller

recently i came across problem problem in accessing the namespaced controllers i have a parent controller in education/educations_controller.rb as
class Education::EducationssController < ApplicationController
   def process_educations
     if highschool
       controller_to_redirect = 'highschool'
     if bacholors
       controller_to_redirect = 'bacholors'
     else
       controller_to_redirect = 'masters'
     end
    redirect_to :controller => controller_to_redirect, :action => 'process_educations'
   end
end

And three child controllers education/highschool_controller.rb , education/bacholors_controller.rb , education/masters_controller.rb with all the parametes present in educations_controller.rb passing to these controllers
class Education::HighschoolController < Education::EducationssController
   def proceed_educations
     do some process
   end
end

class Education::BacholorsController < Education::EducationssController
   def proceed_educations
     do some process
   end
end

class Education::MastersController < Education::EducationssController
   def proceed_educations
     do some process
   end
end

And respective views come after that but in this process the url becomes too long so i wanted to remove all the controllers from the url and then process so irrespective of anything user is taken  to same url, for this i changed routes.rb as
namespace :educations,:path => '' do
  scope "/educations" do
   get 'proceed_educations',to:'educations#proceed_educations'
   post 'proceed_educations',to:'educations#proceed_educations'
  end
  resource :highschool ,:path => '' do
   get 'proceed_educations',to:'highschool#proceed_educations'
   post 'proceed_educations',to:'highschool#proceed_educations'
  end
  resource :bacholors ,:path => '' do
   get 'proceed_educations',to:'bacholors#proceed_educations'
   post 'proceed_educations',to:'bacholors#proceed_educations'
  end
  resource :masters ,:path => '' do
   get 'proceed_educations',to:'masters#proceed_educations'
   post 'proceed_educations',to:'masters#proceed_educations'
  end
end

This generated the same url for every controller but when i try to access them as in educations_controller.rb they always redirect to same controller HighschoolController.
I am not getting where i am doing things wrong, please help me understand this process, or if there is any better way of doing this then please suggest.

A:

If you want to avoid making the same URLs for two namespaced controllers, it will be difficult for the rails to understand which controller to send which request.
However, what you can do is, in your routes.rb, you can eliminate showing controller names and can add space there for differentiation, like this:
namespace :educations,:path => '' do
  scope "/educations",:path => '' do
   get 'proceed_educations',to:'educations#proceed_educations',:path => ''
   post 'proceed_educations',to:'educations#proceed_educations',:path => ''
  end
  resource :highschool ,:path => '' do
   get 'proceed_educations',to:'highschool#proceed_educations'
   post 'proceed_educations',to:'highschool#proceed_educations'
  end
  resource :bacholors ,:path => ' ' do
   get 'proceed_educations',to:'bacholors#proceed_educations',:path => ''
   post 'proceed_educations',to:'bacholors#proceed_educations',:path => ''
  end
  resource :masters ,:path => '  ' do
   get 'proceed_educations',to:'masters#proceed_educations',:path => ''
   post 'proceed_educations',to:'masters#proceed_educations',:path => ''
  end
end

This way, the URL will be same but with extra spaces.


Q:

Unregistered values of rel attribute in anchor tag

I used rel values in jQuery for the parametrized (#!hashbang) AJAX calls.
contact

and with jQuery:
var hashbang = "#!"+$("#_qualifier").attr('rel'); //gives desired result=>"#!telephony"

But, when I validated the page on validator.w3.org, it gave me error:

Bad value #telephony for attribute rel on element a: Keyword #telephony is not registered.

I searched around and according to the HTML5 specs here and here, the rel attribute should have the registered/pre-defined values.

Is there a work around to use custom values for rel in HTML5, without failing the validation?
Is it also invalid for HTML4 doctypes?

A:

You can use custom attributes:
...

It is HTML5 compliant, but not HTML4 or xHTML.
You'll access the attribute just like you did with jQuery.
You can find more informations on the HTML5 reference.


Q:

Is there a limit of sqoop.export.records.per.statement for Sqoop Export job?

Does anyone know if there is a limit for the value of sqoop.export.records.per.statement for Sqoop batch export job?
I have very large size of data, like 200,000,000 rows of data to export, from Impala to Vertica. I will get [Vertica][VJDBC](5065) ERROR: Too many ROS containers exist for the following projections if records per statement is set too low, or java.lang.OutOfMemoryError: GC overhead limit exceeded if records per statement is set too high.
Anyone know how to fix this problem? Thanks!

A:

I think the limit is that of memory.  If you increase the heap it'll let you set the number higher.  Try adding -D mapred.child.java.opts=-Xmx1024M or some larger number than your current settings?
You could try to increase export.statements.per.transaction and reduce your records per statement. I'm thinking this won't help on the ROS container side because I am thinking each batch of SQL = 1 COPY statement = 1 ROS container.  I don't think it'll convert multiple batches of INSERTs into a single COPY, but I don't have a way to test it right now.
You could bypass sqoop and stream the data (You may need to construct the COPY), something like:
impala-shell -k -i server:port -B -q 'select * from mytable' --output_delimiter="|" | vsql -h database_host -U user -w password -c 'copy mytable from stdin direct'


Q:

Node js multiple routes get socket

I am using NodeJS, socket.io and express to create an application and I am wondering how can I determinate which socket (id/user) is on which router?
For example I have 10 users on my website, and I have 3 routes: /home, /about, /contact. How can I know which user is on which router?

A:

Firstly to know "which user" itself you'll need a system with sessions and cookies to identify a particular user each time they make a different request. Passport.JS makes this really easy.
Secondly to share this same user among Express route and Socket.io handler would require sharing the session information between the two. For Passport.js there's socket.io-passport that does this.
Lastly, when client-side Socket.io initiates a connection request to the server by io.connect() it sets the referrer header of the request to current URL, which can be accessed on server-side with socket.request.headers.referer
With all that in place you'll finally be able to tell which user is on which route:
app.get('/about', function(req, res, next){
    // req.user is on '/about' path
});

var URL = require('url');
io.on('connection', function(socket) {
    var user = socket.request.user;
    var path = URL.parse(socket.request.headers.referer).path;
    // user is on -> path
});


Q:

Get names in Pandas groupby

I have a data frame of log-data looking like this:
date    url users
0   2019-09-12  http://example.com/?url=001 45
1   2019-09-12  http://example.com/?url=002 12
2   2019-09-12  http://example.com/?url=003 17
3   2019-09-12  http://example.com/?url=004 87
4   2019-09-12  http://example.com/?url=005 4

I need to extract the top three urls by visitors per day.
If I do this:
df.groupby(['date'])['users'].nlargest(3)

I almost get what I want:
2019-09-12  183    88
            132    62
            49     41
2019-09-13  275    95
            336    65
            206    18

However, instead of the numbers, 183, 132 and so forth, I need the url like this:
2019-09-12  http://example.com/?url=001    88
            http://example.com/?url=002    62
            http://example.com/?url=003    41
2019-09-13  http://example.com/?url=004    95
            http://example.com/?url=002    65
            http://example.com/?url=001    18

If I add url like this:
df.groupby(['date','url'])['users'].nlargest(3)

I lose the url-info completely. How can I fix this?

A:

Only add DataFrame.set_index:
df = df.set_index('url').groupby(['date'])['users'].nlargest(3)
print (df)
Int64Index([0, 1, 2, 3, 4], dtype='int64')
date        url
2019-09-12  http://example.com/?url=004    87
            http://example.com/?url=001    45
            http://example.com/?url=003    17
Name: users, dtype: int64

Or use DataFrame.sort_values with ascending=[True, False] and GroupBy.head:
df = df.sort_values(['date', 'users'], ascending=[True, False]).groupby('date').head(3)

Test in changed data:
print (df)
         date                          url  users
0  2019-09-12  http://example.com/?url=001     45
1  2019-09-12  http://example.com/?url=002     12
2  2019-09-13  http://example.com/?url=003     17
3  2019-09-13  http://example.com/?url=004     87
4  2019-09-13  http://example.com/?url=005      4

df1 = df.set_index('url').groupby(['date'])['users'].nlargest(3)
print (df1)
date        url
2019-09-12  http://example.com/?url=001    45
            http://example.com/?url=002    12
2019-09-13  http://example.com/?url=004    87
            http://example.com/?url=003    17
            http://example.com/?url=005     4
Name: users, dtype: int64

df2 = df.sort_values(['date', 'users'], ascending=[True, False]).groupby('date').head(3)
print (df2)
         date                          url  users
0  2019-09-12  http://example.com/?url=001     45
1  2019-09-12  http://example.com/?url=002     12
3  2019-09-13  http://example.com/?url=004     87
2  2019-09-13  http://example.com/?url=003     17
4  2019-09-13  http://example.com/?url=005      4


Q:

Is there any way to save time using of "Cross" or "Table"?

I need to solve a equation by NDSlove, so I write the equation first, but it takes me a lot of time.
The follow is my code
energy = Subdivide[0, 50, 5];
theta0 = Reverse[N[ArcSin[Subdivide[0, 1, 5]]]]
theta = Cos[
   ArcSin[(R Sin[theta0])/Sqrt[
    t^2 + 2 R t Cos[theta0] + R^2 Cos[theta0]^2 + R^2 Sin[theta0]^2]]];
ni = Length[theta];nj = Length[energy];
Ebare = 10;Ebaree = 15;Ebarx = 24;betae = 0.315;betaee = 0.21;betax = 0.131;R = 10;
Fj = Compile[{{x, _Real}}, (
    betae (betae x)^2)/((E^(betae x) + 1) Ebare) + (
    betax (betax x)^2)/((E^(betax x) + 1) Ebarx)];
Fjbar = Compile[{{x, _Real}}, ((
     betaee (betaee x)^2)/((E^(betaee x) + 1) Ebaree) + (
     betax (betax x)^2)/((E^(betax x) + 1) Ebarx)) ];
For[j = 2, j <= nj, j++,
  For[i = 1, i <= ni, i++,
   P[theta0[[i]], energy[[j]], t] = {Px[theta0[[i]], energy[[j]], t],
     Py[theta0[[i]], energy[[j]], t],
     Pz[theta0[[i]], energy[[j]], t]}]];
For[j = 2, j <= nj, j++,
  For[i = 1, i <= ni, i++,
   Pbar[theta0[[i]], energy[[j]],
     t] = {Pbarx[theta0[[i]], energy[[j]], t],
     Pbary[theta0[[i]], energy[[j]], t],
     Pbarz[theta0[[i]], energy[[j]], t]}]];
Clear["i", "j"];
timing = AbsoluteTiming[
   MPP = Flatten[
     ParallelTable[D[P[theta0[[i]], energy[[j]], t], t] ==
       Cross[Sum[(1 - theta[[ii]] theta[[i]]) (theta[[ii]] -
            theta[[ii -
               1]]) Sum[(Fj[energy[[jj]]] P[theta0[[ii]],
                energy[[jj]], t] -
              Fjbar[energy[[jj]]] Pbar[theta0[[ii]], energy[[jj]],
                t]) (energy[[jj]] - energy[[jj - 1]]), {jj, 2,
            nj}], {ii, 2, ni}], P[theta0[[i]], energy[[j]], t]], {i,
       1, ni}, {j, 2, nj}]]];
timing[[1]]

I run the former code in a HPC which have 16 kernels, when ni=nj=6, the output is 301..., when ni=6, nj=8 the output is 1229...s, as you can find the time used arise quiet quickly. And what final I want is ni=80, nj=32, I can't accept the time used of this.
So, is there anyway to save time to do Table or Cross. Thanks for any suggestions.

A:

Here's a 51 x 31 computation taking around a minute without parallelization. All I really did was precompute the cross product and substitute the components.  Perhaps Cross[] does some symbolic operations that are avoided this way.  The 6 x 6 calculation took around 0.03 seconds.
energy = Subdivide[0., 50., 50];
theta0 = Reverse[N[ArcSin[Subdivide[0., 1., 30]]]];
(* ... *)

timing = AbsoluteTiming[
   MPP = Flatten[
     Table[D[P[theta0[[i]], energy[[j]], t],
        t] == (Cross[{a, b, c}, {d, e, f}] /.
         Thread[{a, b, c, d, e, f} ->
           Join[Sum[(1 - theta[[ii]] theta[[i]]) (theta[[ii]] -
                theta[[ii -
                   1]]) Sum[(Fj[energy[[jj]]] P[theta0[[ii]],
                    energy[[jj]], t] -
                  Fjbar[energy[[jj]]] Pbar[theta0[[ii]], energy[[jj]],
                     t]) (energy[[jj]] - energy[[jj - 1]]), {jj, 2,
                nj}], {ii, 2, ni}],
            P[theta0[[i]], energy[[j]], t]]]), {i, 1, ni}, {j, 2,
       nj}]]];
timing[[1]]

(*  67.5372  *)

Compile isn't always faster, especially when the code depends heavily on external variables.  The following changes reduces the computation to 42.3379 seconds:
Fj = Compile[{{x, _Real}}, (betae (betae x)^2)/((E^(betae x) +
          1) Ebare) + (betax (betax x)^2)/((E^(betax x) + 1) Ebarx) //
     Evaluate];
Fjbar = Compile[{{x, _Real}}, ((betaee (betaee x)^2)/((E^(betaee x) +
           1) Ebaree) + (betax (betax x)^2)/((E^(betax x) +
           1) Ebarx)) // Evaluate];

If you don't compile the expressions at all, it takes 45.0974 sec., which shows how little Compile helps in this application.


Q:

little problem about open set in the definition of topology

Definition 1
Let $X$ be a set of points. A collection of subsets $U = \left\{U_{\alpha }\right\}$ forms a topology on $X$ if

Any arbitrary union of the $U_{\alpha }$ is another set in the collection $U$.

The intersection of any finite number of sets $U_{\alpha }$ in the collection $U$ is another set in $U$.

Both the empty set $\emptyset$ and the whole space $X$ must be in $U$.

The pair $(X, U)$ is called a topological space.
The sets $U_{\alpha }$ in the collection $U$ are called open sets.

My Question

Is a finite isolated points set an open set? At present I think it is a closed set.

Does Definition 1 suit for a finite isolated points set? It seems it just call $U_{\alpha }$ open sets without defining?

A:

You hit upon the right answer in your second question - for general topologies, a set is open if it belongs to the collection $U$, so indeed open is just a name for sets in your collection.
This means that any set $S\subset X$ can be open in some topology, providing you can find some collection $U$ containing $S$ that satisfies the three axioms you listed. As taking $U$ to be all subsets of $X$ works, we can conclude that any subset of $S$ is open in some topology on $X$.
The overall conclusion is that you cannot conclude that a particular set is open or not without considering the chosen topology. In particular, a finite set of points could be open, closed, neither or both depending on the chosen topology.
It's also worth noting that a point can only be called isolated once you have a notion of topology. I could put the topology on the set $S=\{x,y\}$ such that only $\varnothing$ and $S$ are open, and then neither point is isolated.

A:

To answer your first question: Finite sets can be open, closed, both or neither depending on your topology. I'll give some examples of topological spaces where these possibilities occur in the form $(X,U)$. For $X$, I will always choose $\mathbb{R}$, but my $U$ will vary:

$(\mathbb{R},\{\varnothing,\{0\},\mathbb{R}\})$ - In this topological space $\{0\}$ is open but not closed.
$\mathbb{R}$ with its usual (metric) topology - In this space any finite set is closed, but not open.
$(\mathbb{R},2^\mathbb{R})$, the so called discrete topology on $\mathbb{R}$ - In this topology every set (finite or infinite) is open and closed.
$(\mathbb{R},\{\varnothing,\mathbb{R}\})$, the so called indiscrete topology on $\mathbb{R}$ - In this topology the only open sets as well as the only closed sets are $\varnothing$ and $\mathbb{R}$, hence all finite non-empty sets are neither open nor closed.

It is a good exercise to check that all the above are actually topological spaces by your definition.
To answer your second question: I think you are confused about what is being defined. Definition 1 is a definition of topological spaces, not of open sets.


Q:

update table using select from one table records that doesnt' exist in another

I know basic SQL, but not complex.
I have two tables [Table 1 & Table 2] which has username and memberid common in both. There are records in Table 1 where it doesn't exist in Table 2.
For ex. if i needed to pull all the records from Table 1 which doesn't have a matching record in Table 2, using the username as filter, I will write something like this:
select * from Table1 a
  where  not exists (select * from Table2 b
                 where b.MemberID = a.MemberID) and UserName like 'b%'

That was easy. But, how do I update all these results with a different username ?.
I'm trying to find all the records in Table1 for the same username  which doesn't have a matching record in Table 2, and then update those records with my username ('r%').
I know some will ask, what have you tried...I have tried to use the 2 queries as single, but getting lots of error...for ex:
update Table1
   set UserName = (select * from Table1 a
   where  not exists (select * from Table2 b
     where b.MemberID = a.MemberID) and UserName = 'r@gmail.com')

Any help is appreciated.

A:

Try this
UPDATE TAB1
SET    USERNAME = (SELECT TOP 1 USERNAME
                   FROM   TABLE1 A
                   WHERE  USERNAME LIKE 'r%')
FROM   TABLE1 TAB1
WHERE  NOT EXISTS (SELECT 1
                   FROM   TABLE2 B
                   WHERE  B.MEMBERID = TAB1.MEMBERID)
       AND TAB1.UserName LIKE 'b%'


Q:

exiting functions in main

I am relatively new to Stackoverflow and Java, but I have a little experience in C. I liked the very clean way of C exiting the programs after a malfunction with the 'exit()' function.
I found a similar function System.exit() in Java, what differs from the C function and when should I use a 'System.exit()' best instead of a simple 'return' in Java like in a void main function?

A:

System.exit() will terminate the jvm initilized for this program, where return; just returns the control from current method back to caller

Also See

when-should-we-call-system-exit-in-java ?

A:

System.exit() will exit the program no matter who calls it or why. return in the main will exit the main() but not kill anything that called it. For simple programs, there is no difference. If you want to call your main from another function (that may be doing performance measurements or error handling) it matters a lot. Your third option is to throw an uncaught runtime exception. This will allow you to exit the program from deep within the call stack, allow any external code that is calling your main a programmatic way to intercept and handle the exit, and when exiting, give the user context of what went wrong and where (as opposed to an exit status like 2).


Q:

Como saber quando um elemento ta no topo da pagina

Estou desenvolvendo um website no estilo one page com várias seções(sobre, contato, serviços por exemplo)
E um menu fixo, a ideia é conforme o usuário for rolando a pagina o menu fixo iria alterando os links ativos, ou seja quando estivesse na seção contato, no menu fixo o link contato ficasse "ativo"
Minha duvida é, como saber quando a seção passou pelo topo da pagina, pois assim conseguiria remover a colocar os links como ativo, obs: utilizo jquery.
Caso tenham interesse esse é o site http://mkmseguranca.com.br/

A:

Você precisa verificar a posição da rolagem em cada ação - de rolagem.
Então:
$(window).scroll(function () {
   var divAtiva;
   $.each($("#conteudo .div-interna"), function (indice, obj) {
      if (!divAtiva || ($(this).scrollTop() >= $(obj).offset().top * 0.80 && divAtiva.top < $(obj).offset().top * 0.80))
         divAtiva = { elementId: $(obj).attr("id"), top: $(obj).offset().top };
  });
  MetodoQueSelecionaOMenu(divAtiva);
});

Supondo que sua estrutura seja algo semelhante a:

...

...

...

Levei em consideração que você gostaria de selecionar a div ativa quando a rolagem atingisse 80% do seu top, ok? Diferente disso é só ir alterando o cálculo aqui: $(obj).offset().top * 0.80 para o valor que quiser.
(=


Q:

EhCache 3.1.3 persistence issue

I'm having issues with persistence in ehcache. The cache itself works fine when first started but it does not remember the old values when I restart my tomcat servlet.
Here's my code for initializing ehcache. I'm not using any xml.
import org.ehcache.Cache;
import org.ehcache.PersistentCacheManager;
import org.ehcache.Status;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;

PersistentCacheManager persistentCacheManager =
    CacheManagerBuilder.newCacheManagerBuilder()
            .with(CacheManagerBuilder.persistence("/cache"))
            .withCache("test-cache",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(
                            Integer.class, String.class,
                            ResourcePoolsBuilder.newResourcePoolsBuilder()
                                    .heap(1, EntryUnit.ENTRIES)
                                    .offheap(1, MemoryUnit.MB)
                                    .disk(20, MemoryUnit.MB)
                    )
            ).build(true);
Cache cache = persistentCacheManager.getCache("test-cache", Integer.class, String.class);

log.info("Cache get 1 before putting: " + cache.get(1));
for(int i = 0; i< 1000; i++) {
    cache.put(i,"Hello");
}
log.info("Cache get 1 after putting: " + cache.get(1));

Result of the "before" log statement is always null after a restart.

A:

You need to declare your disk ressource pool as persistent. It is not by default.
.disk(20, MemoryUnit.MB, true)

Then your test works perfectly.
The complete code including closing the cache manager:
import org.ehcache.Cache;
import org.ehcache.PersistentCacheManager;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.ehcache.config.builders.CacheConfigurationBuilder.*;
import static org.ehcache.config.builders.CacheManagerBuilder.*;
import static org.ehcache.config.builders.ResourcePoolsBuilder.*;

public class Main {

  private static final Logger log = LoggerFactory.getLogger(Main.class);

  public static void main(String[] args) {
    try(PersistentCacheManager persistentCacheManager =
        newCacheManagerBuilder()
            .with(persistence("cache"))
            .withCache("test-cache",
                newCacheConfigurationBuilder(
                    Integer.class, String.class,
                    newResourcePoolsBuilder()
                        .heap(1, EntryUnit.ENTRIES)
                        .offheap(1, MemoryUnit.MB)
                        .disk(20, MemoryUnit.MB, true)
                )
            ).build(true)) {
      Cache cache = persistentCacheManager.getCache("test-cache", Integer.class, String.class);

      log.info("Cache get 1 before putting: " + cache.get(1));
      for (int i = 0; i < 1000; i++) {
        cache.put(i, "Hello");
      }
      log.info("Cache get 1 after putting: " + cache.get(1));
    }
  }
}


Q:

Python smtplib: How to send messages that look like emails sent from email account

I am trying to send myself text messages using Python. To do so, I created a gmail account, turned on less secure apps, and ran the following code:
import smtplib
from email.mime.text import MIMEText

# Establish a secure session with gmail's outgoing SMTP server using your gmail account
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login('me@gmail.com', 'pw!' )

msg = '\r\n'.join([
  'From: me@gmail.com',
  'To: 5551234567@tmomail.net',
  'Subject: Cats',
  '',
  'on wheels'
])

# sendmail(from, to, msg)
server.sendmail('me@gmail.com', '5551234567@tmomail.net', msg)

This does indeed send a text message to my phone, but the message displays like this:
me@gmail.com / Cats / on wheels

Also, the "from" agent in my text message list shows up as a random hyphenated pair of numbers, like "970-2" or "910-2".
However, when I send a message from gmail itself to my phone number, it shows up in my list of text messages as being from "me@gmail.com" and displays like this:
Subject is here
Body of email is here

Is there a way for me to change my msg object above to make messages sent from Python display like those sent from Gmail itself?
Any suggestions others can offer on this question would be hugely helpful!

A:

To figure this out, I sent an email from Gmail, then clicked on the three dots next to the sent message and clicked "Show Original", which displayed the full packet of data delivered by the Gmail server. Then I just added those fields to my message:
import smtplib
import email.mime.multipart

# Establish a secure session with gmail's outgoing SMTP server using your gmail account
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login('me@gmail.com', pw)

msg = '\r\n'.join([
  'MIME-Version: 1.0',
  'Date: Fri, 22 Feb 2019 11:29:27 -0500',
  'Message-ID: <CAKyky413ikdYD4-Oq_H_FPF-g__weSFehQNLVuspotupWhJaLA@mail.gmail.com>',
  'Subject: wow on what',
  'From: Ludwig Wittgenstein <me@gmail.com>',
  'To: 5551234567@tmomail.net',
  'Content-Type: multipart/alternative; boundary="0000000000003c664305827e1862"',
  '',
  '--0000000000003c664305827e1862',
  'Content-Type: text/plain; charset="UTF-8"',
  '',
  'weeeee',
  '',
  '--0000000000003c664305827e1862',
  'Content-Type: text/html; charset="UTF-8"',
  'Content-Transfer-Encoding: quoted-printable',
  '',
  '
here=C2=A0
',
  ''
  '--0000000000003c664305827e1862--'
])

# sendmail(from, to, msg)
server.sendmail('me@gmail.com', '5551234567@tmomail.net', msg)


Q:

How to write in chunks by multiple ranks using parallel HDF5

I have dataset of 20X20. I want to write it in chunks of 2X2 by 4 ranks in parallel. I am using parallel HDF5. Now each rank has 25 chunks to write. I am not understanding how to code for this as when I use plain chunking, all ranks write the entire 20X20 dataset. When I use hyperslab, I do not know how to set it for multiple chunks written by each rank. Does anyone has any pointers for me? I am really stuck.

A:

I'm not too sure I fully understand what your asking. So here's how I interpret your question.

Global domain is 20x20
4 MPI ranks
Chunking is 2x2

You don't have to set the chunking, in fact I usually don't.

Here's how I would do it.

Domain decomposition in MPI.
Generate a local matrix.
Create a memory hyperslab (based off the local matrix).
Create a file hyperslab (based off the global matrix).
Create the dataset chunking property.
Write the dataset.

Here's what it looks like.

! Program to use MPI_Cart and Parallel HDF5
!
program hdf_pwrite

        use mpi
        use hdf5
        use kinds, only : r_dp

        implicit none

        ! Local array size with halo
        integer, parameter :: g_N   = 20
        integer, parameter :: ndims = 2
        integer, parameter :: halo  = 0

        integer :: argc         ! Number of command line arguments
        integer :: ierr         ! Error status
        integer :: id           ! My rank/ID
        integer :: np           ! Number of processors
        integer :: iunit        ! File descriptor
        integer :: i,j          ! Loop indexers
        integer :: n(ndims)     ! Local N for i and j directions
        integer :: total(ndims) ! Local total dimension size

        ! MPI IO/Lustre file striping
        integer :: lcount       ! Lustre count size
        integer :: lsize        ! Lustre stripe size
        character(len=1024) :: clcount, clsize ! Strings of LFS

        integer :: info                 ! MPI IO Info
        integer :: m_dims(ndims)        ! MPI cart dims
        integer :: coords(ndims)        ! Co-ords of procs in the grid
        logical :: is_periodic(ndims)   ! Periodic boundary conditions
        logical :: reorder              ! Reorder the MPI structure
        integer :: MPI_COMM_2D          ! New communicator

        character(len=1024) :: filename
        integer(kind=hid_t) :: p_id, f_id, x_id, d_id, c_id
        integer(kind=hid_t) :: memspace, filespace
        ! Chunk sizes
        integer(kind=hsize_t) :: c_size(ndims)
        ! Local hyper slab info
        integer(kind=hsize_t) :: d_size(ndims), s_size(ndims), h_size(ndims), &
                                 stride(ndims), block(ndims)
        ! Global hyper slab info
        integer(kind=hsize_t) :: g_size(ndims), g_start(ndims)

        ! Local data array
        real(kind=r_dp), allocatable :: ld(:,:)

        argc = 0
        ierr = 0
        m_dims = (/ 0, 0/)
        is_periodic = .false.      ! Non-periodic
        reorder     = .false.      ! Not allowed to reorder

        call mpi_init(ierr)

        ! Set up the MPI cartesian topology
        call mpi_comm_size(MPI_COMM_WORLD, np, ierr)
        call mpi_dims_create(np, ndims, m_dims, ierr)

        call mpi_cart_create(MPI_COMM_WORLD, ndims, m_dims, is_periodic, &
                             reorder, MPI_COMM_2D, ierr)
        call mpi_comm_rank(MPI_COMM_2D, id, ierr)
        call mpi_cart_coords(MPI_COMM_2D, id, ndims, coords, ierr)

        if (id .eq. 0) then
                if (mod(g_N,np) .ne. 0) then
                        write(0,*) 'Must use divisiable number of procs.'
                        call mpi_abort(MPI_COMM_WORLD, 1, ierr)
                endif

                ! get the filename
                argc = command_argument_count()
                if (argc .lt. 1 ) then
                        write(0, *) 'Must supply a filename'
                        call exit(1)
                endif
                call get_command_argument(1, filename)
        endif

        ! Broadcast the filename
        call mpi_bcast(filename, len(filename), MPI_CHAR, 0, &
                       MPI_COMM_WORLD, ierr)

        ! Init the HDF5 library
        call h5open_f(ierr)

        ! Set a stripe count of 4 and a stripe size of 4MB
        lcount = 4
        lsize  = 4 * 1024 * 1024
        write(clcount, '(I4)') lcount
        write(clsize, '(I8)') lsize

        call mpi_info_create(info, ierr)
        call mpi_info_set(info, "striping_factor", trim(clcount), ierr)
        call mpi_info_set(info, "striping_unit", trim(clsize), ierr)

        ! Set up the access properties
        call h5pcreate_f(H5P_FILE_ACCESS_F, p_id, ierr)
        call h5pset_fapl_mpio_f(p_id, MPI_COMM_2D, info, ierr)

        ! Open the file
        call h5fcreate_f(filename, H5F_ACC_TRUNC_F, f_id, ierr, &
                         access_prp = p_id)
        if (ierr .ne. 0) then
                write(0,*) 'Unable to open: ', trim(filename), ': ', ierr
                call mpi_abort(MPI_COMM_WORLD, 1, ierr)
        endif

        ! Generate our local matrix
        do i = 1, ndims
                n(i) = g_N / m_dims(i)
                total(i) = n(i) + (2 * halo)
        end do
        if (halo .ne. 0) then
                allocate(ld(0:total(1)-1, 0:total(2)-1), stat=ierr)
        else
                allocate(ld(total(1),total(2)), stat=ierr)
        end if
        if (ierr .ne. 0) then
                write(0,*) 'Unable to allocate local data array: ', ierr
                call mpi_abort(MPI_COMM_WORLD, 1, ierr)
        end if

        ld = -99.99
        ! init the local data
        do j = 1, n(2)
                do i = 1, n(1)
                        ld(i,j) = id
                enddo
        enddo

        ! Create the local memory space and hyperslab
        do i = 1, ndims
                d_size(i) = total(i)
                s_size(i) = n(i)
                h_size(i) = halo
                stride(i) = 1
                block(i)  = 1
        enddo

        call h5screate_simple_f(ndims, d_size, memspace, ierr)
        call h5sselect_hyperslab_f(memspace, H5S_SELECT_SET_F, &
                                   h_size, s_size, ierr,       &
                                   stride, block)

        ! Create the global file space and hyperslab
        g_size  = g_N
        do i = 1, ndims
                g_start(i) = n(i) * coords(i)
        enddo

        call h5screate_simple_f(ndims, g_size, filespace, ierr)
        call h5sselect_hyperslab_f(filespace, H5S_SELECT_SET_F, &
                                   g_start, s_size, ierr,       &
                                   stride, block)

        ! Create a data chunking property
        c_size = 2
        call h5pcreate_f(H5P_DATASET_CREATE_F, c_id, ierr)
        call h5pset_chunk_f(c_id, ndims, c_size, ierr)
        ! Create the dataset id
        call h5dcreate_f(f_id, "/data", H5T_IEEE_F64LE, filespace, d_id, &
                         ierr, dcpl_id=c_id)

        ! Create a data transfer property
        call h5pcreate_f(H5P_DATASET_XFER_F, x_id, ierr)
        call h5pset_dxpl_mpio_f(x_id, H5FD_MPIO_COLLECTIVE_F, ierr)
        ! Write the data
        call h5dwrite_f(d_id, H5T_IEEE_F64LE, ld, s_size, ierr,         &
                        file_space_id=filespace, mem_space_id=memspace, &
                        xfer_prp=x_id)

        if (allocated(ld)) then
                deallocate(ld)
        endif

        ! Close everything and exit
        call h5dclose_f(d_id, ierr)
        call h5sclose_f(filespace, ierr)
        call h5sclose_f(memspace, ierr)
        call h5pclose_f(c_id, ierr)
        call h5pclose_f(x_id, ierr)
        call h5pclose_f(p_id, ierr)
        call h5fclose_f(f_id, ierr)
        call h5close_f(ierr)

        call mpi_finalize(ierr)
end program hdf_pwrite

For completeness here's the definition of kinds.
module kinds

        use, intrinsic                               :: iso_fortran_env

        implicit none

        private
        public  :: i_sp, i_dp,      &
                   r_sp, r_dp, r_qp

        integer, parameter                           :: i_sp = INT32
        integer, parameter                           :: i_dp = INT64

        integer, parameter                           :: r_sp = REAL32
        integer, parameter                           :: r_dp = REAL64
        integer, parameter                           :: r_qp = REAL128

end module kinds

Then compiling, running and looking at the output file:
$ make
rm -f kinds.o kinds.mod
h5pfc -c -O3  -o kinds.o kinds.f90
rm -f hdf_pwrite.o hdf_pwrite.mod
h5pfc -c -O3  -o hdf_pwrite.o hdf_pwrite.f90
h5pfc -O3  -o hdf_pwrite kinds.o hdf_pwrite.o

$ mpiexec -np 4 ./hdf_pwrite test.h5

$ h5dump test.h5
HDF5 "test.h5" {
GROUP "/" {
   DATASET "data" {
      DATATYPE  H5T_IEEE_F64LE
      DATASPACE  SIMPLE { ( 20, 20 ) / ( 20, 20 ) }
      DATA {
      (0,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (1,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (2,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (3,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (4,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (5,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (6,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (7,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (8,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (9,0): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      (10,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (11,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (12,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (13,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (14,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (15,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (16,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (17,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (18,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      (19,0): 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
      }
   }
}
}

Hope this helps.
Edit:
Of course you should use a better algorithm to do the domain decomposition, something like MPE_Decomp1d.


Q:

What is the syntax error in Create table statement?

I'm sorry if this is too easy, but I'm tired and cannot seem to solve this on my own. Can anyone see what is wrong with this command?
create table Users (
   user_id NUMBER(4) PRIMARY KEY ,
   username VARCHAR2(16) NOT NULL,
   password VARCHAR2(16) NOT NULL,
   first_name VARCHAR2(20) NOT NULL,
   last_name VARCHAR2(20) NUT NULL,
);

Edit: Thanks all. Problem solved. It was the last comma and the NUT :P

A:

Do this
create table Users (
    user_id numeric(4) PRIMARY KEY ,
    username VARCHAR(16) NOT NULL,
    password VARCHAR(16) NOT NULL,
    first_name VARCHAR(20) NOT NULL,
    last_name VARCHAR(20) NOT NULL
);

I Changed:

number to numeric
removed last comma
varchar2 to varchar
NUT to NOT

A:

Try removing the last comma and change NUT to NULL.


Q:

Split array into chunks of random lengths between a given range

I need some help here please.
So I have the following array:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

I am trying to split this array into chunks with lengths between a given range
const minChunkSize = 2;
const maxChunkSize = 5;

So the chunk size can be anything between minChunksize and maxChunkSize randomly generated.
Possible outputs:
[[1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
or
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
or
[[1, 2], [3, 4, 5, 6, 7], [8, 9, 10]]
or
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

etc...

Thank you for your help!

A:

This is a little inefficient, but you can create a recursive method that progressively slice() a random number (between some min and max) of elements from the array. If the final generated result have some() array with a length less than the minimum, then the method recall itself.

const randSplit = (arr, min, max) =>
{
    // Check arguments.

    if (min > arr.length || max <= min)
        return [arr];

    let res = [], i = 0, rnd;

    while (i < arr.length)
    {
        rnd = Math.floor(Math.random() * (max - min)) + min;
        res.push(arr.slice(i, i + rnd));
        i += rnd;
    }

    if (res.some(x => x.length < min))
        return randSplit(arr, min, max)
    else
        return res;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(JSON.stringify(randSplit(arr, 2, 5)));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


Q:

¿Como puedo obtener un texto de un textbox y mostrarlo en un label de otra Ventada C# WPF?

Tengo la duda de como poner el texto que se introduzca en un textbox en otra ventana.
Explicando esto:
El usuario se logeara en una ventana, al momento de dar ingresar se abrirá un splash dando la bienvenida, lo que quiero hacer es que aparezca el nombre de usuario que introdujo en el splash dando la bienvenida.
Mi código es el siguiente:
Ventana de Login
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void BtnIngreso_Click(object sender, RoutedEventArgs e)
    {

        //Validacion de usuario y contraseña
            if (txtuser.Text == "User" && txtpass.Password == "1234")
            {
                //Si el usuario es correcto, llamar al splash
                SplashBienvenida splashBienvenida = new SplashBienvenida();
                splashBienvenida.LUser = txtuser;
                splashBienvenida.Activate();
                splashBienvenida.Show();
                this.Close();
            }
            else
            {
                //Mostrar el mensaje en caso erróneo
                MessageBox.Show("Usuario o contraseña no validos");
            }

    }

Ventana del Splash
public partial class SplashBienvenida : Window
{
    DispatcherTimer dT = new DispatcherTimer();

    public SplashBienvenida()
    {

        InitializeComponent();
        //Inicia el conteo que durara la ventana de Bienvenida
        dT.Tick += new EventHandler(dT_Tick);
        dT.Interval = new TimeSpan(0,0,10);
        dT.Start();

    }
    //Al momento que termine el conteo mandara llamar la ventana siguiente
    public void dT_Tick(object sender, EventArgs e)
    {

        Opciones opciones = new Opciones();
        opciones.Show();

        dT.Stop();
        this.Close();
    }

}

A:

Yo creo que el problema es que estás asignando la referencia de TextBox al Label, cuando en realidad deberías asignar el valor contenido en el control.
O sea, deberías cambiar esto:
splashBienvenida.LUser = txtuser;

Por esto:
splashBienvenida.LUser.Content = txtuser.Text;

¡Suerte!


Q:

How to convert a datetime into timestamp with timezone(Asia/Dubai) included?

I am able to convert to date from a timestamp, but the conversion from datetime to timestamp is giving wrong answer. here's my code
import datetime
from pytz import timezone

datetime.datetime.fromtimestamp(1426017600,timezone("Asia/Dubai")).strftime('%Y-%m-%d %H:%M:%S')
output:'2015-03-11 00:00:00'

How to include timezone when converting back to timestamp from datetime ?
>>datetime.datetime(2015,03,11).strftime('%s')
output:1426012200

A:

from datetime import datetime, time, date
from pytz import timezone, utc

tz = timezone("Asia/Dubai")
d = datetime.fromtimestamp(1426017600,tz)
print d
midnight = tz.localize(datetime.combine(date(d.year, d.month, d.day),time(0,0)), is_dst=None)
print int((midnight - datetime(1970, 1, 1, tzinfo=utc)).total_seconds())

Based on code from python - datetime with timezone to epoch


Q:

Any way to select without causing locking in MySQL?

Query:
SELECT COUNT(online.account_id) cnt from online;

But online table is also modified by an event, so frequently I can see lock by running show processlist.
Is there any grammar in MySQL that can make select statement not causing locks?
And I've forgotten to mention above that it's on a MySQL slave database.
After I added into my.cnf:transaction-isolation = READ-UNCOMMITTED
the slave will meet with error:

Error 'Binary logging not possible. Message: Transaction level 'READ-UNCOMMITTED' in InnoDB is not safe for binlog mode 'STATEMENT'' on query

So, is there a compatible way to do this?

A:

Found an article titled "MYSQL WITH NOLOCK"
https://web.archive.org/web/20100814144042/http://sqldba.org/articles/22-mysql-with-nolock.aspx
in MS SQL Server you would do the following:
SELECT * FROM TABLE_NAME WITH (nolock)

and the MYSQL equivalent is
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;

EDIT
Michael Mior suggested the following (from the comments)
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
COMMIT ;

A:

If the table is InnoDB, see http://dev.mysql.com/doc/refman/5.1/en/innodb-consistent-read.html -- it uses consistent-read (no-locking mode) for SELECTs "that do not specify FOR UPDATE or LOCK IN SHARE MODE if the innodb_locks_unsafe_for_binlog  option is set and the isolation level of the transaction is not set to SERIALIZABLE. Thus, no locks are set on rows read from the selected table".

A:

Use
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.
Version 5.0 Docs are here.
Version 5.1 Docs are here.


Q:

How to Send Form Data to an External Database and Process It?

In one site, www.example.com, I have a form. It is processed and stored in its database.
Is it possible to send this form data also to another site (www.client-site.com)? It is located on a different server. And this client-site should receive the data and store it on its own database.
I am not sure of the terminology and what should I've been looking for.
Tested different search queries here in SO and this is what most resembles it:
[php] [mysql] +form +"$_post" +external
I'd like to develop this with PHP and the databases run MySQL, and surely security is important in this data transaction.
And hoping this is not a SOAP matter... ;)
Justification:

www.example.com runs a mini site of one of my clients
www.client-site.com is the client main site
being a large company, they cannot provide me credentials to their main site database
I have to propose an alternate solution

A:

You will need to have something like a webservice (this is the word you are looking for) on site b which you can use from the code within your site a.
SOAP is one possibility to create a webservice, but there are many other possibilities. One is shown in this answer on stackoverflow.
NEVER EVER try to archiv this using forms and something like cURL!
Further you should look for proper authorization on your endpoint (site b) and ensure that ssl is used, as security is important to you.


Q:

th:field gives default value as 0 in input field

I have a problem as mentioned in the title.
The input field is of type number.
The th:field refers to an int attribute in the database.
I want my placeholder to be visible instead of the default 0 value.
<input id="courseCredits"  name="courseCredits" th:field="*{courseCredits}" class="form-control" placeholder="Course Credits" type="number" min="0" required autofocus/>

A:

If you don't want the default of 0 you can't use an int.  Instead use an Integer with null for empty.


Q:

MiniZinc Geocode not printing all solutions to CSP with "all" solutions enabled

The Issue
With solve minimize I only get one solution, even though there are multiple optimal solutions. I have enabled printout of multiple solutions in the solver configurations. The other optimal solutions are found with solve satisfy, along with non-optimal solutions.
Possible causes
Could it be that the cardinality function card() ranks by enum value where size of two sets are equal? In other words that card(A, B) > card(B, C)? If so, do I have to switch the representation of my vertices?
The Program
I am creating a MiniZinc program for finding the minimum vertex cover of a given graph. The graph in this example is this:

With Minimal Vertex Cover solutions being:
[{A, B, C, E}, {A, B, E, F}, {A, C, D, E}, {B, C, D, E}, {B, C, D, F}, {B, D, E, F}]. My code only outputs {A, B, C, E}.
Data file:
VERTEX = {A, B, C, D, E, F};

edges = [|1, 0, 1, 0, 0, 0, 0, 0, 0
         |1, 1, 0, 1, 1, 0, 0, 0, 0
         |0, 1, 0, 0, 0, 1, 1, 0, 0
         |0, 0, 1, 1, 0, 0, 0, 1, 0
         |0, 0, 0, 0, 1, 1, 0, 1, 1
         |0, 0, 0, 0, 0, 0, 1, 0, 1|];

Solver program:
% Vertices in graph
enum VERTEX;

% Edges between vertices
array[VERTEX, int] of int: edges;

int: num_edges = (length(edges) div card(VERTEX));

% Set of vertices to find
var set of VERTEX: span;

% Number of vertices connected to edge resulting from span
array[1..num_edges] of var 0..num_edges: conn;

% All edges must be connected with at least one vertex from span
constraint forall(i in 1..num_edges)
           (conn[i] >= 1);

% The number of connections to each edge is the number of vertices
% in span with a connection to that edge
constraint forall(i in 1..num_edges)
           (conn[i] = sum([edges[vert,i]| vert in span]));

% Minimize the number of vertices in span
solve minimize card(span);

A:

solve minimize only show one optimal solution (in some cases, intermediate values might also be shown).
If you want all optimal solutions you must use solve satisfy and add the constraint with the optimal value:
constraint card(span) = 4;

Then the model outputs all the 6 optimal solutions:
card(cpan): 4
span: {A, B, C, E}
conn: [2, 2, 1, 1, 2, 2, 1, 1, 1]
----------
card(cpan): 4
span: {B, C, D, F}
conn: [1, 2, 1, 2, 1, 1, 2, 1, 1]
----------
card(cpan): 4
span: {A, C, D, E}
conn: [1, 1, 2, 1, 1, 2, 1, 2, 1]
----------
card(cpan): 4
span: {B, C, D, E}
conn: [1, 2, 1, 2, 2, 2, 1, 2, 1]
----------
card(cpan): 4
span: {A, B, E, F}
conn: [2, 1, 1, 1, 2, 1, 1, 1, 2]
----------
card(cpan): 4
span: {B, D, E, F}
conn: [1, 1, 1, 2, 2, 1, 1, 2, 2]
----------
==========

Note: I added the output section to show all the values:
output [
   "card(cpan): \(card(span))\n",
   "span: \(span)\n",
   "conn: \(conn)"
];


Q:

Integer solutions of $p^2 + xp - 6y = \pm1$

Given a prime $p$, how can we find positive integer solutions $(x,y)$ of the equation:
$$p^2 + xp - 6y = \pm1$$

A:

Certainly if $p=2$ or $p=3$ you cannot find such $x$ and $y$. For the others, note that ny prime $\gt 3$ is of the form $6k\pm 1$.
Suppose that $p=6k+1$. Then $p^2=6l+1$ for some $l$.
To find $x$ and $y$ such that $p^2+xp=6y+1$ is now very easy: let $x$ be any positive multiple of $6$. Then $p^2+xp\equiv 1\pmod{6}$.
To find $x$ and $y$ such that $p^2+xp=6y-1$, let $x$ be any positive number congruent to $-2$ modulo $6$. Then $p^2+xp\equiv 1+(-2)(1)\equiv -1\pmod{6}$.
Exactly the same sort of idea works for primes $p$ of the form $6k-1$.


Q:

Is there a complete reference for HP's diagnostic port 84 and/or port 85 codes?

The HP ProLiant DL580 systems (G5 is the one I'm interested in at the moment) have a two-digit 7-segment display on the system board (visible only inside the chassis) which displays various diagnostic codes which they refer to as "port 84" or "port 85", switchable via a DIP switch.
The manuals mention this display but give only sketchy information about the actual codes displayed.  Is there anywhere I could find a more specific & complete reference of the display codes?  (I've done some web searches but have so far found only unrelated results.)

A:

You should not need to reference port codes unless you're really having an issue with the server getting through the POST process.
What behavior is the server exhibiting?
The ProLiant POST boot troubleshooting flowchart still indicates checking the codes as a necessary step. It's not valid on newer boxes, but the ProLiant DL580 G5 you're dealing with uses them.
The full reference of Port 85 codes appears on page 64 of the HP ProLiant DL580 Generation 5 Server Maintenance and Service Guide. In general, the action needed to remediate the issues is reseating of the proper components.


Q:

Django pre_save instance link not defined

I'm trying to create a simple pre_save function but I get an error kwargs['instance'].link is not defined etc:
why?
I have printed out kwargs['instance'] and I get this:
{'update_fields': None, 'raw': False, 'signal': <django.dispatch.dispatcher.Signal object at 0x10189f750>, 'using': 'default'}

now the strange bit I printed out instance and got the name field test title name
my model:
class Campaign(models.Model):
 name = models.CharField(max_length=60)
    status = models.CharField(max_length=16, choices=MESSAGE_STATUSES, default="Pending",)
    link = models.ForeignKey(Link,  related_name='campaign', null=True)

@receiver(pre_save, sender=Campaign)
    def my_callback(sender, instance, *args, **kwargs):

        print(kwargs)
        print(instance)

        if kwargs['instance'].link is None:
            link = Link()
            link.link = "test"
            link.save()

            kwargs['instance'].link = link
            # No need to save, as we're slipping the value in
            # before we hit the database.

A:

Just use instance.link. kwargs does not contain 'instance' because the function my_callback specify the instance as positional argument.
if instance.link is None:
    ....


Q:

Return single json object from json array that matches minimum value

I have an array like this
     var data = [
      { i: 0, j: 0, day: 5 },
      { i: 1, j: 0, day: 3 },
      { i: 1, j: 1, day: 5 },
      { i: 1, j: 2, day: 10 },
      { i: 2, j: 0, day: 5 },
      { i: 3, j: 0, day: 5 },
      { i: 4, j: 0, day: 6 },
      { i: 4, j: 1, day: 10 }
    ]

I want to return a single row from JSON with minimum day value
For eg in the above array minimum day is 3 and i want to get
{ i: 1, j: 0, day: 3 }

as output
I have tried this method
Math.min.apply(Math,data.map(function(item){return item.day})) but it returns only the minimum day
One solution i found is using indexOf method but i don't think its a good practice. Is there any shorthand method ??

A:

You could use Array#reduce and return the element with the smaller day property.
For empty arrays, you need a check in advance, because

Calling reduce on an empty array without an initial value is an error.

var data = [{ i: 0, j: 0, day: 5 }, { i: 1, j: 0, day: 3 }, { i: 1, j: 1, day: 5 }, { i: 1, j: 2, day: 10 }, { i: 2, j: 0, day: 5 }, { i: 3, j: 0, day: 5 }, { i: 4, j: 0, day: 6 }, { i: 4, j: 1, day: 10 }],
    result = data.reduce(function (a, b) {
        return a.day < b.day ? a : b;
    });

console.log(result);


Q:

Find an object in different arrays of object with mongoose

I have to know if an item is in the first or in the second arrays in this model.
Model:
_id: String,
array1: [{ id: Number, name: String, timestamp: String }],
array2: [{ id: Number, name: String, timestamp: String }],
array3: [{ id: Number, name: String, timestamp: String }],
array4: [{ id: Number, name: String, timestamp: String }]

});
I am using these queries but can anyone help me to improve it or maybe to do it in only one query?
Model.findOne({_id: userId , 'array1.id': item.id },function(error, res) {
    if(!res){
      Model.findOne({_id: userId , 'array2.id': item.id },function(error, res) {
        if(!res){
          //do what i need;
          }else{
            //error;
          }
        });
    }else{
      //error;
    }
  });

I have already used queries like :
Model.findOne({$and: [{_id: userId} ,{'array1.id': item.id }, {'array2.id': item.id} ]},function(error, res) {
    if(!res){

But it doesn't work.

A:

You can use the $or statement:
Model.findOne({$and: [{_id: userId} , { $or: [ {'array1.id': item.id }, {'array2.id': item.id} ] } ]},function(error, res) { if(!res){....


Q:

Screen Capture in Java not capturing whole screen

I have a small piece of code that I use to keep track of time - very simply it takes a picture of my desktop every four minutes so that later I can go back over what I've been up to during the day - It works great, except when I connect to an external monitor - this code only takes a screen shot of my laptop screen, not the larger external monitor I'm working from - any ideas how to change the code? I'm running OSX in case that's relevant...
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

class ScreenCapture {
    public static void main(String args[]) throws
        AWTException, IOException {
            // capture the whole screen
int i=1000;
            while(true){
i++;
                BufferedImage screencapture = new Robot().createScreenCapture(
                        new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );

                // Save as JPEG
                File file = new File("screencapture"+i+".jpg");
                ImageIO.write(screencapture, "jpg", file);
try{
Thread.sleep(60*4*1000);
}
catch(Exception e){
e.printStackTrace();
}

            }
        }
}

Following the solution given, I made some improvements and the code, for those interested, is under code review at https://codereview.stackexchange.com/questions/10783/java-screengrab

A:

There is a tutorial Java multi-monitor screenshots that shows how to do it.
Basically you have to iterate all screens:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();

for (GraphicsDevice screen : screens) {
 Robot robotForScreen = new Robot(screen);
 ...


Q:

ng pattern which allows alphanumeric but without spaces for input tag in angular js

am using the patterns like "/[a-zA-Z0-9][^\s]/" and "/\s/" but no one is working. can you give any solution for this "ng pattern for input tag and which allows oly alphanumeric but it does not allow spaces in the input field ".

A:

Try the following pattern: /^\s*\w*\s*$/
<script>
   angular.module('textInputExample', [])
     .controller('ExampleController', ['$scope', function($scope) {
       $scope.text = 'guest';
       $scope.word = /^\s*\w*\s*$/;
     }]);
 </script>
 <form name="myForm" ng-controller="ExampleController">
   Single word: <input type="text" name="input" ng-model="text" ng-maxlength="5"
                       ng-pattern="word" required ng-trim="">

Plunkr link