Q:

Failed to create the host-only adapter - windows 10, docker, virtualbox

I've recently run into this problem after having used docker toolbox without a problem for a while.
Started happening after windows update?
Windows 10 Home - 64
Uninstalled and reinstalled Docker toolbox
Uninstalled and reinstalled various versions of VirtualBox
Still get the same error
Running pre-create checks...
Creating machine...
(default) Copying C:\Users\me\.docker\machine\cache\boot2docker.iso to C:\Users\me\.docker\machine\machines\default\boot2docker.iso...
(default) Creating VirtualBox VM...
(default) Creating SSH key...
(default) Starting the VM...
(default) Check network to re-create if needed...
(default) Windows might ask for the permission to create a network adapter. Sometimes, such confirmation window is minimized in the taskbar.
(default) Creating a new host-only adapter produced an error: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe hostonlyif create failed:
(default) 0%...
(default) Progress state: E_FAIL
(default) VBoxManage.exe: error: Failed to create the host-only adapter
(default) VBoxManage.exe: error: Querying NetCfgInstanceId failed (0x00000002)
(default) VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component HostNetworkInterfaceWrap, interface IHostNetworkInterface
(default) VBoxManage.exe: error: Context: "enum RTEXITCODE __cdecl handleCreate(struct HandlerArg *)" at line 71 of file VBoxManageHostonly.cpp
(default)
(default) This is a known VirtualBox bug. Let's try to recover anyway...
Error creating machine: Error in driver during machine creation: Error setting up host only network on machine start: The host-only adapter we just created is not visible. This is a well known VirtualBox bug. You might want to uninstall it and reinstall at least version 5.0.12 that is is supposed to fix this issue
Looks like something went wrong in step ´Checking if machine default exists´... Press any key to continue...

A:

This answer is not specifically related to Docker, but seeing as this is one of the more recent top Stack Overflow search results (together with this question) on Google when searching for the "Failed to create the host-only adapter" error message from VirtualBox, I'm leaving this here in the hope that it will help someone else.
As a side note, if you can, I recommend you use Docker For Windows instead of Docker Toolbox to run Docker on Windows (requires Windows 10 Professional or Enterprise 64-bit).

My scenario:

Windows 10 Pro Version 1709
I use Hyper-V to run virtual machines whenever possible, but had a need to run an old VirtualBox VM with Windows XP as the guest OS
VirtualBox 5.2.4-119785 (Windows only supports a single hypervisor - I can recommend this approach if you need to switch between Hyper-V and VirtualBox)
VirtualBox did not (or failed to) create a host-only adapter on installation

When trying to create a host-only adapter using the Host Network Manager GUI, I got the dreaded "Failed to create the host-only adapter" error message, with a detail of: "Querying NetCfgInstanceId failed (0x00000002)".
Because I use Hyper-V, I had a number of Hyper-V Virtual Ethernet Adapters in addition to the actual physical adapter.

Looking at the properties of the physical adapter, it appears to be normal for Hyper-V to turn off all of the protocol drivers except for "Hyper-V Extensible Virtual Switch". Windows then gets its network connectivity through one of the virtual adapters, in my case it's called "External Virtual Switch", and the usual set of protocol drivers (TCP/IPv4 etc.) is enabled there.

I then noticed that VirtualBox appears to (want to) work in a similar fashion, because it had managed to install and enable a new protocol driver called "VirtualBox NDIS6 Bridged Networking Driver".

When I checked the properties of the other, virtual, adapters I noticed that the "VirtualBox NDIS6 Bridged Networking Driver" was enabled on all of them, but the "Hyper-V Extensible Virtual Switch" was not. It seemed odd that the VirtualBox driver was enabled on the Hyper-V virtual adapters, so I disabled it on all of them but left it enabled on the physical adapter.
I think at this stage I threw in a good old reboot for good luck, though I doubt whether that was actually necessary. When I subsequently tried to create the VirtualBox host-only adapter again, it worked! (I actually got an error message from VirtualBox, in a modal that I had to find on the taskbar, about the adapter name already being used. However a new "VirtualBox Host-Only Ethernet Adapter" showed up under the Windows Network Connections and when I closed and re-opened the VirtualBox Host Network Manager window, the adapter showed up there too.)
TL;DR;
My theory is that VirtualBox is for some reason unable to determine which adapter is the actual physical network adapter, and in a rather gung-ho manner goes ahead and enables its "VirtualBox NDIS6 Bridged Networking Driver" on every adapter that it finds.
Furthermore it then appears to be unable to determine which adapter it needs to create its virtual "wrapper adapter" for and fails.
Even if you don't use/have Hyper-V, you might have multiple adapters including virtual ones (lots of VPN software installs virtual adapters too, for example).
You can try disabling the "VirtualBox NDIS6 Bridged Networking Driver" on all but your actual physical network adapter(s) before attempting to create the VirtualBox host-only adapter again.

This is certainly not a new issue for VirtualBox judging by the large number of related tickets on their public bugtracker and in other places, some more than 2 years old. I have a feeling that for a lot of people the problem might be related to what I have described above, so hopefully this helps them.

Edit 01/15
Hmm, in retrospect I'm not sure how normal it is for Windows to use the Hyper-V "External Virtual Switch" for network connectivity. If I remember correctly the "Default" switch that Hyper-V creates and which provides connectivity to guests via NAT is a relatively new thing and before it was necessary to add and use the "External" switch... On my home PC, without an "External" switch, the normal (TCP/IPv4 etc.) protocol drivers stay enabled on the physical network adapter and the "Hyper-V Extensible Virtual Switch" is disabled both on the physical and on the virtual adapters. I haven't had a chance to test what happens if I add a new "External Virtual Switch" under those circumstances.

A:

tl;dr  If you are using Trend Micro or Symantec antivirus solutions, try uninstalling Virtualbox, then re-install it with the antivirus disabled.
It may work with others as well.
I am adding this answer for the record.
My coworkers and I started having a similar issue just after updating from Windows 10 Pro version 1703 to version 1709.
I tried rolling back to version 1703, and it worked, but of course this is not an acceptable solution.
For some reason, this had to do with the antivirus, which in our case is Trend Micro Office Scan. After doing a clean re-install with the antivirus disabled, the host-only adapter was available again.
The issue has been reported in the Virtualbox forum and issue tracker:
https://forums.virtualbox.org/viewtopic.php?f=6&t=86179#p413876
https://www.virtualbox.org/ticket/17354#comment:22
Unfortunately, this error is quite frequent, and it has been reported dozens of times with different causes.
In our case, the settings shown in bszom's answer were already correct.


Q:

Iterate and extract tables from web saving as excel file in Python

I want to iterate and extract table from the link here, then save as excel file.
How can I do that? Thank you.

My code so far:
import pandas as pd
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate

url = 'http://zjj.sz.gov.cn/ztfw/gcjs/xmxx/jgysba/'
res = requests.get(url)
soup = BeautifulSoup(res.content,'lxml')
print(soup)

New update:
from requests import post
import json
import pandas as pd
import numpy as np

headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36",
        "Referer": "http://zjj.sz.gov.cn/projreg/public/jgys/jgysList.jsp"}
dfs = []
#dfs = pd.DataFrame()

for page in range(0, 10):
    data = {"limit": 100, "offset": page * 100, "pageNumber": page + 1}
    json_arr = requests.post("http://zjj.sz.gov.cn/projreg/public/jgys/webService/getJgysLogList.json", headers = headers, data = data).text
    d = json.loads(json_arr)
    df = pd.read_json(json.dumps(d['rows']) , orient='list')
    dfs.append(df)
    print(dfs)

dfs = pd.concat(dfs)
#https://stackoverflow.com/questions/57842073/pandas-how-to-drop-rows-when-all-float-columns-are-nan
dfs = dfs.loc[:, ~dfs.replace(0, np.nan).isna().all()]
dfs.to_excel('test.xlsx', index = False)

It generates 10 pages and 1000 rows, but some columns values are misplaced, someone knows where did I do wrong? Thank you.

A:

So, using the JSON API from XHR you make a simple python post request via requests and you have your data.
In the params you have two of them which you can change to get different volumes of data, limit is the nos of objects you get in a request. pageNumber is the paginated page counter.
from requests import post
import json

url = 'http://zjj.sz.gov.cn/projreg/public/jgys/webService/getJgysLogList.json'
data = { 'limit' : '100', 'pageNumber' : '1'}
response = post(url, data=d)
response.text

Further you can use pandas to create a data frame or create a excel as you want.


Q:

Correct way of binding click event to list item in jquery

HTML CODE:

Name1

Name2

Name3

Name4

Name5

JQUERY CODE:
$(function() {
   $("#sortable1 li").each(function()
   {
        $(this).on("click",make($(this)));
   });

   function make($li)
   {
        alert("hello");
   }
});

fiddle :
http://jsfiddle.net/gztRq/433/
when i run the fiddle , it will automatically displays the alert for five list items.
actually i have binded click event for list item so whenever  the list is clicked it needs to call the function.
but why the above "make" function triggered five times before am clicking the list.  after clicking  the list item nothing happened. what is the problem ?
when i write the function code in-line everything works as expected.
Working code:
 $("#sortable1 li").each(function()
 {
    $(this).on("click",function()
    {
      alert("hello");
    });
 });

what is the correct behavior ?

A:

You call your function, don't add "(", ")". Just write name function (is reference). And this, is already define for the event function.
http://jsfiddle.net/gztRq/437/
$(function() {
   $("#sortable1 li").each(function() {
       $(this).click(make);
   });
   function make() {
        alert("hello "+$(this).text());
   }
});

A:

Remove the $.each() loop completely and just use:
$('#sortable1').on('click', 'li', function() {
    alert("Hello"); // Or make($(this)); if you still want that extra function
});

JSFiddle demo.


Q:

Windows 10 BackgroundMediaPlayer SystemTransportControls Pause Button Not Working

I have recently decided to add Background Audio playback support for podcasts in my app. I have got most of it to work but, the pause button in the SystemTransportControls of the BackgroundMediaPlayer doesn't seem to do anything.
Here is my background audio task class file:
public sealed class AudioPlayer : IBackgroundTask
{
    private BackgroundTaskDeferral _deferral;
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        _deferral = taskInstance.GetDeferral();

        var control = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
        control.IsEnabled = true;
        control.IsPauseEnabled = true;
        control.IsPlayEnabled = true;
        control.IsNextEnabled = false;
        control.IsPreviousEnabled = false;

        taskInstance.Canceled += TaskInstance_Canceled;

        BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
    }

    private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        BackgroundMediaPlayer.Shutdown();
        _deferral.Complete();
    }

    void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
    {
        object obj;
        e.Data.TryGetValue("MessageBody", out obj);

        string url = (string)obj;
        url = url.Replace("\"", "");
        var source = MediaSource.CreateFromUri(new Uri(url, UriKind.Absolute));

        var list = new MediaPlaybackList();
        list.Items.Add(new MediaPlaybackItem(source));

        BackgroundMediaPlayer.Current.Source = list;
        BackgroundMediaPlayer.Current.Play();
    }
}

It is important to note that the audio does start playing in the background but I don't have the ability to pause the audio.
Thanks,
P.

A:

To react to SystemMediaTransportControls (SMTC) and handle each Universal Volume Control (UVC) button: play, pause, next, and previous, we need handle the  SystemMediaTransportControls.ButtonPressed event in Run method like following:
public void Run(IBackgroundTaskInstance taskInstance)
{
    var control = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
    control.ButtonPressed += control_ButtonPressed;
    ...
}

And in control_ButtonPressed method, deal with different buttons like:
private void control_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
    switch (args.Button)
    {
        case SystemMediaTransportControlsButton.Play:
            //Todo with play
            break;
        case SystemMediaTransportControlsButton.Pause:
            //Todo with pause
            break;
        case SystemMediaTransportControlsButton.Next:
            //Todo with skip to next;
            break;
        case SystemMediaTransportControlsButton.Previous:
            //Todo with skip to previous;
            break;
    }
}

For a complete sample, please refer to the official Background audio sample on GitHub, especially the MyBackgroundAudioTask class. And there is also a very nice post that will walk you through setting up background audio, reacting to device media controls, communicating with the background media player, and managing playlists. Read more at The Basics of Background Audio.


Q:

How to split up integers using printf in Java

Hello everyone I was having some issue splitting up a user input number using printf (I do have to use printf). My problem is that when I put in say the number 12345 it will print the integers on five separate lines, and also has them in the reverse order. So it would look something like this when I put in the integer 12345:
5
4
3
2
1
But without the spaces (I need those as well). I want it to print like this: 1 2 3 4 5.
Here is the code I have so far:
public static void main(String[]args){
    Scanner input = new Scanner(System.in);

    int one;

    System.out.print("Enter the five digit integer you would like to be split up:");
    one = input.nextInt();

    while (one > 0){
        System.out.printf("%d%n", one % 10);
        one = one /10;
}
}

A:

First, in order to avoid printing on separate lines, you should avoid using the %n formatting character in your printf().
Now, how do you print the digits in the correct order? Well, since you are limited to five-digit numbers, you can do something like this:
    for ( int divisor = 10000; divisor >= 1; divisor /= 10 ) {
        System.out.printf( "%d ", n / divisor);
        n %= divisor;
    }
    System.out.printf( "%n" ); // Just to complete the line

(divisor /= 10 is shortcut for divisor = divisor / 10, and n %= divisor is shortcut for n = n % divisor).
So you start by dividing the number by 10000. This will give you the fifth digit from the right. Then you take the remainder and put it in n. This gives you just the remaining four digits. Then the loop will reduce your divisor to 1000, which will take the fourth digit from the right, and you keep doing that until you reach a divisor of 1.
Another approach that does not require knowing that the number is 5 digits long, but requires recursion is to write a method like so:
public static void printSplitNumber( int n ) {

    if ( n == 0 ) {
        return;
    }
    printSplitNumber( n / 10 );
    System.out.printf( "%d ", n % 10);
}

And from your main, call:
    printSplitNumber(n);
    System.out.printf("%n"); // Again, just completing the line.

This recursive method relies on the fact that you print the current digit only after all the rest of the number has been printed. So this causes it to print it to the right of the rest of the digits, giving you the effect you need.


Q:

How to deal with being away from moderating for extended periods of time?

I have a sub in which the other mods are not entirely reliable. There is a spam filter and the sub runs smoothly for the most part without moderation, but is/are there better ways than to just hope for the best?

A:

in which the other mods are not entirely reliable

First of all, is there anything you can do about this? You have bigger problems than taking a vacation if this is true. If you have several examples of them acting up, you can tell a higher-up person. If you don't feel like you can trust the other moderators, then it might be best to just leave.
Other than that:

See if you can check in every day or two sometime (maybe at night). I don't know where you're going, so this might not always be an option.
If there's a mod on an unrelated part of the site that you trust, you might ask them to help. You could phrase it to be a temporary substitute so you don't "stress the other moderators." :)

You need to either fix this situation or get out of it as soon as you can. Not trusting the other mods is a bad thing and can hurt your reputation and your site that you moderate.

A:

There are at least two styles of moderation that I can think of right now, so I'll try to address them both.
Time-based moderation
My go-to would be to find some sort of protégé in the mod community and actually and publicly charge him/her with your moderation duties for the term.  This way, people know who to come to and there is an explicit sense of responsibility on the person you charge.
Big Ball of Modly-Wobbly Stuff
This one is trickier.  There's no real single source of responsibility here.  In this case though, I think the mod community will be able to handle one person leaving (depending on how large it is).  If it is very small, the time-based suggestion should work, too.


Q:

Transforming a checkboxGroupInput object into a vector

After a long time searching for a possible answer I am still unable to create a character vector out of a user input (specifically checkboxGroupInput).
My ultimate purpose is to pass the user selected entries from checkboxGroupInput into a python list (using RPython) for further process. However, I only manage to do that "character by character" instead of the whole word even when using toString. I have read the post Getting multiple checkbox values in Shiny suggesting the double brackets indexing. Actually I did not see any difference in the result when using single brackets and/or toString (see commented out command in server.r). In both ways I end up having variables in python like "L", "o", "n", "d", "o", "n" instead of just "London".
# server.R
library(shiny)
library(rPython)
copy2  <- function(test) {
    python.exec("locations = []")
    for (i in 1:length(test)) {
        python.assign("temp",toString(test[[i]]))
#       python.assign("temp",test[i])
        python.exec("locations.extend(temp)")
    }
    python.exec("print locations")
}

shinyServer(function(input, output) {
    output$chosen <- renderPrint({
        string <- copy2(input$checkGroup)
    })
  }
)

# ui.r
library(shiny)
library(rPython)

locations <- c("London", "Paris", "Munich")

shinyUI(pageWithSidebar(
    headerPanel(
      "Map",
  ),
    sidebarPanel(
        checkboxGroupInput("checkGroup",
            label = h3("Select Locations:"),
            locations,)
    ),
    mainPanel(
    h3('Main Panel text'),
    p('Selected Locations:'),
    verbatimTextOutput("chosen")
    )
))

What would be the best way to simply transfer the contents of the R Shiny object (the selected values from the checkboxGroupInput) into an R vector or Python list ?
Thank you for the advice.

A:

Well, the problem is in your Python code.
You have to understand the difference between list.append() and list.extend().
>>> locations = []
>>> locations.extend("London")
>>> locations
['L', 'o', 'n', 'd', 'o', 'n']

versus
>>> locations = []
>>> locations.append("London")
>>> locations
['London']


Q:

Entities and Value Objects in Web Applications

We have a simple domain model: Contact, TelephoneNumber and ContactRepository. Contact is entity, it has an identity field. TelephoneNumber is typical value object: hasn't any identity and couldn't be loaded separately from the Contact instance.
From other side we have web application for manipulating the contacts. 1st page is "ContactList", next page is "Contact/C0001" which shows the contact details and the list of telephone numbers.
We have to implement telepone numbers edit form. The first approximation thought is to add some page which will be navigable like 'ThelephoneNumber/T0001'.
But ThelephoneNumber is is Value Object class and its instance couldn't be identified this way.
What is the best practice for resolving this issue? How can we identify non-identifieble objects in the stateless applications?

A:

Does the value objects state identify that particular instance?  If not you could just pass back the old value and the new value when the edit form is submitted, then update any objects with the old state to the new state.
I would rather have a page like Contact/C0001/ThelephoneNumber, and use both the contact id and the value objects class to identify the instance you want to change.
Unless I've completely misunderstood what you're asking.


Q:

Android - 文字入力の確定検知について

こんばんは。
EditTextの入力終了検知を確定を検出することで行おうと考えています。検索で次のようなコードを見つけました。
edit1.addTextChangedListener(new TextWatcher()
{
        int currentLength = 0;

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        currentLength = s.toString().length();
    }

    @Override
    public void afterTextChanged(Editable s) {
        Log.v("", "after:" + s.toString());
        if (s.toString().length() < currentLength) {
            return;
        }
        boolean unfixed = false;
        Object[] spanned = s.getSpans(0, s.length(), Object.class);
        if (spanned != null) {
            for (Object obj : spanned) {
                if (obj instanceof android.text.style.UnderlineSpan) {
                    unfixed = true;
                }
            }
        }
        if (!unfixed) {
            Toast toast = Toast.makeText(getApplicationContext(), "確定", Toast.LENGTH_SHORT);
            toast.show();
        }
    }
});

うまく動作するのですが、確定後にソフトキーボードのDeleteキーを押したときにも、確定が発生します。
これを防ぐ方法はありますでしょうか？
よろしくお願いいたします。

A:

調べた結果、ソフトキーボードのDeleteキーが入力されると、onTextChanged(CharSequence s, int start, int before, int count)のcountが0になるそうです。
そこで、次のようにしました。
edit1.addTextChangedListener(new TextWatcher() {

    boolean keycodeFlag = false; // 上記コードに追加

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        // このブロック追加
        if (count == 0) {
            keycodeFlag = true;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

        if (s.toString().length() < currentLength || keycodeFlag) {   // 変更
            keycodeFlag = false;  // 追加
            return;
        }
    }
}

これで、質問内容のDeleteキーが確定として検知されるのを防ぐことができるようになりました。
（Genymotionエミュレータ上Android 4.2.2, 4.4.4, 5.0で確認）


Q:

An olympiad question

I came across a question ( mentioned below ) which is from a Mathematical Olympiad.
It says,
If $m $ and $n $ are positive integers such that

$n + (n + 1) + (n + 2) +...+ (n + m) = 1000 $

then how many $(m, n)$ pairs exists ?

A:

$n(m+1)+(1+2+\cdots+m)=1000$
$n(m+1)+\dfrac 12m(m+1)=1000$
$(m+1)(2n+m)=2000$
Note that $m+1$ and $m+2n$ are of opposite parities. We have to factorize $2000$ into the product of an odd and an even number.
Note that both factors should be greater than $1$ as $m$ is positive.
$2000=5\times400=25\times80=125\times16$
Note also that $m+1<2n+m$.
So, $(m+1,2n+m)=(5,400)$ or $(25,80)$ or $(16,125)$
$(m,n)=(4,198)$ or $(24, 28)$ or $(15,55)$.


Q:

Speeding up a for loop containing a sum in R

I'm wondering if it's possible to modify this loop to run faster.  When I run it with n=2000000 it takes about 25 seconds. Any tricks available?
for(i in 1:n)
{
    x[i] <- sum(runif(20))
}

A:

system.time(x <- rowSums(matrix(runif(2e6),ncol=20)))
#   user  system elapsed
#  0.108   0.620   0.748


Q:

Using load in R markdown

I am using Rmarkdown and knitr in RStudio. I used this code in Rmarkdown and I knit it by knitr but I cannot see the dataset in my console environment.
load(url("http://bit.ly/dasi_gss_data"))

What should I do?

A:

I did this
```{r}
load(url("http://bit.ly/dasi_gss_data"))
table(gss$year)
```

and it worked just fine.
Are you expecting to see gss in your console environment? It won't show there.


Q:

Deleting sub-list that contains duplicates

I have a large list of uniform-length lists. What is an efficient way to delete component lists that contain duplicates? For three-item sub-lists, I have used the following code:
allUnique = DeleteCases[DeleteCases[DeleteCases[listOfThreeItemLists,
  {y_,x_,x_}],{x_,y_,x_}],{x_,x_,y_}];

But enumerating all possible pairs for sub-lists of, say, seven items, seems unwieldy. Thoughts?

A:

SeedRandom[1]
listOfThreeItemLists = RandomInteger[5, {10, 3}]

{{4, 2, 4}, {0, 1, 0}, {0, 2, 0}, {0, 3, 5}, {2, 0, 3}, {4, 4, 1}, {3,
         3, 4}, {1, 4, 2}, {1, 1, 4}, {5, 4, 5}}

In addition to Select suggested in comments, you can also use:
DeleteCases[listOfThreeItemLists, {___, x_, ___, x_, ___}]
DeleteCases[listOfThreeItemLists, Except[_?DuplicateFreeQ]]
DeleteCases[listOfThreeItemLists, _?(Not[DuplicateFreeQ @ #] &)]
Cases[listOfThreeItemLists, _?DuplicateFreeQ]
Pick[#, DuplicateFreeQ /@ #] & @ listOfThreeItemLists

all give

{{0, 3, 5}, {2, 0, 3}, {1, 4, 2}}

A:

You can also use a bit of linear algebra to make this really fast.
Let's start with an input data set
SeedRandom[1]
n = 1000000;
m = 3;
data = RandomInteger[10, {n, m}];

Here the timing of a Select-based approach:
a = Select[data, DuplicateFreeQ]; // RepeatedTiming // First

0.68

And here a variant based on linear algebra
b = With[{
      A =  Normal[IncidenceMatrix[DirectedEdge @@@ Subsets[Range[m], {2}]]],
      u = ConstantArray[1, Binomial[m, 2]]
      },
     Pick[
      data,
      Unitize[data.A].u,
      Binomial[m, 2]
      ]
     ]; // RepeatedTiming // First

a == b

0.050
True

How does this work? Well, for a vector v of length m, the vector v.A contains all differences of elements in v. Unitize[v.A] will replace all nonzero entries with 1. Since u is a vector of ones,  Unitize[v.A].u counts the number of pairs of elements in v that are duplicate-free. We can do that for all vectors in the list data at once with Unitize[data.A].u. This way we utilize than matrix-matrix and matrix-vector multiplications are highly optimized on the machine level and that Unitize is also a vectorized (thus highly efficient) function on packed arrays. In the end, we use Pick to pick only those vectors from data that contain a maximal number of duplicate-free pairs (the maximal number is Binomial[m, 2]).
This works also for larger m but the performance boost in comparison to Select+DuplicateFreeQ will decay quite qickly; starting with m = 10, Select+DuplicateFreeQ is faster on my machine. Some reasons for this are that the size of the matrix A grows quadratically in m and that DuplicateFreeQ can short-circuit when it finds the fist duplicate in a vector. Morever, there is potential to use a binary search tree for the implementation of DuplicateFreeQ so that DuplicateFreeQ might have runtime $O(m \log(m))$ instead of $m^2$...


Q:

Как в PHP создавать динамически страницы типа site.com/page и так далее? Чтобы не выводило ошибку Страница не найдена?

Как в PHP создавать динамически страницы типа test.ru/page и так далее? Чтобы не выводило ошибку Страница не найдена?

A:

Здесь как таковой PHP ни при чём.
В .htacces отправляете запрос в index.php, а вот там уже строите логику обработки параметров
Как пример
RewriteEngine On

Options -Indexes
IndexIgnore */*
DirectoryIndex index.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]


Q:

Using ResultSet multiple times not working as expected

Why I can't while for two time.the second time I will get blank.
String sql = "select * from t_user";
Connection con = dbUtil.getCon();
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
    System.out.println("phoneFirst" + rs.getString("phone"));
}

while (rs.next()) {
    System.out.println("phoneSecond" + rs.getString("phone"));
}

A:

It's because, ResultSet won't work that way. It is forward only. Once it reach the end, it won't come back to first. You might want to use the Scrollable Result.
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY);

And once you done with a While loop, reset to first using the line rs.beforeFirst();
while (rs.next()) {
    System.out.println("phoneFirst" + rs.getString("phone"));
}

 rs.beforeFirst();

while (rs.next()) {
    System.out.println("phoneSecond" + rs.getString("phone"));
}


Q:

How to create a view from table row values

I have a table like this:
ID  |  staff_id  |  Meta_key  | Meta_Value  | Meta_Group
1          1         landline      456          contact
2          1          mobile       777          contact
3          1          email      i@i.i          contact
4          2         landline      453          contact
5          2          mobile       888          contact
6          2          email      d@i.i          contact

I want to create a view called view_contact_details that looks like this:
 staff_id  |  landline  |  mobile  | email
    1          456          777      i@i.i
    2          453          888      d@i.i

Is this possible to do? I appreciate any help and thank you in advance.

A:

You can do this with a CASE wrapped in a MAX
Sample Data
CREATE TABLE #TestData (ID int, staff_id int, meta_key varchar(10), meta_value varchar(10), meta_group varchar(10))
INSERT INTO #TestData (ID, staff_id, meta_key, meta_value, meta_group)
VALUES
(1,1,'landline','456','contact')
,(2,1,'mobile','777','contact')
,(3,1,'email','i@i.i','contact')
,(4,2,'landline','453','contact')
,(5,2,'mobile','888','contact')
,(6,2,'email','d@i.i','contact')

Query;
CREATE VIEW view_contact_details
AS
SELECT
Staff_ID
,MAX(CASE WHEN Meta_Key = 'landline' THEN Meta_Value END) Landline
,MAX(CASE WHEN Meta_Key = 'mobile' THEN Meta_Value END) Mobile
,MAX(CASE WHEN Meta_Key = 'email' THEN Meta_Value END) Email
FROM #TestData
GROUP BY staff_id

Results;
Staff_ID    Landline    Mobile  Email
1           456         777     i@i.i
2           453         888     d@i.i


Q:

What would be the electric field lines for parallel plates with different charge density?

How would electric field lines look like if charge densities on parallel plates (like the ones used in parallel plate capacitors) are different (still opposite though so electric fields can form)?

A:

Electric field lines are a pictorial tool to provide general qualitative information on the nature of the field, specifically the direction and relative strength of the field. The direction is indicated by arrows on the lines. The relative strength in a particular area is indicated by comparing the density of the lines in that area to other areas on the same diagram. The density of the lines provides no quantitative information on the field strength.
Since the strength of the field between the plates of the capacitor is proportional to the charge density, increasing or decreasing the charge density, all other things being equal, would increase or decrease the density of the lines, respectively. However, the density of the lines of a diagram of a single capacitor will tell you nothing because there is nothing to compare it with, such as another capacitor on the same diagram which is identical except for the charge density.
Hope this helps.


Q:

Oracle: What does 'execute immediate' mean?

What is the significance of execute immediate in PL/SQL when used with DML and DDL statements? Does execute immediate implicitly commit to a database like DDL statements do ?
The following is an example I have encountered:
SELECT 'TRUNCATE TABLE BD_BIDS_APPR_DET' INTO V_SQL1 FROM DUAL;
EXECUTE IMMEDIATE V_SQL1;

SELECT 'TRUNCATE TABLE BD_BIDS_SYS_DET' INTO V_SQL1 FROM DUAL;
EXECUTE IMMEDIATE V_SQL1;

SELECT 'TRUNCATE TABLE BD_BIDS_EXT_DET' INTO V_SQL1 FROM DUAL;
EXECUTE IMMEDIATE V_SQL1;

A:

It is for running native dynamic SQL.
For DML you'd use it when running statements that you don't have available at compile time, e.g. if the column list is based on a selection from the user.
In your case it's being used because DDL cannot be run as static SQL from within PL/SQL. Only certain query, DML and TCL commands are valid. Anything else has to be treated as dynamic.
I'd say it's rare to need to use DDL from a PL/SQL block. TRUNCATE might be reasonable; if you find anything creating or dropping objects on the fly then that might be more of a concern as it can suggest a suboptimal data model.
EXECUTE IMMEDIATE itself does not automatically commit; but if you execute DDL then that will behave the same as if you ran it outside PL/SQL, so it will commit in your case, yes.
Incidentally, I'm not sure why your code is using an intermediate variable to hold the statement; that's useful if you want to display what it's going to run maybe, but you don't seem to be doing that. What you have could be done as:
EXECUTE IMMEDIATE 'TRUNCATE TABLE BD_BIDS_EXT_DET';

i.e. without using V_SQL_1 at all.


Q:

jQuery Selector for server side control

What is the difference between $('#<%=lblName.ClientID%>') and $("[id$=lblName]")?

A:

$('#<%=lblName.ClientID%>') will find an element with the id attribute as supplied by the ClientID property in ASP.Net.
$("[id$=lblName]") will find an element with an id attribute that ends with lblName, for example foo-lblName.


Q:

Good way to scramble html?

I am embedding my livestream channel on my page so people can see it only there. However, if you look at the source code, you will be able to see the URL of my channel on livestream and see it there which i dont want. I wonder if there is a way to make it human unreadable. I have tried many html scramble pages but they all fail in scrambling the URL.
My embed code is something like this:

with the scramblers i have tried so far i get this:

Notice how the URL part is still human readable. Not very useful, right? I know that this trick would be useless with computer wizards and savvy users but it will be enough for the average user so im fine with that. No matter whether its a page or a php function i am willing to try.
Thank you.

A:

You can't make your URL unreadable because the url will be unusable in SRC attribute. Do you have any programming language installed on your server? Example with PHP:
embedder.php (can be html)

iframe.php
<?php
if (!isset($_SERVER["HTTP_REFERER"])
    || $_SERVER["HTTP_REFERER"] !== "http://localhost/embedder.php") exit;
header("Location: http://www.livestream.tv/embed/56576778");
?>

When you try to direct access the 'iframe.php' then the redirect doesn't happen.


Q:

C - Matrix input function gets runtime error if matrix is bigger than 5x5, but there is no size defined at the code

I'm using this function to read the input matrix:
void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}

And I'm creating the matrix like this:
scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

A:

matriz1 is a double pointer so while allocating memory you should write sizeof(int*). because ** pointer will holds/contains * single pointers.
int **matriz1 = malloc(v1 * sizeof(int*));
for(i = 0;i < v1; i++){
    matriz1[i] = malloc(v1 * sizeof(int));
}

typecasting malloc() is discouraged.


Q:

Trying to install apps directly to SDK with ADB. However, it doesn't detect my galaxy ace. Any advice?

I already restarted server in the console, and I installed all SDK tools packages.
It just doesn't detect the phone.
It says:
C:\Program Files <x86>\Android\plataform tools>adb devices
List of devices attached.    (there's nothing here)

Oh, BTW, I'm using Windows 7 64 bit Premiun
UPDATE 1: Installing kies and the usb drivers from samsung. Thanks for the reccommendation
 SuNnY_sYeD
UDATE 2: Finished installing and started running adb console and detected the device. Apparently, it detected SOMETHING at least, because now it says :

0123456789ABCDEF device.

A:

Well step one is downloading the driver for your device which can be found here samsung.com/sg/support/model/… then see if adb is picking up your device


Q:

Calculator and Formatter classes

Calculator class:
class Calculator
{
    /**
     * @return array
     */
    function doPowTable ($n)
    {
        $table = array();
        for ($i = 1; $i <= $n; $i++)
        {
            $table[] = array(
                'i' => $i,
                'factor' => pow($i, 2)
            );
        }
        return $table;
    }
}

Formatter class:
class Formatter
{
    /**
     * @return array
     */
    function getAndFormat ($n)
    {
        $table = (new Calculator()).doPowTable ($n);
        return array_map (function($item) {
            $item['i_factor'] = $item['i'].'_'.$item['factor'];
            return $item;
        }, $table);
    }
}

They say it's bad because the helper hard-codes the Calculator. But I think it's how it is supposed to be. It would have been better if I didn't give the $n to it but an array created by the doPowTable() method. Why?

A:

What if I want to put the Formatter class under test? How can I mock the Calculator dependency if it is hard-coded?
I suggest you put that into a separate public method so that it would be possible for other developers to create a partial mock and test it. It will also be clearer since you start reading the class what its dependencies are.
class Formatter
{
    /**
     * @var Calculator
     */
    private $calculator;

    /**
     * @param Calculator $calculator
     * @return $this
     */
    public function setCalculator(Calculator $calculator)
    {
        $this->calculator = $calculator;

        return $this;
    }

    /**
     * @return Calculator
     */
    public function getCalculator()
    {
        return $this->calculator;
    }

    /**
     * @return array
     */
    function getAndFormat ($n)
    {
        $table = $this->getCalculator()->doPowTable($n);

        return array_map (function($item) {
            $item['i_factor'] = $item['i'].'_'.$item['factor'];
            return $item;
        }, $table);
    }
}

This way you can either provide a different calculator or a mocked one for testing purposes.
Please consider the example below. It shows how to create a partial mock of the Formatter class to override the Calculator dependency.
$mockedCalculator = $this->getMock(Calculator::class);

// set your mocked calculator behaviour here

$formatter = $this->getMockBuilder(Formatter::class)
    ->disableOriginalConstructor()
    ->setMethods(['getCalculator'])
    ->getMock();

$formatter
    ->expects($this->once())
    ->method('getCalculator')
    ->willReturn($mockedCalculator);

$n = 123; // it's just an example
$this->assertEquals($expectedValue, $formatter->getAndFormat($n));


Q:

Why won't abs() in java work?

I have always had a question about java.lang.Math: (It might by very basic)
Why do I have to Math.abs(-100) and can't to abs(-100)?
I figure that Math is a class. And abs is a static method. But why can I not simply import java.lang.Math and use abs(-100)?

A:

You can import all the methods in Math:
import static java.lang.Math.*;

or just the one method you want:
import static java.lang.Math.abs;

Normal imports just import classes, making that class available via its short name.

A:

abs is a static method and in order the compiler knows where it's defined, you have to specify the class (in your case - Math).
Note that you could do a static import on Math.abs and then you'd be able to just do abs(-100) instead of Math.abs(-100). In this case you'll have to add an import statement like this one:
import static java.lang.Math.abs;

Note also that in Java, unlike JavaScript and PHP, there aren't any public functions, which is why import statements are important.


Q:

Processing error: Cannot invoke blurImage(int, int, int) on the primitive type int

I recently made a program in processing Java to load an image and blur it but am now putting this function into a class as a method and got this error:

Cannot invoke blurImage(int, int, int) on thee primitive type int

my class:
//create class called ImageProcessing where all image editing methonds will be
class ImageProcessing {
  //create function "blurImage" which takes in an xOffset, a yOffset, and a blur amount
  //xOffset and yOffset is changing where the grid starts so the make the blurring algorithm less pixelated using other methods when calling this function
  //the blur amount is how big each box in the grid is
  void blurImage(int xOffset, int yOffset, int blurAmount) {
    //loop through x in the image starting at the negative xOffset and incrementing by the blurAmouint / 2
    //the negative xOffset's purpose is to start the offset off the grid so as to blur the whole image no matter the offset
    //incrementing by the blurAmount / 2 is done because it needs to go in both directions
    for (int x = -xOffset; x < pic.width; x += blurAmount / 2) {
      //loop through the same way for the y so that we can got though in 2 dimentions instead of just 1
      for (int y = -yOffset; y < pic.height; y += blurAmount / 2) {
        //create a 2D array called p that is the size of the blur amount, the size of the box; this is the box
        color[][] p = new color[blurAmount][blurAmount];
        //initialize variables that are the averages of each color channel
        int redAverage = 0;
        int greenAverage = 0;
        int blueAverage = 0;

        //loop through the blurAmount in both dimentions to refrence all the pixels in the p array
        for (int a = 0; a < blurAmount; a++) {
          for (int b = 0; b < blurAmount; b++) {
            //fill the array with the colors of the current box on the grid so i can refrence them easily
            p[a][b] = pic.get(x + a, y + b);
            //these lines add up the Red Green and Blue channels into their individual variables
            //the "(p[a][b] >> 16) & 0xFF" is first shifting the hexidecimal number over into the correct position and then chopping off the extra bits to the right
            redAverage += (p[a][b] >> 16) & 0xFF;
            greenAverage += (p[a][b] >> 8) & 0xFF;
            blueAverage += p[a][b] & 0xFF;
          }
        }

        //dividing the red averages by the square of the blurAmount
        //the squaring is needed to find the area in pixels, this makes the average
        redAverage /= (int)(blurAmount * blurAmount);
        greenAverage /= (int)(blurAmount * blurAmount);
        blueAverage /= (int)(blurAmount * blurAmount);

        //create color from the average values
        color blur = color(redAverage, greenAverage, blueAverage);

        //loop through the current box on the grid the same way as before
        for (int a = 0; a < blurAmount; a++) {
          for (int b = 0; b < blurAmount; b++) {
            //setting all the pixels in the box to the color of the averages
            //the reason for the "x + a" and the "y + b":
            //find the location of the pixels in the box relative to the top left corner of it
            pic.set(x + a, y + b, blur);
          }
        }
      }
    }
  }
}

my code to call it:
/*
//The purpose of this program is to create a blurring algorithm that can
//adjust to pixelate or blur the image at different levels.
//
//We first need to split th image into a grid and work with each box on the grid individually.
//After this we get all the color values from each pixel in the box and store it in our code.
//We can then add all the reds together, the greens together, and the blues together and divide each by the number of pixels.
//Next, we turn all the three average into a color variable and set all the pixels in the current box the that color
//
//If we run this multiple times, we can change the blur amount each time and offset the grid to get less pixelated results, we can get a smoother image.
//
//Kwown Issues:
//none so far
//
//Created by Matthew Teta
*/

//create instance of my ImageProcessing claa
ImageProcessing i = new ImageProcessing();

//Make sketch full screen
boolean sketchFullScreen() {
  return true;
}

//initialize image
PImage pic;

void setup() {
  //load image from file and save it into pic PImage
  pic = loadImage("image.jpg");
  //create window at size of picture
  size(pic.width, pic.height);
  background(255);
  frameRate(1);
}
//maxBlur is the starting variable for the blur; TL;DR sets the first size of the grid boxes; also used for the temperary blur value running later in my code
float maxBlur = 16;
//initialize the blurDecrement
int blurDecrement = 0;
//create variable that is the amount of times the blurring algorithm is run
//RECOMENDATION: make the blur half of the maxBlur
//the lower the value the more pixelated
int blur = 1;
//simple boolean so that my code for running the blur is only run once at the beginning
boolean first = true;

void draw() {
  //calling "first()" if this is the first iteration
  if (first) {
    first();
  }

  //save image in file called "blurred-img" as a jpg
  pic.save("blurred-img.jpg");

  //setting the variable for runniong the code once to false so that is won't be run again
  first = false;
}

//create function first that is only run one time when the program is run
void first() {
  //first find the blurDecrement so that we will get a smooth transition for the number of iterations of the blur algorithm we have
  blurDecrement = (int)(maxBlur / blur);

  //iterate through blur, the number of times to blur
  for (int i = 0; i < blur; i++) {
    //run blur algorithm at the blurDecrement for the x and y offsets using the maxBlur
    //remember: the maxBlur is also used to store the value after being decremented in the loop
    i.blurImage(blurDecrement, blurDecrement, round(maxBlur));
    //draw the image on the canvas at the top left point, (0, 0)
    image(pic, 0, 0);

    //decrement maxBlur by the blurDecrement value
    maxBlur -= blurDecrement;
  }
}

The error is on the line

i.blurImage(blurDecrement, blurDecrement, round(maxBlur));

I have searched the internet for the problem but have not gotten what I wanted. Thanks in advance for a response!

A:

HINT in the below loop, you declare i as an int in: int i = 0. Remember, local variables take precedence over global variables. Try renaming your object i to something like object_i. i.e. ImageProcessing object_i = new ImageProcessing();
for (int i = 0; i < blur; i++) {

    i.Func(foo);// the problem = object name is same as int variable name.

//stuff
}


Q:

VBA Worksheet_change when a new row has been added, insert today's date

i tried to use the formula =Today() on the table of my database and when i try to insert a new row the next day, the whole data even the previous dates had been replace with the current day's date. Is there anyway to prevent it ? Or is it possible to use worksheet_change to update the date's column when new row had been inserted and the new role's date column will have the current day date and the following day when i update again it wont be replaced? Please advise thanks

A:

ZQ7, this answer is as I mentioned in the comments, finds the =TODAY() formula cell and paste it's values to it's current cell. Then you can add your new row and run the rest of your code..
Option Explicit

Sub prevenddate()
Dim mert As Range
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
    Cells.Find(What:="=TODAY()", After:= _
        ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Copy
ActiveCell.PasteSpecial xlPasteValues

End Sub

And here is the desired answer!
This below code, firstly looks for any =TODAY() formula in worksheet, and if the result is today's date it doesn't do anything. But if it's different then today's date then it simply does Paste Values
Private Sub Worksheet_Change(ByVal Target As Range)

Dim wb As Workbook
Dim ws As Worksheet
Dim myRw As Long, myCl As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
On Error GoTo 10

myRw = ActiveCell.Row
myCl = ActiveCell.Column

        ws.Cells.Find(What:="=TODAY()", After:= _
        ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, MatchCase:=False, SearchFormat:=False).Activate
  If ActiveCell.Value <> Date Then

        Cells.Find(What:="=TODAY()", After:= _
        ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Copy
ActiveCell.PasteSpecial xlPasteValues
  Else
End If
10
  ws.Cells(myRw, myCl).Offset(-1, 0).Activate
Application.CutCopyMode = False
End Sub


Q:

How do i get Object index in an array

I have seen many threads about this but my problem doesn't solved. This may be a simple way but i have no idea...
I'm trying to get Objects indices in an array like so :
var test:Array = new Array();

for (var row:Number = 0; row < 2; row++) {
    test[row] = [];
    for (var column:Number = 0; column < 3; column++) {
        test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
        test[row][column] = new ballShape(column, column, row);
        addChild(test[row][column]);
    }
}

function objClicked(evt:MouseEvent):void {
    // Here must return Object index in array
}

P.S :
I can get items index in int array, but i don't know about objects.
Any ideas would be appreciated.
Edit :
ballShape.as
package  {
    import flash.display.Graphics;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import fl.motion.Color;

    public class ballShape extends Sprite {

    private var shapeId:uint;
    private var currentPosition:uint;
    private var arrayPosition:uint;
    private var color:Number;

    public function ballShape(Id:uint, currPos:uint, arrPos:uint) {
        setId(Id);
        setArrayPos(arrPos);
        setCurrentPos(currPos);

        //trace("Array : " + arrPos);
        //trace("Curr : " + currPos);

        if (arrPos == 0) {
            var posX:uint = 60;
        } else {
            var posX:uint = (arrPos + 1) * 60;
        }
        if (currPos == 0) {
            var posY:uint = 42;
        } else {
            var posY:uint = (currPos + 1) * 42;
        }
        if (arrPos == 0) {
            color = 0xFF0000;
        } else {
            color = 0x00FF00;
        }
        graphics.beginFill(color, 1.0);
        graphics.drawCircle(posX, posY, 20);
        graphics.endFill();
        this.addEventListener(MouseEvent.CLICK, Clicked);
    }
    public function setId(Id:uint):void {
        shapeId = Id;
    }
    public function getId():uint {
        return shapeId;
    }
    public function Clicked(evt:MouseEvent):void {
        //return getId();
        trace("Ball id is "  + getId());
        trace("Array id is " + getArrayPos());
        trace("PositionInArray id is "  + getCurrentPos());
        //return arrayPosition;
    }
    public function setCurrentPos(Pos:uint):void {
        currentPosition = Pos;
    }
    public function getCurrentPos():uint {
        return currentPosition;
        trace(currentPosition);
    }
    public function setArrayPos(arrayPos:uint):void {
        arrayPosition = arrayPos;
    }
    public function getArrayPos():uint {
        return arrayPosition;
        trace(arrayPosition);
    }
    public function addBead(arrayId, currPos):void {

    }
}

}

A:

I would suggest adding row and column as public variables in your ballShape class.
That way you can get them like this:
function objClicked(evt:MouseEvent):void {
    trace(ballShape(evt.target).getCurrentPos(), ballShape(evt.target).getArrayPos());
}

Maybe turn this two lines around:
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);

to be :
test[row][column] = new ballShape(column, column, row);
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);


Q:

Display Firebase database content in a FirebaseListAdapter

I am currently experimenting with Firebase by creating a kind of small chat app.
I am able to send data to the database reference, however I would expect it to be displayed thanks to the following code. However that is not the case, I was wondering if there was something wrong with the way I am using the adapter for my list.
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(FirebaseAuth.getInstance().getCurrentUser() == null) {
            // Start sign in/sign up activity
            startActivityForResult(
                    AuthUI.getInstance().createSignInIntentBuilder().build(),
                    SIGN_IN_REQUEST_CODE
            );
        } else {
            // User is already signed in. Therefore, display
            // a welcome Toast
            Toast.makeText(this,
                    "Welcome " + FirebaseAuth.getInstance()
                            .getCurrentUser()
                            .getDisplayName(),
                    Toast.LENGTH_LONG)
                    .show();

            displayChatMessages();
        }

        FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText input = (EditText)findViewById(R.id.input);

                // Read the input field and push a new instance
                // of ChatMessage to the Firebase database
                FirebaseDatabase.getInstance()
                        .getReference()
                        .push()
                        .setValue(new ChatMessage(input.getText().toString(),
                                FirebaseAuth.getInstance()
                                        .getCurrentUser()
                                        .getDisplayName())
                        );

                // Clear the input
                input.setText("");
            }
        });

    }

    private void displayChatMessages() {
        ListView listOfMessages = (ListView)findViewById(R.id.list_of_messages);

        Query query = FirebaseDatabase.getInstance().getReference();

        FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
                .setQuery(query, ChatMessage.class)
                .setLayout(R.layout.message)
                .build();

        adapter = new FirebaseListAdapter<ChatMessage>( options ) {
            @Override
            protected void populateView(View v, ChatMessage model, int position) {
                // Get references to the views of message.xml
                TextView messageText = (TextView)v.findViewById(R.id.message_text);
                TextView messageUser = (TextView)v.findViewById(R.id.message_user);
                TextView messageTime = (TextView)v.findViewById(R.id.message_time);

                // Set their text
                messageText.setText(model.getMessageText());
                messageUser.setText(model.getMessageUser());
                messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
                        model.getMessageTime()));
            }
        };

        listOfMessages.setAdapter(adapter);

    }

 @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == SIGN_IN_REQUEST_CODE) {
            if(resultCode == RESULT_OK) {
                Toast.makeText(this,
                        "Successfully signed in. Welcome!",
                        Toast.LENGTH_LONG)
                        .show();
                displayChatMessages();
            } else {
                Toast.makeText(this,
                        "We couldn't sign you in. Please try again later.",
                        Toast.LENGTH_LONG)
                        .show();

                // Close the app
                finish();
            }
        }

    }

}

Here is the UI of the main activity
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="citroentrex.citron.MainActivity">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:clickable="true"
        android:tint="@android:color/white"
        app:fabSize="mini"
        />

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/fab"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Input"
            android:id="@+id/input"
            />
    </android.support.design.widget.TextInputLayout>

    <ListView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_alignParentTop="true"
      android:layout_alignParentLeft="true"
      android:dividerHeight="16dp"
      android:divider="@android:color/transparent"
      android:layout_above="@id/fab"
      android:id="@+id/list_of_messages"
      android:layout_marginBottom="16dp"
      />

</RelativeLayout>

and of the message
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/message_user"
        android:textStyle="normal|bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/message_user"
        android:layout_alignParentRight="true"
        android:id="@+id/message_time" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_user"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="5dp"
        android:id="@+id/message_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textSize="18sp" />
</RelativeLayout>

displayChatMessages is the bit wher I would expect the adapter to display the data content in my list. (Pushing data to the database works for sure)
This is the model of my database. (there are no child)

A:

The adapter had to be initialised as follow:
@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}


Q:

std::vector performance for pixel buffers

Doing software 2d pixel buffers, blitting, etc. Someone was telling me there's absolutely no overhead involved in using an std::vector to represent objects, I was wondering if std::vector is indeed a good container for pixel buffers or if I should instead stick with a raw array like I've always used.
Thanks

A:

When used properly, there shouldn't be any overhead in performance. But, they aren't exactly zero-overhead compared to raw arrays.
Size overhead
A typical std::vector container will use 3 pointers. Since you probably already track width and height yourself, your raw array could be done in one pointer since you already know the size.
Allocation overhead
You will incur some overhead when allocating the memory for the std::vector. However, this is the same overhead you incur if you allocate your own memory.
Zero-initialization overhead
std::vector will actually zero-init your memory when using resize(), which may or may not be significant to what you're doing.
But, from a performance standpoint, accessing a std::vector is the same as accessing an array.


Q:

How do I efficiently search for ICs?

I am a computer engineering student with an electronics background (i.e. mandatory circuit design and analog electronic courses) and my degree thesis requires me to design an electronics project.
So now I have this project to get done and of course I have to look for ICs that do this and that. Do I just Google stuff until I find what I need? I feel really lost since my electronics background is just that, a background, so I know how diodes, opamps and transistors work but I have no idea what the various acronyms (like PHY, MIPI, TTL and so on) mean, so what usually happens is I Google "integrated feature 1 feature 2 ", then I click on any results that look related, read datasheets (when I can find them, since many are under NDA), stop to Google any acronym I don't know, which usually gets me to know what it means but not how it works, rinse and repeat.
Some of the time I can actually find what I want, but most of the time I just spend a whole day staring at my screen feeling completely lost and at the end of the day I turn off my computer feeling like I haven't accomplished anything. Most components look like they are not interoperable, have different standards for input and output or actually have the same standards but call them by different names because of copyright!
So my question is: how do I efficiently search for the ICs I need? My project doesn't sound so hard on paper, I have a very good idea of what I have to do but I have a hard time finding the components I need. Am I doing this wrong?

A:

To be honest, you're asking 'How do I understand a massive subject quickly so I can design a project' and the answer is 'you can't', as you probably gathered. Your best path is to contact an experienced electronics engineer who can work with you on what you're trying to do.
As a start, search/look for demonstration boards that may be similar to your application you're designing. Bear in mind that will just give you examples of what you're trying to do, not the knowledge to reliably do it yourself.
But to go from zero to connecting and using something like a PHY reliably isn't something you'll discover from the relatively short amount of browsing time that a thesis makes available.

A:

Summary: It's an incremental process, not a "big bang", to go from college theory work to a substantial project. There is no substitute for experience.

After reading the whole question, I don't think your real question is the title of "Where and how do I search for ICs?". Instead I think your real question is more like - how can you choose components for a project, when you don't understand what components you need, and you don't understand enough of the datasheets to be confident that you are choosing suitable components.

I am a computer engineering student and started being interested in electronics for my degree thesis.

You don't say how much electronics is taught in your computer engineering course. However even though you are interested in electronics, if they aren't teaching you enough electronics for what you want to do in your thesis, then don't try to make this an electronics thesis. Instead, keep electronics as a hobby interest for now and focus on what you can do for your thesis.
As already mentioned in comments, you should consider approaches like block diagrams. That is similar to decomposition in computer programming, where you break down a system requirement into functions, data types etc.
But what if you don't know enough about which electronic components are currently available, to know what blocks in your block diagram are sensible?
You said that you...

feel that what I'm missing is a primer on...the real world or something.

Many (most?) of us went from theory to "real world" in steps by doing projects, starting with something small and getting bigger each time. I doubt that anyone went straight from theory to a (successful) big project. That experience, of making increasingly complex projects, does a few things (just like learning any new skill):

You increase your confidence for tackling more complex projects, because of each previous success.
You get to expand your knowledge of current technology with each new project. Each time you can focus on learning only what is new & different in that project, relying on your experience from previous projects for elements that are common between those projects and the new project.
This increasing knowledge helps you to know what sensible "blocks" you can include on your next project block diagram. For example, at the beginning, you might not know how to detect when a voltage is above an upper limit or below a lower limit. For that project, you do some research and find there's a term for that — window comparator — and you can add that to the list of blocks which you can include in future block diagrams.
Another important way to increase your knowledge incrementally is to read project-based books or magazines (Elektor is a current example of such a magazine - there were many others in the past, which have now disappeared) and build at least some of the projects. With each project you will learn new things, including new "blocks" (ICs, interfaces, functionality like window comparators etc.) for your future block diagrams.

A few final points, from my own experience:

Sometimes you need to allow yourself to fail, at least initially, because that is when you are likely to learn the most.
If you always do the same project type (e.g. flashing LEDs) then you will eventually be able to do them in your sleep, but you won't learn anything new. If you try something requiring different knowledge (e.g. designing a switch-mode power supply) it is more likely not to work first time. You'll learn lots from troubleshooting and fixing it, but that will take time - so don't choose a "stretch goal" project requiring new knowledge, with a hard deadline.
One example of a book which is somewhere between the "circuit design" books you already found and real world knowledge, is "Practical Electronics for Inventors" by Paul Scherz and Simon Monk. Early editions had several mistakes, and even the current latest (4th) edition has errata - but at least errata lists are available. Another example is "Practical Electronics Handbook" by Ian Sinclair and John Dutton. These books contain examples of the circuit design "building blocks" which you might find useful. You might prefer the style and contents of one book over another, so these are not specific recommendations, just examples of the type of book you might find useful.
There is always "The Art of Electronics" by Paul Horowitz and Winfield Hill. However that is heavy on theory. So while it does include some practical information, if you haven't already read this book, check to see if it is "practical enough" for you.
However, books on their own aren't enough. You have to try some projects, to find either "that was much easier than expected, so I can try something harder next time", or "oops, that is much harder than expected, I'll pick something simpler to build up my knowledge from a lower starting point".

In short: It's an incremental process, not a "big bang", to go from college theory work to a substantial project.


Q:

Maximum length of an SQL Query

SELECT f.*
FROM feeds f,
     user_feeds uf
WHERE (f.id=uf.feed_id and uf.user_id in (1,2,5,6,23,45))
ORDER BY created_at DESC

This is a query used to construct a user's feeds. The issue I have with this query is that the "uf.user_id in ()" increases as the number of users he follows increase.
What is the allowed max length of an SQL query ?
Is there a better way to implement my above query ?
Note: I am using ActiveRecord. And I am using Postgres.

A:

The maximum length of a query that PostgreSQL can process is 2147483648 characters (signed 4-byte integer; see src/include/lib/stringinfo.h).

A:

To avoid the query size, you could replace the IN (1, 2) with IN (select followed_id from following where follower_id = ?) or whatever the appropriate query would be to find the ids of the followed users from the follower's id.

A:

While there is no (real) limit on the length of the query string, there is a limit on the number of IN (x,y,z...) clauses: 10000, configurable in the postgres.ini-file:
See:
http://grokbase.com/t/postgresql/pgsql-general/061mc7pxg6/what-is-the-maximum-length-of-an-in-a-b-c-d-list-in-postgresql :
"In 7.4 and earlier it depends on the max_expr_depth setting."
...
"In 8.0 and later max_expr_depth is gone and the limit depends on
max_stack_depth."


Q:

Change button label text dynamically in razor pages

I am using Razor Pages in my ASP.NET Core web application.
I would like to change the button text from code-behind.  Even if i add runat="server" in Html markup and I can't access the button in *.cshtml.cs file.
Also, I can not use <asp:button> in razor pages. Is there any way to do without using the javascript approach?
<input type="submit" value="Create" class="btn btn-primary"/>

MyPage.cshtml.cs
public IActionResult OnGet(Guid id)
{
if(id == Guid.Empty) //Make button create
else // make it update
}

A:

Razor Pages in .net core are quite a bit different than classic aspx pages. There are a number of good intro articles out there in this one from MS. Using your question and some sample code from that article this what the page might look like.
The cshtml file might look like:
@page
@using RazorPagesIntro.Pages
@model IndexModel2

Separate page model

    <input type="submit" value="@Model.Label" class="btn btn-primary"/>

The cshtml.cs page model:
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;

namespace RazorPagesIntro.Pages
{
    public class IndexModel2 : PageModel
    {
        [BindProperty]
        public string Label { get; set; }

        public void OnGet()
        {
            if (id == Guid.Empty) {
                Label = "Create";
            } else {
                Label = "Update";
            }
        }
    }
}


Q:

How does llvm-ld locate libstdc++

Short question:
How does llvm-ld locate libstdc++?
Details:
I am getting the following error message:
llvm-ld: error: Cannot find library 'stdc++'
while running llvm-ld.  I am trying to understand how llvm-ld searches for libstdc++.
I am setting up a new system and following compilation steps that work on a different system.  Eventually I noticed a difference with the LD_LIBRARY_PATH that was set in my .bashrc on the old system that included a large number of directories including for Cadence and other miscellaneous software.  I don't want to use the LD_LIBRARY_PATH, I want to be able to link against libstdc++ by supplying the appropriate command line parameters to llvm-ld.
The command I am running is:
llvm-ld -disable-internalize -native -o foo foo.bc4 -L/usr/lib/x86_64-linux-gnu -lpthread -lrt  -lstdc++ -lm -v

which results in the following output:
  Linking bitcode file 'foo.bc4'
  Linked in file 'foo.bc4'
  Linking archive file '/usr/lib/x86_64-linux-gnu/libpthread.a'
  Linking archive file '/usr/lib/x86_64-linux-gnu/librt.a'
llvm-ld: error: Cannot find library 'stdc++'

However running ls -l /usr/lib/x86_64-linux-gnu/libstdc++* results in:
lrwxrwxrwx 1 root root     19 Apr 15 16:34 /usr/lib/x86_64-linux-gnu/libstdc++.so.6 ->    libstdc++.so.6.0.16
-rw-r--r-- 1 root root 962656 Apr 15 16:36 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16

So I don't understand why llvm-ld is not finding this file?  Especially since when I compile with with the LD_LIBRARY_PATH set and then run ldd on the resulting executable I get the following output:
linux-vdso.so.1 =>  (0x00007ffff7ffe000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007ffff7dc1000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007ffff7ac0000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007ffff77c6000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007ffff75b0000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffff71f0000)
/lib64/ld-linux-x86-64.so.2 (0x0000555555554000)

Which seems to indicate that the version of libstdc++ that I want is /usr/lib/x86_64-linux-gnu/libstdc++.so.6 but I can't figure out why llvm-ld is not locating it with the search path -L/usr/lib/x86_64-linux-gnu.
For reference: uname -a results in: Linux FOO 3.2.0-30-generic #48-Ubuntu SMP Fri Aug 24 16:52:48 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
And llvm-ld --version:
LLVM (http://llvm.org/):
  LLVM version 3.1svn
  Optimized build.
  Built Sep 14 2012 (13:22:38).
  Default target: x86_64-unknown-linux-gnu
  Host CPU: core2

A:

It looks like llvm-ld isn't looking for .so.#. According to the man page:

When looking for a library specified with the -l option, llvm-ld first attempts to load a file with that name from the current directory.  If that fails, it looks for liblibrary.bc, liblibrary.a, or       liblibrary.shared library extension, in that order, in each directory added to the library search path with the -L option.  These directories are searched in the order they are specified.  If the library cannot
   be located, then llvm-ld looks in the directory specified by the LLVM_LIB_SEARCH_PATH environment variable.  If it does not find a library there, it fails.

You can make this work by creating a symlink /usr/lib/x86_64-linux-gnu/libstdc++.so -> libstdc++.so.6.
I usually link with clang directly, since it understands searching for C++ library things better.


Q:

Facebook Login Error Code 1 Sub code 1357045

I have implemented a login with facebook method in my website. Originally it works fine, but suddenly this past few days it won't work anymore, even tough I don't change any source code or settings. After some tracing, I found the problem is when I call FB.api /me? it returns this error:
Error Code 1
Error Sub Code 1357045
Message Unknown Error (empty response)
Type Http
Status 0

Does anyone can help me, please ??
FIXED:
Problem solve at this thread Facebook Login JAvascript SDK, Content Securty Policy

A:

Also this error can be because of some extension added to your browsers such as addBlock, Ghostery etc. In my case it was Ghostery.


Q:

reading docx (Office Open XML) in PHP

I want to add an word import function to our CMS, the only problem I cannot seems to find a good library for reading docx files (Word 2007).
Do anyone has some recommendations, the library should be able to extract content of the document and basic styling like italic, bold, superscript?
Thanks for your help

A:

docx files are actually just containers for the document's XML. You should be able to unzip the docx file and then go to the word folder inside, then to the document.xml. This has the actual text. But things like the fonts and styles are in other xml files in the docx container, so you'll probably want to mess around a bit and figure out what is what and how to match it up (start by using namespaces, I bet).
But yea, unzip the file, then use simplexml to convert it into something you can actually mess around with.

A:

There is a library to do this but it works with Zend framework may be it will help you
It is called phpLiveDocx : http://www.phplivedocx.org/downloads/
The library is licensed under New Bcd

A:

PHPDocX PRO includes a TransformDoc class that can read .docx (zip) files and generate XHTML (or PDF) from it:
...
require_once 'phpdocx_pro/classes/TransformDoc.inc';
$doc = new TransformDoc();
$doc->setStrFile($file->filepath);
$doc->generateXHTML();
$html = $doc->getStrXHTML();


Q:

how can i make this be height: 100vh on mobile and or scrollable

I am working on a small Web-App. I want to make it responsive for smaller devices. Problem is, on mobile, the sidebar is not scrollable to see the last item on bottom, and i don't know how to make it look good on mobile screen.
Solution would be something like:
@media (max-width: 500px) {
  #sidebar {
    height: 100vh;
  }
}

but this isn't working and idk why. any ideas?

A:

You can try this inside your "nav" tag
height: 100%;
overflow: scroll;

It's because you working with pixels. It's better for responsive sites to work with a percentage number. Also, try to search for "overflow" propriety


Q:

Fade out background pic without beamer

I am writing a technical report with a background figure on the cover. I want to add a fade-out effect to the image and I have found this  answer How to add a gradient fade-out effect to an image? but with the beamer class.
Is there a way to have the same effect with the article class?
My MWE is the following:
\documentclass[12pt,twoside,titlepage]{article}
\usepackage{graphicx}
\usepackage{eso-pic}
\newcommand\BackgroundPic{%
\put(0,0){%
\parbox[b][\paperheight]{\paperwidth}{%
\vfill
\centering
\includegraphics[width=\paperwidth,height=\paperheight,%
keepaspectratio]{Textura.pdf}%
\vfill
}}}

\begin{document}
\begin{titlepage}
\AddToShipoutPicture*{\BackgroundPic}
\end{titlepage}
HOLA

\end{document}

Thank you

A:

You can use the same code as in the beamer example. The relevant piece of code is the tikzpicture environment, where the image and the fade-out is specified. This code uses the tikz package and the fadings library for TikZ, which you have to add in the preamble (at the start of the code, between the documentclass and \begin{document}).
MWE:
\documentclass[12pt,twoside,titlepage]{article}
\usepackage{graphicx}
\usepackage{eso-pic}
\usepackage{tikz}
\usetikzlibrary{fadings}
\newcommand\BackgroundPic{%
\begin{tikzpicture}
\path (0,0) rectangle (\paperwidth,\paperheight);
\node[scope fading=west,inner sep=0pt,outer sep=0pt,anchor=north east] at(\paperwidth,\paperheight) {\includegraphics[width=\paperwidth,height=\paperheight,keepaspectratio]{example-image-c}};
\end{tikzpicture}
}

\begin{document}
\begin{titlepage}
\AddToShipoutPicture*{\BackgroundPic}
\end{titlepage}
HOLA

\end{document}

Result:


Q:

Initialize an ActiveRecord instance using a parameter not on the table

The User model has an id column that is used all throughout your schema, but you'd like to create other models using the username rather than the id:
User.create!(username: "phillip")
User.create!(username: "joe")
Message.create!(from_username: "phillip", to_username: "joe", message: "hello")

Here, 'from_username' and 'to_username' don't actually exist on the table. Rather, there is a 'from_id' and 'to_id'. You can add 'from_username' and 'to_username' as methods to the model, but then you can't create a new Message using them.
What is the recommended way to add these 'virtual attributes' to a model?

A:

Most idiomatic way
You could define a custom create function, like this:
class Message < ActiveRecord::Base
  def self.create_from_usernames(from_username, to_username)
    from_user = User.find_by_username(from_username)
    to_user = User.find_by_username(to_username)
    self.create(from_user: from_user, to_user: to_user)
  end
end

Making call-site code handle this itself
This is still somewhat idiomatic, but not very DRY.
from_user = User.find_by_username("phillip")
to_user = User.find_by_username("joe")
Message.create!(from_user: from_user, to_user: to_user)

Using create directly
This is not really recommended, but you could do something like this:
class Message < ActiveRecord::Base
  attr_accessor :from_username, :to_username

  before_create :find_users

private
  def find_users
    self.from_user = User.find_by_username(from_username)
    self.to_user = User.find_by_username(to_username)
  end
end

This leads to somewhat "magical" behavior though, and there should be more error checking / handling if you're going to do it.


Q:

Overall view validation with a datagrid and keeping to MVVM

I am struggling to find a good architecture for what must be a common problem

Enable/Disable a button in a View that contains a datagrid, and has
  validation requirements on the cell, row and collection  levels. And to perform this cleanly in a MVVM architecture.

If it wasn't for the datagrid then this would be easy, I'd just check the overall result of either an INotifyDataErrorInfo or IDataErrorInfo implementation on the ViewModel and use existence of any errors to disable the button via the ICommand interface to the button, that resides in the ViewModel.
However the data grid complicates things, and I find myself going back and forth between doing data validation in the ViewModel or in the View itself.  EG:

Validation in the ViewModel keeps the validation closer to the datasource and I can implement INotifyDataErrorInfo on each item in the collection.  This enables me to validate on a cell and row level, but there appears to be no support for validating against the overall collection itself - and I have yet to find a decent solution that can do this (see link below).  (And I don't want to pollute the items in the collection by adding some reference to an external entity to them).
Validation in the View itself (using validation rules on the datagrid) allows me to validate on the cell, row and collection level1, but I can't see how to communicate the presence of errors to the ViewModel as nothing is passed back to the ViewModel unless it is valid.

The closest solution I have seen online that solves all of my problems is this 2014 TechNet one - Data Validation in MVVM
But it is as ugly as ugly can get2.  To quote from that page (emphasis mine):

The Most Important thing is to disable the Save button when the form
  is invalid. For this we had a static property in our view model named
  Errors. When the Error is occurred the Error count is increased by 1.
  When the error is corrected the error count is decreased by 1. So when
  the Count is 0 the save will be enabled or disabled.

The author's solution is put a static counter on the ViewModel and set a call back in the View itself. When an error is detected in the ViewModel the IDataErrorInfo interface passes that information up to the View which then increments the counter on the ViewModel, and the value of the counter is use to disable the button.
In addition, to perform validation on a collection level, they implement another static variable on the ViewModel which is set to the instance of the collection in the current ViewModel.  Thus an item validates itself against the entire collection by finding the collection from this static variable.
This code makes me cringe.
So what am I missing?  How can I easily, cleanly, and keeping to strict MVVM guidelines, perform validation of an overall ViewModel that requires validation of a data grid at the cell, row and collection levels?  And communicate the results of that validation back to the ViewModel itself?

1 In order to perform validation at the collection level using ValidationRules I created a custom rule as per this SO question https://stackoverflow.com/a/10555571/31326 that injects the binding source of the data grid into the rule.  This cleanly allows you to do validation at the collection level.
2 According to the comments at the bottom of that link, this article won prizes!

Update
I am going with a modified version of Emerson's answer.  I am going to keep the internal validation within the object view model, but inject in a validation test for doing collection level validation.  The following code lays out my ideas.  This code seems to work (and probably could be optimised), but I am not sure if I am going to hell for it :D
// Base of all view models
// Handles property notification and error notification
public abstract class ViewModelBase<T> INotifyPropertyChanged, INotifyDataErrorInfo :  where T : class
{
    // Validate view model against external sources
    // Return a list of errors
    protected Func<T, List<String>> ExternalValidate = null;

    // Rest of INotifyPropertyChanged and INotifyDataErrorInfo implementation etc.
    protected void AddError(string error, [CallerMemberName] string propertyName = null)
    {
      INotifyDataErrorInfo.AddError(error, propertyName);
    }

    protected void AddError(List<string> errors, [CallerMemberName] string propertyName = null)
    {
      foreach(var error in errors)
      {
        INotifyDataErrorInfo.AddError(error, propertyName);
      }
    }
}

// The Product data model
public class Product
{
  public int Number { get; set; }
}

// Adapts a Product Data/Domain model to a view model
// Does all the error checking for the view model both within and external to this one object
public class ProductViewModel : ViewModelBase<ProductViewModel>
{
  public int Number
  {
    get { return _Number; }
    set
    {
      // Validate "value" against other properties in *this* view model
      if (value<0) AddError("can't be negative");

      // Validate against **External** values
      if (ExternalValidate != null)
      {
        var errors = ExternalValidate(this);
        if (errors != null) AddError(errors);
      }
    }
  }
  protected int _Number;

  public ProductViewModel(Func<ProductViewModel,List<string> externalValidate, Product product)
  {
    // The external validation check
    ExternalValidate = externalValidate

    // Initialize PVM from product
    _Number  = product.Number;
  }
}

// Holds the collection of ProductViewModel objects
// Defines the collection level validation rules
// Injects those rules into the ProductViewModel objects
// The key thing is capturing the values in the Func.
public class MainVM()
{
  public int TheAnswer {get; set; } = 42;

  public List<ProductViewModel> PVMS = new List<ProductViewModel>();

  Func<ProductViewModel, List<string>> ExternalTest = (ProductViewModel pvm) =>
  {
    var result = new List<string>();
    foreach(var pvms in PVMS)
    {
      if (!Object.ReferenceEquals(ppm,pvms)
      {
        if (ppm.Number == pvms.Number)
        {
          result.Add("Can't have duplicates");
        }
      }
    }

    if (pvm.Number == TheAnswer)
    {
      result.Add("Can't equal the answer");
    }

    return result.Count>0 ? result : null;

  }

  List<Product> products = GetProductsFromSource();

  foreach(var product in products)
  {
    PVMS.Add( new ProductViewModel(ExternalTest, product) );
  }
}

In the above code, whenever the Number property of the ProductViewModel is set, the class will validate within itself and then call the external validation.  If the Number is duplicated or set to the current value of TheAnswer then an error message will be generated.
The jumping through hoops to get to this means that my ProductViewModel does not know that it is a part of a collection and simply validates itself against some externally defined set of conditions. These external conditions could be anything, such as iterating over the collection and looking for duplicate values, or in this case checking that the Number property doesn't equal some particular value.
And by placing the conditional check in an generic base class this code is reusable.

A:

Supposing you have a Product class, each product shouldn't know about other products in the list.
In your GUI, I suggest you use a ProductViewModel, responsible to validate all info. Therefore, there's no problem in making the ProductViewModel to have knowledge of other instances of the same type in its parent collection. After all validation succeeds, you could generate a collection of Product if necessary.
Here's some code trying to illustrate my suggestion:
Your data entity class
public class Product {
    public int Id {get;set;}
    public string Name {get;set;}
}

Your view model (responsible to validate everything)
//Represents the view model for the Product.
//This view model is responsible for validating information of the product.
//As part of  this validation, it is necessary that this instance know
//details of the collection it belongs.
public class ProductViewModel : INotifyDataErrorInfo {

    //This could be injected via constructor or property.
    //Represents the collection of products, that requires validation
    //See its definition below
    private ProductViewModelCollection parentCollection;

    public int Id {
        get { return _id; }
        set { if (ValidateId(value))) _id = value; }
    }
    public string Name {
        get { return _name; }
        set { if (ValidateName(value)) _name = value; }
    }

    //The methods below validate all info.
    //Alternatively, you could implement the validation somewhere else,
    //and inject the necessary validators into this viewModel instance.
    private bool ValidateId(int id) {
        //... validate the id...

        foreach (ProductViewModel otherProduct in parentCollection) {
            //...if necessary, perform additional validations comparing
            //with other products in the parent collection
        }
    }
    private bool ValidateName(string name) {
        //... validate the name...

        foreach (ProductViewModel otherProduct in parentCollection) {
            //...if necessary, perform additional validations comparing
            //with other products in the parent collection
        }
    }

    //...implementation of INotifyDataErrorInfo...
}

Your collection of products, it is the source for the datagrid
public class ProductViewModelCollection : ObservableCollection<ProductViewModel>, IINotifyDataErrorInfo {
    //...implementation of INotifyDataErrorInfo...
}

After this, you won't need to use built-in validation of UI components; you can implement everything in the view model, being able to unit test it accordingly. The knowledge across collection is implemented in the ViewModel (because your GUI requires it), not within your data entity.
UPDATE: Second approach (via injection):
//Represents the view model for the Product.
//This view model is responsible for validating information of the product.
//As part of  this validation, it is necessary that this instance know
//details of the collection it belongs.
public class ProductViewModel : INotifyDataErrorInfo {

    //Injected via constructor or property.
    private IProductValidator validator;

    //String properties, IF YOUR GUI ALLOWS user to type
    //text in the fields
    public string Id {
        get { return _id; }
        set { if (validator.ValidateId(value))) _id = value; }
    }
    public string Name {
        get { return _name; }
        set { if (validator.ValidateName(value)) _name = value; }
    }

    public Product GetProduct() {
        //...generate Product object with valid info...
    }
}

public class ProductValidator : IProductValidator {

    //This could be injected via constructor or property.
    //Represents the collection of products, that requires validation
    //See its definition below
    private ProductViewModelCollection parentCollection;

    //The methods below validate all info.
    //Alternatively, you could implement the validation somewhere else,
    //and inject the necessary validators into this viewModel instance.
    private bool ValidateId(string id) {
        //... validate the id...

        foreach (ProductViewModel otherProduct in parentCollection) {
            //...if necessary, perform additional validations comparing
            //with other products in the parent collection
        }
    }
    private bool ValidateName(string name) {
        //... validate the name...

        foreach (ProductViewModel otherProduct in parentCollection) {
            //...if necessary, perform additional validations comparing
            //with other products in the parent collection
        }
    }

    //...implementation of INotifyDataErrorInfo...
}


Q:

How to find amplitude and frequency of an incoming sinusoidal signal (analog) in VHDL

In my application, there's an incoming sinusoidal signal and I need to find its frequency and amplitude by VHDL coding. This is non-synthesisable as we are not implementing it on FPGA.
So far I've been using the "MAXIMUM" function of VHDL to find the amplitude. In testbench, I am  successfully generating the sine wave, and so in my source code I am using the maximum function. But the problem is that I am not getting one value but several.
Here's the sample of my code;
--in the entity
(input_sine : real;
    Amp_out : real;
    frq_out : real);
end entity;

--in the architecture,

signal S_amp : real := 0.0;

process

begin

  Amp_out <= MAXIMUM(input_sine, S_amp);

  wait for 1 us;

end process;

I expect the output to be just one value i.e, the maximum amplitude value of the input sinusoidal wave. And also to find its frequency. I'm not sure how to proceed, neither am I with this maximum function. So, someone please help me with this.
Thanks in advance.

A:

The VHDL MAXIMUM function returns the maximum (ie larger) value of its two inputs. Your two inputs are input_sine and S_amp, which is always 0.0. So, Amp_out will equal input_sine when input_sine is positive and 0.0 when it is negative.
https://www.edaplayground.com/x/4nsb
To find the maximum value of input_sine (ie its amplitude) and its frequency, you're going to have to write some code. This is a hardware description language, not Matlab.


Q:

Button Group Border Radius issue

I'm trying to have a button group that works for having multiple buttons inside it, or just one.
Here's a fiddle: http://jsfiddle.net/jssq20gn/
Here's the html:

       Test
       Test
       Test

       Test
       Test

       Test

It works for when there is more than one button, but when there is only one button, the button doesn't have rounded corners on all sides.

A:

The issue is :last-child is getting called after :only-child. And while this is an "only-child" it's also a "last-child" so the :last-child selector is overwriting the only:child in the CSS hierarchy. Move :only-child below :last-child:
.btn-group .button:last-child {
  border-radius: 0 6px 6px 0;
  margin-left: -1px;
}

.btn-group .button:only-child {
  border-radius: 6px;
  margin-left: 0;
}

FIDDLE