text:
Q: How bind works with new and instanceof? I had an interview yesterday and there was a task to write JavaScript class that can be created with multiple new and created object has to be instance of all its parents. I tried to do it using Function.bind() but it didnt work.

function JSObject() {
  return JSObject.bind(null);
}

var obj1 = new JSObject();
var obj2 = new obj1();
var obj3 = new obj2();

console.log(obj2 instanceof obj1); // prints false, expected true
console.log(obj3 instanceof obj2); // prints false, expected true
console.log(obj3 instanceof obj1); // prints false, expected true

console.log(obj1 instanceof obj2); // prints false, expected false
console.log(obj1 instanceof obj3); // prints false, expected false

let objects = [JSObject, new JSObject()];

for (let i = 0; i < 10; i++) {
  objects.push(new objects[objects.length - 1]());
}

for (let obj of objects) {
  const objProt = Object.getPrototypeOf(obj);
  const objProtProt = Object.getPrototypeOf(obj.prototype);
  const funcProt = Object.getPrototypeOf(Function);
  const funcProtProt = Object.getPrototypeOf(Function.prototype);
  console.log(objProt === funcProt); // expected true
  console.log(objProtProt === funcProtProt); // expected true
}

In addition I cant change prototype directly, tests have check that prototype of Object has to be Function

A: This isn't really a "class", since you cannot distinguish between a constructor and an instance. Every "constructor" function just creates new objects that are themselves "subclasses".
function inherit(parent) {
    function object() {
        return Object.setPrototypeOf(inherit(object), object.prototype);
    }
    object.prototype = Object.create(parent.prototype);
    return object;
}
var JSObject = inherit(Function);

Or using ES6:
function inherit(parent) {
    return class object extends parent {
        constructor() {
            return Object.setPrototypeOf(inherit(object), new.target.prototype);
        }
    }
}
const JsObject = inherit(Function);

These even achieve obj instanceof Function and obj.prototype instanceof Function (and instanceof Object, of course). Your additional requirements of Object.getPrototypeOf(obj) == Function.prototype and Object.getPrototypeOf(obj.prototype) == Object.prototype are not achievable. (Assuming we don't use stateful proxies that cheat your tests).


text:
Q: Saving JsonResult to HttpContext.Session Based on this article i am saving my jsonresult like this
HttpContext.Session.SetObjectAsJson(multiple, jsonresult);

then i am retrieving it like this
var myComplexObject = HttpContext.Session.GetObjectFromJson<FileUploads>(multiple);

my problem is that i am getting different data when i retrieve it. for example the jsonresult has a FileUploadsID but myComplexObject has a different ID.
when i use
HttpContext.Session.GetString(multiple);

The FileUploadsID is correct. It is just when i use the GetObjectFromJson that it is different.
Have i done this right? I am not sure what is going on.

A:
Why is it a bad practice to store file in session state?

First of all, HTTP is state less. We like to keep it that way in ASP.NET MVC, so we try not to use Session State in ASP.NET MVC as much as possible unless we really have to.
Storing data in session state is basically storing them in server's memory.~ If we store large amount of data, the server will eventually throws OutOfMemory exception, and app domain will restart.
In addition, if application crashes for any reason, we will lose everything we stored in memory.
~In web farm, Session is stored in distributed system like SQL Server or Redis Cache to synchronize the session across the farm.

redpajama_set_name: RedPajamaStackExchange


text:
Q: page-id/notifications returns an empty array I'm writing a desktop application using Facebook SDK .NET. This app must do somethink for every post, comment or message sent to a Facebook page. I'm using the page-id/notifications API command:
page-id/notifications?fields=id,title,unread,application,from,message,object&limit=250
This command returns correct unseen count in summary section but data array is empty:
{
  "data": [
  ],
  "summary": {
    "unseen_count": 2,
    "updated_time": "2016-02-05T14:53:10+0000"
  }
}

If someone write a new wall post on the page or send a private message to the page, unseen_count is updated but data array is always empty. If someoune write a comment to an exisiting wall post unseen_count is updates and data array is populated with a comment notification (only this type of notification are added to data array):
{
  "data": [
    {
      "id": "notif_XXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXX",
      "title": "yyyyy yyyyyyy commented on his post.",
      "unread": 1,
      "application": {
        "link": "https://www.facebook.com/games/?app_id=xxxxxxxxxxx",
        "name": "Feed Comments",
        "id": "1967xxxxxxx"
      },
      "from": {
        "name": "Mxxxx Sxxxxxx",
        "id": "1020xxxxxxxxxxxxx"
      },
      "object": {
        "created_time": "2016-02-05T14:52:32+0000",
        "message": "ABCDEFGHILMNOPQRSTUVZ",
        "id": "36xxxxxxxxxxxx0_546xxxxxxxxxxx0"
      },
      "to": {
        "name": "Ixxxxxxx",
        "id": "36xxxxxxxxxxxxx"
      }
    }
  ],
  "paging": {
    "previous": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
    "next": "xxxxxxxxxxxxxxxxxxxx
  },
  "summary": {
    "unseen_count": 3,
    "updated_time": "2016-02-05T14:55:23+0000"
  }
}

Is it an API bug or there is something wrong in my API request?
I CANNOT use real time notification.
Thanks
Marco


text:
Q: How do I add/use an embedded SQLite in a Java project? I'm trying to add an embedded database to my application, but I have no clue where to begin. So far I've found that I should download the sqlite-jdbc driver and add the .jar to my project. From there I'm kind of lost, are there any good tutorials to get me started or some helpful tips?
Also, I'm using Eclipse for my IDE, so if there's anything within there that will simplify the process, feel free to add that as well!

A: You want dependency management here? Read up on Maven (very easy), write a Maven pom.xml file and load it into Eclipse that way. Eclipse and NetBeans understand Maven very well now. No need to learn an Eclipse-specific way to do this since Maven will work as well in NetBeans as Eclipse and is simple to run on the command line too.
Based on what search.maven.org says, your dependency in Maven would be this added to a standard pom file to get the latest:
<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.7.15-M1</version>
</dependency>


text:
Q: Rails 3: Uniqueness validation for nested fields_for - Part2 I am new to coding - and have not enough reputation to comment this answer:
Rails 3: Uniqueness validation for nested fields_for
So I am creating this question as "Part 2" :)
I am a web designer but curious to learn coding, held with this from my days.
# app/validators/nested_attributes_uniqueness_validator.rb
class NestedAttributesUniquenessValidator < ActiveModel::EachValidator
        record.errors[attribute] << "Products names must be unique" unless value.map(&:name).uniq.size == value.size
      end
end

above code with "ActiveModel::EachValidator" throw this error:
"undefined method `map' for "Area 1":String"

# app/validators/nested_attributes_uniqueness_validator.rb
class NestedAttributesUniquenessValidator < ActiveModel::Validator
    record.errors[attribute] << "Products names must be unique" unless value.map(&:name).uniq.size == value.size
  end
end

above code with "ActiveModel::Validator" throw this error:
"Subclasses must implement a validate(record) method. "

this is model file:
class Area < ActiveRecord::Base

  validates :name,
            :presence => true,
            :uniqueness => {:scope => :city_id},
            :nested_attributes_uniqueness => {:field => :name}

  belongs_to :city

end

You can find complete code over here:
https://github.com/syed-haroon/rose

A: @Syed: I think you are trying to do this. else reply to my comment.
# app/models/city.rb
class City < ActiveRecord::Base
  has_many :areas
  validates :areas, :area_name_uniqueness => true
end

# app/models/area.rb
class Area < ActiveRecord::Base
  validates_presence_of :name
  validates_uniqueness_of :name
end

# config/initializers/area_name_uniqueness_validator.rb
class AreaNameUniquenessValidator < ActiveModel::Validator
  def validate_each(record, attribute, value)
    record.errors[attribute] << "Area names must be unique" unless value.map(&:name).uniq.size == value.size
  end
end

A: I found the answer over here :
https://rails.lighthouseapp.com/projects/8994/tickets/2160-nested_attributes-validates_uniqueness_of-fails
&
validates_uniqueness_of in destroyed nested model rails
This is for rails 2, one line need to me modified over here:
add_to_base has been deprecated and is unavailable in 3.1. Use self.errors.add(:base, message)


text:
Q: C output formatting using tabs My code
int main(void){
    int arr1[6],arr2[6];
    const char * weather[] = {"January","February","March","April","May","June"};

    printf("Enter 6 numbers for Arr1");  //get values for arr1
    for(int i = 0;i<6;i++){
        scanf("%d",&arr1[i]);
        //avg2 = intarr[i] + avg2;
    }

    printf("Enter 6 numbers for Arr1");  //get values for arr2
    for(int i = 0;i<6;i++){
        scanf("%d",&arr2[i]);
        //avg2 = intarr[i] + avg2;
    }

    for(int i = 0;i<6;i++){ . //print values for arr1
        printf("\n%s        ",weather[i]);
        printf("|");
        for(int k = 0;k<arr1[i];k++){
            printf("*");
        }
        printf("\n      |");
        for(int k = 0;k<arr2[i];k++){
            printf("!");
        }
    }
}

Output:
https://i.imgur.com/GymyHqD.png
I'm confused on how to get the February line to format correctly. As shown, it is off by the others by one tab. Is there an easy way to format this?

A: Why not just printf the string left justified with a length modifier.
printf("%-20s", weather[i]);

Will print weather[i] :

*

*-  makes it left justified

*20 makes the length of the field to 20 characters. Empty places are filled with spaces.


text:
Q: jQuery move/prepend html text in a list not working I would like to move / prepend each list item text (Brochure A, Brochure B etc) from wpdf_file_name class to the row_downloadbutton > a then remove row_filename

Brochure A

Download

Brochure B

Download

    ...

    ...

This is my jQuery:
jQuery(".row_downloadbutton>a").each(function(){
   jQuery(this).prepend(jQuery('.wpdf_file_name').html());
});
jQuery(".row_filename").remove();

However only Brochure A is getting repeated to the row_downloadbutton..not Brochure B, Brochure C etc etc
I have tried .children(), .siblings(), .closest() but not working.
Thanks!

A: For each download link, get the .closest() common parent (could be .clearfix or li or both in your case), then .find() the corresponding .wpdf_file_name :

(function($) {
  $(".row_downloadbutton > a").each(function() {
    $(this).prepend(
      $(this).closest('li.clearfix').find('.wpdf_file_name').html()
    );
  });
  $(".row_filename").remove();
})(jQuery);

Brochure A

        Download

Brochure B

        Download

A: You can use closest and find like this:
jQuery(this).prepend(jQuery(this).closest('li').find('.wpdf_file_name').html());

See demo below:

jQuery(".row_downloadbutton>a").each(function() {
  jQuery(this).prepend(jQuery(this).closest('li').find('.wpdf_file_name').html());
});
jQuery(".row_filename").remove();

Brochure A

Download

Brochure B

Download

    ...

    ...


text:
Q: Use trait options or traitui.editor factory options? When options for a Trait are available both in the traits definition and in the traitsui.DefaultEditor for this trait, what is the recommendation for which one to use and why?
E.g. the File trait has the option for a filter, which can also be defined in the traitsui.FileEditor()


text:
Q: asp MVC - Add a model representing user to a Partial displayed via layout my layout page includes a header partial which changes depending on the user / company that is logged in, so it makes sense to make teh partial stronglyTyped.
I know how to call a partial and add in the model, but at what point (and where) do I add the header model? Do I need to add it on each page that uses the layout (which seems excessive), or is there some way I can add the header model without writing code on each page to add it to the viewbag and pass it through? (I suspect that if it is viable, it will have to pass through a controller somewhere. In which case, can I use an existing controller, or do I need a special 'partial header' controller?)

A: Implement an action that will

*

*Create the model

*Return a ViewResult rendering your Partial with the given model

Then do an Html.RenderAction("ActionName", "ControllerName") for that action in your Layout.


text:
Q: Concerns about Guidelines for Creating Entity Relationship Models I am currently enrolled in the online Oracle Academy Database Design Course, which briefly talks about the concept of nontransferable relationships. I understand the concept behind them, but the course's vague details left me with a few of questions.

*

*Can nontransferable relationships exist between entities which are connected with a 1:1 or M:M relationship? All of the example provided by Oracle depicted 1:M relationships.

*Can the diamond used to represent the nontransferable relationship be drawn on either end of the relationship, whether they are optional or mandatory? I believe they can only appear on the mandatory end of the relationship, but I want to be sure.

*Similarly, can the diamond used to represent the nontransferable relationship potentially appear on BOTH ends of the relationship?
The following are a couple of examples provided by the Oracle Academy:

A: *

*I'm not sure but if you think about certain 1:1 relationships, they are nontransferable. For example, one person can only have one passport. A passport cannot be transferred between people.  I'm not sure about many to many but I can think of an example - you can have a group of people who write series of books.  This would be many to many and authorship cannot be transferred to other people. That probably isn't a great example.

*The diamond can be drawn on either side but typically it appears on the mandatory end, so I would always put it on that end.

*I have never seen the diamond on both ends.


text:
Q: pip for python3.5 broken Ubuntu 16.10 I'm experiencing a strange issue with the pip(3).
I'm receiving this error when I performed any pip command like pip --version(or pip3 --version):
Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 7, in <module>
    from pip import main
  File "/usr/local/lib/python3.5/dist-packages/pip/__init__.py", line 28, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "/usr/local/lib/python3.5/dist-packages/pip/vcs/subversion.py", line 9, in <module>
    from pip.index import Link
  File "/usr/local/lib/python3.5/dist-packages/pip/index.py", line 31, in <module>
    from pip.wheel import Wheel, wheel_ext
  File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 6, in <module>
    import compileall
  File "/usr/lib/python3.5/compileall.py", line 20, in <module>
    from concurrent.futures import ProcessPoolExecutor
  File "/usr/local/lib/python3.5/dist-packages/concurrent/futures/__init__.py", line 8, in <module>
    from concurrent.futures._base import (FIRST_COMPLETED,
  File "/usr/local/lib/python3.5/dist-packages/concurrent/futures/_base.py", line 357
    raise type(self._exception), self._exception, self._traceback
                               ^
SyntaxError: invalid syntax

Python version
Python 3.5.2+ (default, Sep 22 2016, 12:18:14)
[GCC 6.2.0 20160927] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

~/ pip

pip          pip2         pip2.7       pip3         pip-compile  pip-sync

I've pip2.7 installed and is working well. I'm under Ubuntu 16.10 and I don't understand what is the issue.
Thanks

A: I had the same problem. Replace the the line
raise type(self._exception), self._exception, self._traceback

with
raise Exception(self._exception).with_traceback(self._traceback)

in /usr/local/lib/python3.5/dist-packages/concurrent/futures/_base.py

A: The futures library back-ports some Python 3 features so that they can be used in Python 2.
Unless you absolutely must have it installed, you can just:
pip uninstall futures

to remove it from your Python 3 virtual environment.


text:
Q: How to read Chrome/Firefox Pop up actions Leave/Stay when we the leave the page? When ever u made some change to page and try to leave chrome/firefox throws a alert.  Data you entered may not be saved with (Leave or Stay) buttons.
How i can do certain action when user clicks leaves or stay.

To which event i need to listen to to make actions when we click leave or stay?
TIA

A: There is no window close event.You can use onbeforeunload to prevent asking for simple confirmation etc.
That is what is done internally by website developers on their page. But you can't read that answer from an user script. It is simply the website developers implementation.You can't read user's response given to website developers confirm question by user from an application.
Those popups are implemented by the corresponding websites not browser.
Solution
Modern browsers now consider displaying a custom message to be a security hazard and it is removed therefore. Browsers now only display generic messages. So we can simply do this:-
window.onbeforeunload = function() {
    return false;
};
window.onbeforeunload = null; // this will not show any popup.

So just remove everything fron onbeforeunload and return false and make it null. This will solve your problem.
Note: You can't show custom message or do anything significant using onbeforeunload. That is the answer to your question originally asked.


text:
Q: Magnitude of reciprocal-lattice vector I'm reading "A Journey into Reciprocal Space" by Glazer where the metric tensor in reciprocal space is defined as:

$$M^*=\begin{bmatrix} \textbf{a}^*\cdot\textbf{a}^* &
 \textbf{a}^*\cdot\textbf{b}^* & \textbf{a}^*\cdot\textbf{c}^* \\
 \textbf{b}^*\cdot\textbf{a}^* & \textbf{b}^*\cdot\textbf{b}^* &
 \textbf{b}^*\cdot\textbf{c}^* \\ \textbf{c}^*\cdot\textbf{a}^* &
 \textbf{c}^*\cdot\textbf{b}^* & \textbf{c}^*\cdot\textbf{c}^*
 \end{bmatrix} = \begin{bmatrix} (a^*)^2 & a^*b^*\cos\gamma^* &
 a^*c^*\cos\beta^* \\ b^*a^*\cos\gamma^* & (b^*)^2 & b^*c^*\cos\alpha^*
 \\ c^*a^*\cos\beta^* & c^*b^*\cos\alpha^* & (c^*)^2 \end{bmatrix}$$

In the worked example for a monoclinic crystal with $a = 0.6 \text{ nm}$, $b = 0.7\text{ nm}$, $c = 0.8\text{ nm}$ and $β = 110^{\circ}$ the magnitude of the reciprocal-lattice vector of the length denoted by the direction [31-2] is calculated as:

$$\begin{align*} a^*&=2\pi\frac{1}{a\sin\beta}=11.14\text{ nm}^{-1} \\
 b^*&=2\pi\frac{1}{b}=8.98\text{ nm}^{-1} \\
 c^*&=2\pi\frac{1}{c\sin\beta}=8.36\text{ nm}^{-1} \\ \beta^*&=
 180^{\circ} - \beta = 70^{\circ} \end{align*}$$
Then
$$\left((2\pi)^2\begin{bmatrix} 3 & 1 & \overline{2}
\end{bmatrix}\begin{bmatrix} 3.14 & 0 & 0.80 \\ 0 & 2.04 & 0 \\ 0.80 & 0 & 1.77
\end{bmatrix}\begin{bmatrix} 3 \\ 1 \\ \overline{2}
\end{bmatrix}\right)^{1/2} = 33.1\text{ nm}^{-1} $$

It's not clear to me how the numerical values were obtained in this matrix; for example, I would say $(a^*)^2=124.19\text{ nm}^{-1}$ rather than $3.14\text{ nm}^{-1}$; is it not?

A: You have in front the factor term $(2\pi)^2$ , so you must divide all your matrix terms by $({2\pi})^2$,  e.g. for $(a^*)^2, (b^*)^2, (c^*)^2$ by $({2\pi})^2$, just mathematics.


text:
Q: A specific case of the $p$-center problem Given a fixed positive integer $m$, let $\cal{S}$ be the subset from $\mathbb{R}^m$ defined as $\cal{S} = \{u \in \mathbb{R}^m \mid \forall i \in \{1, \dots, m\}, u(i) > 0$ and $\sum_{i=1}^m{u(i) = 1}\}$. $\cal{S}$ is together with a metric $d$ which corresponds to the Manhattan distance. Let $S$ be a given finite subset of $\cal{S}$ and $u_* \in S$. Let ${\cal S}(u_*) \subseteq {\cal S}$ be the set of all vectors from ${\cal S}$ which are closer to $u_*$ than to any other vector from $S \setminus \{u_*\}$.
Given a positive integer $p$, I would like to be able to compute a finite set $S' \subseteq {\cal S}(u_*)$ of size $p$, such that $S'$ minimizes the function $\max_{v \in {\cal S}(u_*)}{\min_{w \in S'}}{d(v, w)}$.
Roughly, the idea consists in drawing the "Voronoi diagram" on the space ${\cal S}$ built from the finite set of points $S$. Then, one focuses on the "cell" from this diagram associated with the point $u_* \in S$. One wants to solve the $p$-center problem on this cell, i.e., find $p$ points which are "best distributed" inside this cell.
Does anybody know how to solve this problem? Like, whether it is possible to solve the problem using linear programming? Note that the inputs of the problem are $S$, $u_*$ and $p$.
Edit: since the above problem may be out of reach, I'd rather consider the following simpler problem. Let ${\cal S}$ be defined as above and let $p$ be a positive integer, find a set $S' \subseteq {\cal S}$ of size $p$ which minimizes the function $\max_{v \in {\cal S}}{\min_{w \in S'}}{d(v, w)}$. Is there also anyway to encode this problem?


text:
Q: Qt QUdpSocket: readyRead() signal and corresponding slot not working as supposed I have problems to find why my short QUdpSocket example is not working. I plan to use only one UDP socket to read and write to an embedded device at 192.168.2.66 on port 2007. The device will reply always on port 2007 to the sender. I tested the device with an UDP terminal software and works as I said. So, I designed a simple class to embed the functions needed to manage the device:
class QUdp : public QObject
{
    // Q_OBJECT
public:
    explicit QUdp(QObject *parent = 0, const char *szHost = 0, uint16_t wPort = 0);
    ~QUdp();
    bool Open();
    int64_t Write(QByteArray &data);
    int64_t Write(QString strData);
private:
    QString m_strHost;
    uint16_t m_wPort;
    QUdpSocket *OUdp;
private slots:
    void received();
};

I suppose that the problem is in the Open method:
bool QUdp::Open()
{
    QHostAddress OHost;
    connect(OUdp, &QUdpSocket::readyRead, this, &QUdp::received);
    bool zRet = OUdp->bind(QHostAddress::AnyIPv4, m_wPort, QUdpSocket::ShareAddress);
    OHost.setAddress(m_strHost);
    OUdp->connectToHost(OHost, m_wPort, QIODevice::ReadWrite);
    return(zRet);
}
//------------------------------------------------------------------------

I used the Qt 5 syntax for the connect(), m_strHost value is "192.168.2.66" and m_wPort is 2007
my Write method is very simple (the part inside #if 0 was added to see if the socket received any data)
int64_t QUdp::Write(QString strData)
{
    QByteArray data(strData.toStdString().c_str(), strData.length());
    int64_t iCount = OUdp->write(data);
#if 0
    bool zRecved = OUdp->waitForReadyRead(3000);
    int64_t iRecvCount = OUdp->bytesAvailable();
#endif
    return(iCount);
}
//------------------------------------------------------------------------

and this is my test received() method... I wrote it just to see if the signal-slot works or not:
void QUdp::received()
{
    int64_t iRecvCount = OUdp->bytesAvailable();
}
//------------------------------------------------------------------------

I don't understand what is wrong.. I found some posts saying that is not possible read and write using only one UDP socket in Qt (Qt uses BSD sockets so it should be possible) but my example looks as the proposed solutions so I really don't understand what is not working.

A: You can read and write using just one UDP socket in Qt. I have this running in Qt5 on both windows and Linux, so no worries there :)
To establish Rx direct comms in QUdpSocket you should really use the bind() function, something like this:
// Rx connection: check we are not already bound
if (udpSocket->state() != udpSocket->BoundState)
{
    // Rx not in bound state, attempt to bind
    udpSocket->bind(address, port);
}

Once this has completed you will be able to check that udpSocket->state() == udpSocket->BoundState is true, then you are successfully "bound" to this ip/port. Now your listening can begin if your connection to readready() is correct. I have not used this connection syntax that you are using, so I can't say much about that, but here is the example of how I connect:
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(rxDataEvent()), Qt::QueuedConnection);

Where "this" is the class which contains my QUdpSocket and udpSocket is a QUdpSocket pointer. Then rxDataEvent is defined below:
void CIpComms::rxDataEvent(void)
{
    QByteArray rxData;
    QHostAddress sender;
    quint16 senderPort;

    while (udpSocket->hasPendingDatagrams())
    {
        // Resize and zero byte buffer so we can make way for the new data.
        rxData.fill(0, udpSocket->pendingDatagramSize());

        // Read data from the UDP buffer.
        udpSocket->readDatagram(rxData.data(),
                                rxData.size(),
                                &sender,
                                &senderPort);

        // Emit ipDataReceived Signal
        emit ipDataReceived(rxData);
    }
}

Here we continually check for datagrams until there are none pending (bit easier then doing the whole "bytesAvailable thing") and stick the data into a QByteArray and emit it off elsewhere (which you obviously don't have to do!).
That is all you need to do for connection. Then to send is very easy, you simply have to call writeDatagram(), well there are other options but this is by far the easier to use:
if (-1 == udpSocket->writeDatagram(txData, address, port))
{
    // Data write failed, print out warning
    qWarning() << "Unable to write data to " << address.toString() << ":" << port << endl;
    return false;
}

I have pretty much cut and pasted this from my working code (with a few edits to keep it short-n-simple so it should give you a starting point. In summary where I believe you are going wrong is that you have not "bound" to the IP address/port and are therefore NOT listening to it and will not receive any readReady() events.


text:
Q: SOAP web service not working for EJB calls I am trying to create a SOAP based web service, which will call stateless EJB in other project. My configuration is Server: WAS 8.5,IDE: RAD 8.5,Java 1.6, EJB 3.1, and SOAP 1.1. When I write a simple addition method it properly create Web Service, WSDL and i can access the Web Service. But When i add another method which calls EJB it wont allows me to create service and WSDL, it throws below error popup :
Errors occurred during wsgen.
error: compilation failed, errors should have been reported
warning: The apt tool and its associated API are planned to be
removed in the next major JDK release.  These features have been
superseded by javac and the standardized annotation processing API,
javax.annotation.processing and javax.lang.model.  Users are
recommended to migrate to the annotation processing features of
javac; see the javac man page for more information.
Note:   ap round: 1
Problem encountered during annotation processing;
see stacktrace below for more information.
java.lang.NullPointerException
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceVisitor.isLegalType(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceVisitor.isLegalMethod(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceVisitor.methodsAreLegal(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceVisitor.isLegalImplementation(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceVisitor.shouldProcessWebService(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceVisitor.visitClassDeclaration(Unknown Source)
    at com.sun.tools.apt.mirror.declaration.ClassDeclarationImpl.accept(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceAP.buildModel(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.processor.modeler.annotation.WebServiceAP.process(Unknown Source)
    at com.sun.mirror.apt.AnnotationProcessors$CompositeAnnotationProcessor.process(Unknown Source)
    at com.sun.tools.apt.comp.Apt.main(Unknown Source)
    at com.sun.tools.apt.main.AptJavaCompiler.compile(Unknown Source)
    at com.sun.tools.apt.main.Main.compile(Unknown Source)
    at com.sun.tools.apt.main.Main.compile(Unknown Source)
    at com.sun.tools.apt.Main.processing(Unknown Source)
    at com.sun.tools.apt.Main.process(Unknown Source)
    at com.sun.tools.apt.Main.process(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.wscompile.WsgenTool.buildModel(Unknown Source)
    at com.ibm.jtc.jax.tools.ws.wscompile.WsgenTool.run(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.ibm.ast.ws.jaxws.emitter.jws22.v85.command.AbstractWsGenCommand.execute(Unknown Source)
    at com.ibm.ast.ws.jaxws.emitter.command.WsGenCommand.execute(Unknown Source)
    ....

This is my code which works fine
public class Operations {
    public int addition(int x, int y){
        return x+y;
    }
    public String Greetings(String name){
        return "happy birthday"+name;
    }
}

when i add
@EJB
    private transient StatusEJBBeanLocal statusEJBBeanLocal;
    public Product StatusFromProductId(int ProdutoID) {
        Product produto = null;
        produto = this.statusEJBBeanLocal.StatusFromProductId(ProdutoID);
        return produto;
    }

It shows error. Please help me out here with some tutorial link or tell me whats wrong with my code, how to call EJB from Web services. Thanks in advance.


text:
Q: Automorphisms of a modular tensor category I would like to ask for references on automorphisms of a modular tensor category, that do not change the objects. Some special cases, such as automorphisms of a quantum double, are also helpful.

A: Not much known in general, but in this paper https://arxiv.org/abs/1312.7466, Davydov gives a description of them for Drinfeld Centers of Vec(G).

A: For most quantum group categories all braided autoequivalences are classified by Cain Edie-Michell in this paper.  The kind you're interested in, which is called "gauge auto-equivalences" there, almost never exist.  One example where it does happen is Cor. 3.2 for the adjoint subcategory of sl_3 at level 3, but I'm not sure if that one is braided.
Many of the arguments there build on an idea from my paper with Grossman Thm 5.5 which is that if you have a planar algebraic description of your tensor category then gauge autoequivalences in particular give you an automorphism of the planar algebra, and you can often see that no such automorphism exists.


text:
Q: Spinner is not working in Fragment My application crashes when I am using Spinner in Fragment.
public class TestRideFragment extends Fragment implements AdapterView.OnItemSelectedListener {

    String[] country = { "India", "USA", "China", "Japan", "Other",  };

    public TestRideFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        //return inflater.inflate(R.layout.fragment_test_ride, container, false);
        View v = inflater.inflate(R.layout.fragment_test_ride, container, false);

        Spinner spin = (Spinner) getView().findViewById(R.id.spinner1);
        spin.setOnItemSelectedListener(this);

        //Creating the ArrayAdapter instance having the country list
        ArrayAdapter aa = new ArrayAdapter(getContext(),android.R.layout.simple_spinner_item,country);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //Setting the ArrayAdapter data on the Spinner
        spin.setAdapter(aa);

        return v;
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) { }
 }

Could anyone help me spot the issues with my code, please?

A: You are trying to get view before it's being created, so that's why it is returning null.
So, you can do like,
Spinner spin = (Spinner) v.findViewById(R.id.spinner1);

or, you can move your code to onViewCreated where view will be created,
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    return inflater.inflate(R.layout.fragment_test_ride, container, false);

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Spinner spin = (Spinner) view.findViewById(R.id.spinner1);
    spin.setOnItemSelectedListener(this);

    //Creating the ArrayAdapter instance having the country list
    ArrayAdapter aa = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, country);
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    //Setting the ArrayAdapter data on the Spinner
    spin.setAdapter(aa);
}

A: Try using v.findViewById(R.id.spinner1) also make sure that spinner1 is declared in the xml layout fragment_test_ride
Try adding array in strings.xml
<array name="countries">
    <item>India</item>
    <item>USA</item>
    <item>China</item>
    <item>Japan</item>
    <item>Other</item>
</array>

and in your xml
<android.support.v7.widget.AppCompatSpinner
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:entries="@array/countries"
   android:id="@+id/spinner1" />

Remove the ArrayAdapter but do not this one will make your options static based on whats in the array declare on the string xml

A: Change your code:
Spinner spin = (Spinner) getView().findViewById(R.id.spinner1);

Into this:
Spinner spin = (Spinner) v.findViewById(R.id.spinner1);

A: Maybe the problem is in your adapter which should be;
   ArrayAdapter<CharSequence> aa= ArrayAdapter.createFromResource(this,
    country, android.R.layout.simple_spinner_item);

and you have;
   ArrayAdapter<CharSequence> aa= ArrayAdapter.createFromResource(this,
     android.R.layout.simple_spinner_item, country);


text:
Q: Wordpress - Get User's image ID from Pods field I am currently working with the Pods plugin.
I extended the user pod and I added a corporate image field.
On the administration everything is fine, I can change the image of each user.

AND :

My problem is that I can not display this image on a front office page..
If i do this : var_dump($pod->field('image_societe'));
It return false, while the field name is correct, and for plain text fields, it works.
But i can do this :
var_dump($pod->fields('image_societe'));

This will return me full of information, but I do not have access to the id of the image, it is not present in the information.
I would like to finally be able to do this:
the_attachment_link( 11923 );

Where 11923 is the image's ID.
To be dynamic according to the user, the documentation says that it must be done like this:
the_attachment_link($pod->field('image_societe.ID'));

But as pods return me false, it does not work.
Does someone have an idea ?
Thank you !

A: Usually you can get the image url by querying $pod->field('image_societe.guid'). E.g. :
$items = pods('your_pod', array("limit" => -1));
while($items->fetch()) {
    echo $items->field('image_societe.guid');
}

If $pod->field('image_societe'); doesn't return anything, then something might be wrong with your pod query, or caching kicking in. So more code would be needed to review this.


text:
Q: Web request not repeating after failure, try/catch not working I am trying to send a web request to a Snom PA1 bell.  The bell rings periodically throughout the day, but occasionally times out trying to contact the bell.  That would be fine, but after this happens a couple times, the web request stops sending altogether.  the sub still runs, but no bells.  Also, while debugging, the webrequest throws a webexception that is not handled by the catch, even though it is contained within the try/catch.
Does anyone know why the web request would stop working after a failure?
Private Sub ringIPBell(ByVal params() As Object, Optional ByVal secondattempt As Boolean = False)

    Dim IPaddress As String = params(0)
    Dim ringSeconds As Double = params(1)
    Dim wr As Net.HttpWebRequest

    If ringSeconds = 2 Then
        wr = Net.HttpWebRequest.Create("http://" & IPaddress & "/line_login.htm?l=2")
    Else
        wr = Net.HttpWebRequest.Create("http://" & IPaddress & "/line_login.htm?l=1")
    End If
    wr.Method = "post"
    wr.CachePolicy = New System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore) 'added Oct2010
    wr.Credentials = New Net.NetworkCredential("correctName", "correctPassword")

    Dim postdata As String = "PLAY_RINGER:1=Play Ringer"

    wr.ContentLength = postdata.Length + 2
    Dim requestStream As IO.Stream, strmwrit As IO.StreamWriter
    Try

        requestStream = wr.GetRequestStream()
        strmwrit = New IO.StreamWriter(requestStream)
        strmwrit.WriteLine(postdata)
        strmwrit.Close()
        Dim responsestream As New IO.StreamReader(wr.GetResponse.GetResponseStream)

        Catch ex As System.Net.WebException
        If Not secondattempt Then
            ringIPBell(params, True)
        End If
        Dim testvar As String = ex.ToString
    Catch ex As Exception
        Beep()
    End Try

Also, I previously had the following code ringing the bell, but it would only work for one of the two bells, Even though as far as i can tell their settings were identical.
requestStream = wr.GetRequestStream()
strmwrit = New IO.StreamWriter(requestStream)
strmwrit.WriteLine(postdata)
strmwrit.Close()
requestStream.Close()

As suggested I broke out the responestream line as such:
requestStream = wr.GetRequestStream()
            strmwrit = New IO.StreamWriter(requestStream)
            strmwrit.WriteLine(postdata)
            strmwrit.Close()

it breaks on "requestStream = wr.GetRequestStream()"
with the error:
"A first chance exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The operation has timed out"


text:
Q: Empty Expression and Provider when using Moq and DBSet I got stuck at a really weird problem for days now and can't find a solution. I'm mocking a DatabaseContext and some DBSet<T> entities. Creating the moq works fine and looks good.
When .Any() is called on a special DBSet, it crashes with NullReferenceException. I took a closer look and found out, that Expression and Provider of my mocked DBSet are null again. But I have no idea why.
Function, which creates the DB-Set:
private DbSet<T> GetQueryableMockDbSet<T>() where T : class
{
    var list = mockListCollection.Single(o => o.GetType().GetGenericArguments()[0] == typeof (T))
        .ToList()
        .ConvertAll(o => (T) o);

    var queryable = list.AsQueryable();

    var dbSet = new Mock<DbSet<T>>();
    dbSet.As<IQueryable<T>>()
        .Setup(m => m.Provider)
        .Returns(new TestDbAsyncQueryProvider<T>(queryable.Provider));

    //dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
    dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
    dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
    dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
    dbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>(list.Add);

    dbSet.Object.AddRange(list);

    return dbSet.Object;
}

It is called here for every table of my DatabaseContext:
private void InitMockMethods<T>() where T : class, new()
{
    this.DataBaseContextMock.Setup(m => m.Set<T>()).Returns(this.GetQueryableMockDbSet<T>());
    this.DataBaseContextMock.Setup(m => m.Set<T>().Local).Returns(new ObservableCollection<T>(this.GetQueryableMockDbSet<T>()));

    this.DataBaseContextMock.Setup(m => m.Set<T>().Create()).Returns(new T());

    // first get the parameter name out of database context by generic type argument (e. g. DbSet<TblProject>  --> get name by TblProject)
    // because type and typename are not equal.
    // TblProject --> Name is TblProjects
    var paramName = typeof (IDatabaseContext).GetProperties().Single(o => o.CanWrite && o.PropertyType.GetGenericArguments()[0] == typeof(T)).Name;

    // build lamda expression for moq setup
    var parameter = Expression.Parameter(typeof(IDatabaseContext));
    var body = Expression.PropertyOrField(parameter, paramName);
    var lambdaExpression = Expression.Lambda<Func<IDatabaseContext, object>>(body, parameter);

    // setup moq
    this.DataBaseContextMock.Setup(lambdaExpression).Returns((DbSet<T>)this.GetQueryableMockDbSet<T>());
}

After that, all objects look fine. But when I call DatabaseContext.Set<TblVendor>().Any(), it crashes because Provider and Expression are null.
Is anyone out there, who's any idea, what could be wrong?!
Edit:
Here's the test function:
[Test]
    [TestCase(11,31)]
    public void TestFilterExtension(int expGl1, int expGl2)
    {
        var userMock = new Mock<AspNetUser>();
        userMock.Setup(x => x.EnableFilterByUserAuthorization).Returns(true);
        userMock.Setup(x => x.Tablename).Returns("TblVendor");
        userMock.Setup(x => x.Columnname).Returns("gl");
        userMock.Setup(x => x.Value).Returns(expGl1.ToString);

        var gl = new Mock<TblVendor>();
        gl.Setup(n => n.Id).Returns(Guid.NewGuid);
        gl.Setup(x => x.GL).Returns(expGl1);

        var gl2 = new Mock<TblVendor>();
        gl2.Setup(n => n.Id).Returns(Guid.NewGuid);
        gl2.Setup(x => x.GL).Returns(expGl2);

        var manager = new VendorManager(base.Manager, MockProvider.Instance.DataBaseContextMock.Object,
            userMock.Object, MockProvider.Instance.EntityHelperMock.Object);

        //MockProvider.Instance.ClearMockList<TblVendor>();

        //manager.AddOrUpdate(gl.Object);
        //manager.AddOrUpdate(gl2.Object);

        var test = MockProvider.Instance.DataBaseContextMock.Object.Set<TblVendor>();
        var b = test.Any(); // <----- NullReferenceException because of missing Provider and or Expression
        //var b = manager.EntityCollection;
        //var data = manager.EntityCollection.ToList();

    }

A: I see you have used the async provider way, so i would tell you to try to implement the getenumerator async too, as explained in the msdn guide how to mock ef dbcontext.
Once it is done, avoid to moq queries because it is not needed. Your mock already will work with linq queries as expected! Also, if there is another function call as Include() you must mock it to return the itrm you want( most of the times will be the original object mock, the original list)


text:
Q: Why my ESP32-CAM won't power up with 5 volts? I'm new into electronics and I decided to power up my ESP32-CAM with a 9V battery instead FTDI programmer (I measured it, it gives 5V to ESP32-CAM). I thought if I reduce voltage to 5V with mini voltage regulator it will work but it didn't instead it turns on red light and makes high pitched noise. I tried get logs for debugging but since I'm a programmer and not an electrical engineer, I failed (I seriously tried connect TX and RX to FTDI, GND and VCC to battery). What did I do wrong? (See my diagram below.)

A: *

*Does it still work in the previous configuration using the FTDI programmer? Do that to verify that it hasn't been damaged.
The ESP32-CAM has two VCC pins, 3.3 and 5.0; ensure that you've connected to the correct pin. Supplying 5 V on the 3.3 V pin could irreparably damage it.

Source

*Rule out the voltage regulator as a problem, and supply 5 V directly using a bench supply to verify that the fault isn't with the regulator.

*Ensure the battery you're using is good. Also, 9 V batteries are not generally used for higher-current applications. The datasheet for the ESP32-CAM does not give clear power requirements, but does list 310 mA at 5 V. If the regulator was 100% efficient (it won't be), that would be ~172 mA from the 9 V battery, which isn't necessarily a problem unless the battery is moderately discharged.


text:
Q: Angular Error: error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable' I'm fairly new to Angular and was hoping someone could help with the following error I am getting.

error TS2322: Type 'Observable<{}>' is not assignable to type
'Observable<ITimesheetComments[]>'. Type '{}' is missing the following
properties from type 'ITimesheetComments[]': length, pop, push,
concat, and 28 more.

The TimesheetCommentsService.getList() function calls the HttpService.getList() function which should return ITimesheetComments[].  Presumably I am missing a cast of some sort somewhere?
timesheet-comments.services.ts
import { ITimesheetComments } from './../models/timesheet-comments.model';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { ResourceParams } from '../../../core/http/models/resource-params.model';
import { HttpService } from '../../../core/http/http.service';

@Injectable()
export class TimesheetCommentsService {

    constructor(private http: HttpService) { }

    getList(transactionRelatedNum : number) : Observable<ITimesheetComments[]> {
        let resourceParams : ResourceParams = new ResourceParams();
        resourceParams.orderBy = "date_created desc";
        let endpoint: string = `ServiceReceipts/${transactionRelatedNum}/Comments`;
        return this.http.getList<ITimesheetComments[]>(endpoint, resourceParams);
    }
}

http.service.ts
getList<T> (endpoint: string, resourceParams: ResourceParams = new ResourceParams(),  headers ?: any, useOnlyEndpoint: boolean = false)
{
    let url = `${(useOnlyEndpoint) ? '' : `${this.env.BASE_URL}/${this.URL_PATH}/`}${endpoint}${this.buildParams(resourceParams.toExtraParams())}`
    return from(this.appAuth.authenticateToken(this.token).then(() => this.httpGet(url, headers)))
        .pipe(map((response : HTTPResponse) => this.parseData<ITimesheetComments[]>(response)),
            catchError(error => this.handleError(error, 'Get')));
}


text:
Q: Getting objects from a rectangular area with fabric.js and draw the area to a canvas How can i get fabric.js objects from a specific rectangular area (same behavior as the selection box but manually) then draw the "selected" pixels area of the objects onto a standard canvas?
Note: Getting the pixels data directly is impossible in my case because the canvas is used as a viewport and objects can be out of the viewport (ie: panning).

A: Solved it by looking at the function _collectObjects and extend fabric.js with a function drawObjsTo which gather the objects from a rectangle and render them on a canvas context passed as argument, the solution is a bit dirty but it can solve another problem i had with a simple getImageData on the fabric.js canvas, the resulting data included the selection box, thus the function can also be used to get the pixels data of the objects only.
fabric.Canvas.prototype.drawObjsTo = function (ctx, x1, y1, x2, y2) {
    var currentObject,
        selectionX1Y1 = new fabric.Point(Math.min(x1, x2), Math.min(y1, y2)),
        selectionX2Y2 = new fabric.Point(Math.max(x1, x2), Math.max(y1, y2));

    for (var i = this._objects.length; i--; ) {
        currentObject = this._objects[i];

        if (!currentObject || !currentObject.visible) {
            continue;
        }

        if (currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2) ||
            currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2) ||
            currentObject.containsPoint(selectionX1Y1) ||
            currentObject.containsPoint(selectionX2Y2)
        ) {
            currentObject.render(ctx);
        }
    }
};

Maybe there should be a way to do that in fabric.js natively.


text:
Q: How to set buttons property IsEnabled based if listbox has content in it? I am trying to make button with property IsEnabled=true only is listbox has one item. If listbox has zero items than button property isEbabled has to be 'false'. I'd like t find what will be the best approach to achieve it. I am ading listboxitems dynamically. Any ideas are highly appreciated!
<ListBox x:Name="ListBox" SelectionMode="Multiple" Height="100" />
<Button x:Name="btnNext" Style="{StaticResource AVV_ButtonStyle}" Content="NextButton" IsEnabled="False" />

A: In WPF:
<ListBox x:Name="ListBox" SelectionMode="Multiple" Height="100" />
<Button x:Name="btnNext" Style="{StaticResource AVV_ButtonStyle}" Content="NextButton" IsEnabled="{Binding ElementName=ListBox,Path=HasItems" />

Silverlight does not support HasItems on the ItemsControl so you would need to move this binding to a boolean property on your DataContext, this would return something like:
return list.Count > 0

I would subscribe to the CollectionChanged event on the collection your List is bound to then raise a PropertyChanged event against the boolean property your IsEnabled property is bound to to force the binding to re-read its source.
If you have bound your button to a command you can do this via the CanExecute property on the command, although the Commands implementation in Silverlight differs from WPF.

A: You could use a command for the button. Then you can specify the CanExecute method for the command. And this will make to button enabled/disable. Then all you have to do is re-check the CanExecute value every time your listBox's source changes. With code similar to:
        (this as INotifyPropertyChanged).PropertyChanged += (s, e) =>
        {
            (YourCommand as DelegateCommand).RaiseCanExecuteChanged();
        };


text:
Q: How do i append new data into an existing cell array? Assuming i have a 1x4 cell array, and i also have a while loop within which i call the function that produces a new result which is of the same size as my original array.
How do i append the new result into the existing one such that i still have a 1x4 array with the new results appended to the existing cells.
See an example code below:
% image
SegI = [2 2 2 0 0
        2 2 2 0 0
        1 1 2 0 0
        1 1 1 1 0
        1 1 1 1 1];

figure, imshow(SegI, [], 'InitialMagnification','fit')
grid on;

% face vectors obtained from each internal node in the image; such that %edge directions of 1|2 are denoted as 'm', and 0|2 as 'n', and others as NaN
% i made the 'b' up just for the purpose of detecting the output easily

allfaces = {NaN,NaN,NaN,NaN; NaN,NaN,NaN,NaN; 'm',NaN,'m',NaN; NaN,NaN,NaN,NaN; NaN,NaN,'n','n'; NaN,'n',NaN,'n'; NaN,'m',NaN,NaN; NaN,NaN,NaN,'m'; NaN,NaN,NaN,NaN; NaN,'m','b',NaN; 'm',NaN,NaN,'n';  NaN,NaN,NaN,NaN; NaN,NaN,NaN,NaN; NaN,NaN,NaN,NaN; NaN,NaN,NaN,NaN; NaN,NaN,NaN,NaN};

% find point vertices... which are nodes that contain pixel edges of both 1|2 and 0|2
Pvertex = find( any(strcmp('m', allfaces),2) & any(strcmp('n', allfaces),2) );

% create storage cell array as well as initialize Pvertex to inodej
myArray = cell(numel(Pvertex), 4);
inodej  = Pvertex;
cp = [3,3];     %coordinates of Pvertex

for k = 1: numel(Pvertex)

    % find next node from Pvertex
     [myArray, allfaces, inodej, ynode, xnode, dist_node] = Obtain_nodes(k, cp, inodej, myArray, allfaces);

    while dist_node < sqrt(2)
        % find nodes until exit loop
       [myArray, allfaces, inodej, ynode, xnode, dist_node] = Obtain_nodes(k, cp, inodej, myArray, allfaces);
    end

end

The function is given as:
function [myArray, allfaces, inodej, ynode, xnode, dist_node] = Obtain_nodes(k, cp, inodej, myArray, allfaces)
% This function computes new nodes from previous ones, as well as
% store each results in the storage cell "myArray"

if ( find( strcmp('m', allfaces(inodej(k),:)) ) == 1 ) == true
    % Find the node at the northern end of the face after inodej
    inodej(k,:) =  inodej(k,:) - 1;

    % extract the n, s, e, w faces from allfaces
    a = allfaces(inodej(k),:);

    % store the new results (exclude the existing result at the southern face)
    a(1) = {NaN};
    myArray(k,:) = a;

    % Obtain a new allfaces that deals the South face for the current node
    allfaces(inodej(k),:) = a;

elseif ( find( strcmp('m', allfaces(inodej(k),:)) ) == 2 ) == true
    % Find the node at the southern end of the face  after inodej
    inodej(k,:) = inodej(k,:) - 4;

    % extract n, s, e, w faces from allfaces
    a = allfaces(inodej(k),:);

    % store the new results (exclude the node at the northern face)
    a(2) = {NaN};
    myArray(k,:) = a;

    % Obtain a new allfaces that deals the North face for the current node
    allfaces(inodej(k),:) = a;

end

%# compute the distance between inodej and Pvertex
% firstly get the coordinates of the inodej
xnode(k) = mod(inodej(k,:) - 1, 4) + 1;
ynode(k) = (inodej(k,:) - xnode(k))/4 + 1;

% Then find the distance
dist_node(k,:) = sqrt( (cp(1) - ynode(k)).^2 + (cp(2) - xnode(k)).^2 );

end

See the figure below for some explanations.
enter image description here
The first function call in the for loop returns:
inodej = 10, and myArray = {NaN, 'm', 'b', NaN}
The function call within the while loop returns:
inodej = 6,  which draws a result from 6th row of allfaces to give:
myArray = {NaN, NaN, NaN, 'n'}
However, i do not get to see my initial (1st) result after the while loop exits because the new(2nd) result updates the cell array. Hence, the issue for me is how to get any new results stored and updated with the previous as the while loop is executed.
I would expect my final output to be something in this form:
[{NaN, NaN}] [{'m', NaN}] [{'b', NaN}] [{NaN, 'n'}]

Please, also bear in mind that I could for instance increase the search distance (dist_node) in which case i wouldn't know beforehand (except by visual inspection) how many new results i could get. Thus, the code will have to be able to append as many new results as obtainable.
Please, i need any help/suggestions/advice to get through this. Thank you in advance.

A: myArray1 = {NaN, 'm', 'b', NaN};
myArray2 = {NaN, NaN, NaN, 'n'};
result = cellfun(@(x,y) {x y}, myArray1, myArray2, 'UniformOutput', false)'

x: Each element of myArray1
y: Each element of myArray2
UniformOutput = false ensures the outputs are cells.
The prime in the end converts a row vector to column vector.
Please read the cellfun documentation of MATLAB


text:
Q: How to add a string at the end of a list with python? Hi guys I'm new with python and i would like to add at the n-th term of a list of tuples a new string suppose the following:
_list = [('string0', 'string1'),.... ,('stringN', 'stringN-1')]

I would like to add another string like this:
_list = [('string0', 'string1'),.... ,('stringN', 'stringN-1'),'NEW_STRING']

edited:
I tried the following with the append method:
_list.append('NEW_STRING')

print "this is the updated list",_list

Any idea of how to incorporate a new string at the end of a list of n tuples?.

A: list.append works in-place changing your object (which you shouldn't call list).
list.append('NEW_STRING')
print list

A: Try the code below
.append() should work.
list = [('string0', 'string1'),('stringN', 'stringN-1')]
list.append("hello")
print list

A: >>> my_list = ['a','b']
>>> print "hello", my_list.append('c')
hello None
>>> my_list
['a', 'b', 'c']

you code will work, the string will be appended, but as append returns None, so it will print None
so to avoid printing None, put append in next line.
Note: using list as variable name is bad practice, as list is inbuilt function in python


text:
Q: How to make a upload image functionality in Angular 6? I m trying to create a upload image page. However I want to it implementend in a way that I want the uploaded file to be saved in the directory of assest in my angular project folder. In that way I can store only the url of the image in my DB. SO I want to save this file without using a backend. I dont want to save the files in my back end. Is this possible or is there another way to upload files without using a back end?

A: You will not be able to save the file in a folder without your server running.
Read

*

*how to upload image in node js

*Upload Files Or Images To Server Using Node.js

*File uploads using Node.js
And visit

*

*Imgur

*Uploapfiles.io

*files.fm
With these services you can save files without back-end


text:
Q: Mongoose not retrieving the same data as mongo console client So, I have a Mongo database with a collection where the documents have a structure similar to this:
{
  "name": "sampleName",
  "subdocument": [
      {
        "name": "subDocName",
        "subsubdocument": [...]
      }
  ]
}

When running mongoose it returns the subsubdocument array empty for all the documents even if they have data. If I run a mongo client on a console I can retrieve the information with no problem at all.
But it gets weirder: if I run the following on my nodejs endpoint it returns an empty array, suggesting there are no empty subsubdocument arrays in any of my documents (which I can confirm from a direct access to the database is true).
MyCollection.find({'subdocument.subsubdocument': {$eq: []}},function(err, result) {
  console.log(result);
});

Although if I run the code bellow all my subsubdocument arrays are printed as [ ].
MyCollection.find(function(err, result) {
  console.log(result);
});

I have even used a GUI (mongobooster) to check if I was not going crazy.
I have no clue of what is going on here and no idea how to solve this so please any ideas are welcome.
PS: I am using version 3.2 of MongoDB and mongoose v4.4.12.

A: So, it appears it was a rather stupid error that I wasn't thinking of because I assumed the standard behavior would be different. It was just a confusion with some git versions that caused an error on the mongoose schema.
I just thought if it was that it should show an error and not just hide the information, rather strange indeed...
But thanks to Inder R Singh to pointing me out in the right direction.


text:
Q: Subtleties in the calculation of limits associated with adherent points Just want to check if I understand formal definitions of limits and continuity correctly (i.e. everything that I wrote is correct)
Suppose we have a function $f: (0, +\infty) \rightarrow R$ , $\;$ $f(x) = \sqrt{\frac{1}{x}}$
I compute three limits at  $0$. (This is about my understanding of two-sided and one-sided limits)
I'm learning from Tao book. There he uses an improved limit definition:
$$\lim_{x \to x_0, \; x \in E} f(x)$$ where $E$ can be any subset of $X$ (not only the usual $X -x_0$), $x_0$ should be an adherent of $E$ for that matter, the same remains as in the usual definition of a limit)
Before I start I'd like to make a notice of how I work with limits

*

*Fix some subset E of original domain X

*Fix some point in which i would like to calculate a limit

*Check whether or not this point is an adherent point of E.

*If it's not an adherent point then the limit is not defined. (I.e. there is no such notion - we can't say that this means that function diverges in this point for example.)

*If it is an adherent point then we can talk about its convergence or divergence (it will be one and exactly one of those)

Now we compute two sided-limit. I claim that it equals to $+ \infty$
$$\lim_{x \to 0, \; x \in X} \; \sqrt{\frac{1}{x}} = + \infty$$ For that let's take an arbitrary $\varepsilon > 0$ and $${\delta = \frac {1}{\sqrt{\varepsilon ^ 2}}}$$ this means that $$\sqrt {\frac{1}{\delta}} \geq \varepsilon$$
and any $x$ from $(0, +\infty)$, such that $|x| \leq \delta$. (Unwrapping formal definition here)
Now for that x we have to show that $|f(x)| \geq \varepsilon$
But since $x$ is in $(0, +\infty)$ it is positive, so we have $\frac {1}{x} > \frac {1}{\delta}$ and $|f(x)| = f(x)$ so in the end we have  $$|f(x)| = \sqrt{\frac {1}{x}} > \sqrt{\frac{1}{ \delta}} \geq \varepsilon$$
So, indeed
$$\lim_{x \to 0, \; x \in X} \; \sqrt{\frac{1}{x}} = + \infty$$
Next we take right-sided limit
$$\lim_{x \to 0, \; x \in X  \cap (0, + \infty)} \; \sqrt{\frac{1}{x}} $$
The intersection $X  \cap (0, + \infty) = (0, + \infty)$ is in fact equal to $X$, so this limit is the same as previous one, thus we have $$\lim_{x \to 0, \; x \in X  \cap (0, + \infty)} \; \sqrt{\frac{1}{x}} = +\infty$$
Finally let's take left sided limit:
$$\lim_{x \to 0, \; x \in X  \cap (- \infty, 0)} \; \sqrt{\frac{1}{x}} $$
The intersection here $(0, + \infty)  \cap (- \infty, 0)$ is, in fact, equal to the empty set and no point can be an adherent point of the empty set (because of vacuous implications) So this limit is ill-defined.

If I computed everything right then this is quite interesting because this shows some subtleties in using one-sided limit theorem. (Two sided limit exists while one of one-sided is not defined)

In the same passion it seems to me that the function
$$f(x) =
     \begin{cases}
       \text{0,} &\quad\text{x}\le0\\
       \text{1,} &\quad\text{x}\ge1 \\
     \end{cases}$$ is continuous! (Though it does not pass pen draw test)
(For a function to be continuous means to be continuous in every point of its domain, right?)
Also, is the notion of continuity defined only for a domain of a function? (In the very same way as the notion of limit is defined only for an adherent point of a set) I.e. it makes no sence to ask or say whether my function is continuous or discontinous in, say, $x = 1/2$?)
Let's check for example it's continuity in zero.
For any $\varepsilon$ we take $\delta = 1/2$.
Now for any x from its domain, which also satisfies $|x| < 1/2$ we have $f(x) = 0$ obviously, so that $|f(x)-0| = 0 < \epsilon$.
Once again here right-sided limit is not defined.


text:
Q: Make a div with buttons inline How do you make a Div with 2 buttons become inline?

 Break Length

    <button id="break-decrement">
                    handleClickBreakDecrement
                </button>

 5 minutes or something

    <button id="break-increment">
                    handleClickBreakIncrement
          </button>

The div with the ID="button" must be inline  like this:
   **handleClickBreakDecrement** 5 minutes or something **handleClickBreakIncrement**

Instead of this:
  **handleClickBreakDecrement**
5 minutes or something
**handleClickBreakIncrement**

I tried using display : inline but nothing happened

A: The paragraph element (
...
) between your two buttons is a block-level element, which accounts for the behavior you're witnessing.
To fix, either set display: inline on the paragraph element, or replace it with an inline element like ...:

 Break Length

    <button id="break-decrement">handleClickBreakDecrement</button>
     5 minutes or something
    <button id="break-increment">handleClickBreakIncrement</button>

A: To make the inner buttons and paragraph render on the same line, you can set their CSS property display as inline-block, like the following snippet:

#button > button, p {
  display: inline-block;
}

 Break Length

      <button id="break-decrement">
                handleClickBreakDecrement
            </button>

 5 minutes or something

      <button id="break-increment">
                handleClickBreakIncrement
      </button>

A: Three feasible ways to achieve:

#button {
  display: flex;
}

 Break Length

    <button id="break-decrement">
      handleClickBreakDecrement
    </button>

 5 minutes or something

    <button id="break-increment">
      handleClickBreakIncrement
    </button>

#button button,
#button p {
  display: inline;
}

 Break Length

    <button id="break-decrement">
      handleClickBreakDecrement
    </button>

 5 minutes or something

    <button id="break-increment">
      handleClickBreakIncrement
    </button>

#button {
  overflow: hidden;
}
#button button,
#button p {
  float: left;
}

 Break Length

    <button id="break-decrement">
      handleClickBreakDecrement
    </button>

 5 minutes or something

    <button id="break-increment">
      handleClickBreakIncrement
    </button>


text:
Q: mbed CLI: make.py: error: Could not find executable for ARM I'm trying to compile a program with the mbed CLI using the following command:
mbed compile -m UBLOX_C027 -t ARM

It results in the following error:
make.py: error: Could not find executable for ARM.
Currently set search path: No path set

How can I set the executable?

A: I know I am way too late but still if anyone is facing the same problem.
I solved it in this way in MAC OS.

*

*Download GCC_ARM for MAC OS from here: https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads

*Extract it in some location and set the path using mbed cli:

mbed config -G GCC_ARM_PATH "/Users/amod-mac/Desktop/gcc-arm-none-eabi-7-2017-q4-major/bin"

A: Two ways, either:

*

*Set ARM_PATH in mbed_settings.py in the root folder of your project.

*Or make sure that ARMCC is in your path.

Note that ARM compiler target is for the commercial ARM compiler. If you're using GCC ARM use the GCC_ARM target.


text:
Q: Groups execution order is wrong in Kotlin Spek Here is my test:
object MySpek : Spek({
    val myMock1: MyMock1 = mock()
    val myMock2: MyMock2 = mock()
    val handler = StartModeHandler(myMock1, myMock2)

    val session = mock<Session> {
        on { user }.doReturn(User.builder().withUserId("userId").build())
    }
    describe("item exists for user") {
        beforeGroup {
            reset(digitalPointDao, trackDao)
        }
    whenever(myMock1.loadItem(session.user.userId)).thenReturn(Optional.of(MyItem()))
        whenever(myMock2.loadSomething()).thenReturn(ArrayList())
        context("method onLaunch was called") {
            val response = handler.onLaunch(session)
            it("should return the response for existing user") {
                //some asserts here
            }
            it("should save the item") {
                //some mock verifies here
            }
        }
    }
})

According to Spek documentation, I expect the flow to be the following:

*

*initialize everything before describe

*call beforeGroup

*initalize describe body e.g. my whenever calls for mocks

*run context

*run each it method

But i'm getting the following flow:

*

*initialize everything before describe

*run my describe body e.g. my whenever calls for mocks

*run context

*run beforeGroup

*run each it method

Am I miss something and doing something wrong here?

A: As mentioned in the Spek documentation group scopes (given, describe, context) will eagerly execute any code within. Any test state initialization should be done within fixtures (beforeEachTest, beforeGroup, etc ...). You can also use memoized to create a dependency tied to Spek's lifecycle.
object MySpek: Spek({
    val myMock1 by memoized { mock<myMock1>() }
    val myMock2 by memoized { mock<myMock2>() }

    val handler by memoized { StartModeHandler(myMock1, myMock2) }

    val session by memoized {
        mock<Session> {
            on { user }.doReturn(User.builder().withUserId("userId").build())
        }
    }

    describe("item exists for user") {
        beforeEachTest {
            reset(digitalPointDao, trackDao)
            whenever(myMock1.loadItem(session.user.userId)).thenReturn(Optional.of(MyItem()))
            whenever(myMock2.loadSomething()).thenReturn(ArrayList())
        }

        // use on instead of context
        on("method onLaunch was called") {
            val response = handler.onLaunch(session)
            it("should return the response for existing user") {
                //some asserts here
            }
            it("should save the item") {
                //some mock verifies here
            }
        }

    }
})


text:
Q: Android AlarmManager triggered immediately even with correct parameters? I am setting an AlamManager from the onCreate of my main Activity.
Here is the method
public void scheduleAdsUpdateAlarm() {
    long THEE_HOURS = 3 * 60 * 60 * 1000;
    long THREE_MINUTES= 3*60*1000;
    long UNTIL_FIRST_TRIGGER = THREE_MINUTES;

    // Construct an intent that will execute the AlarmReceiver
    Intent intent = new Intent(getApplicationContext(), AdsUpdateAlarmReceiver.class);

    // Create a PendingIntent to be triggered when the alarm goes off
    final PendingIntent pIntent = PendingIntent.getBroadcast(this, AdsUpdateAlarmReceiver.REQUEST_CODE,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);

    if(alarm != null){
        alarm.cancel(pIntent);
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, UNTIL_FIRST_TRIGGER,
                THREE_MINUTES, pIntent);
    }
}

As you can see the alarm is set to run every three hours with the initial start after three minutes.
Problem is that the alarm goes off immediately when the onCreate and the following alarm setup is called. I don't understand what I am doing wrong?

A: alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, UNTIL_FIRST_TRIGGER,
THREE_MINUTES, pIntent);

should be changed to:
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + UNTIL_FIRST_TRIGGER, THREE_MINUTES, pIntent);

since the second parameter in alarm.setInexactRepeating isn't a milliseconds from now value but an actual time value.


text:
Q: Multiple keywords for history search browser addon API Is there a way to have an OR in the search query when searching the browser history?
Currently I use it like this:
  browser.history.search({
    text: some_root_url,
    maxResults: max_results,
    startTime: some_date
  }).then(process_items)

This is for an addon.
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/search
What I do is search for a root url in "text", like "https://somesite.com".
But I want to try using multiple sources, multiple urls in "text".
But doesn't seem to have an OR mode.
I know I can just do multiple calls to the history, one for each source, but that seems to double the running time.


text:
Q: Why seem my program memory write faster than read? My simple program:
//usage:
//indent ./a.c;gcc -O0 ./a.c
//./a.out max r/w repeat timeout

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int
main (int argc, char **argv)
{
  time_t const start_time = time (NULL);
  time_t timeout;
  int max;
  int repeat;
  if (argc == 5)
    {
      max = atoi (argv[1]);
      repeat = atoi (argv[3]);
      timeout = ((time_t) (atoi (argv[4])));
    }
  else
    return 1;

  unsigned char **block_array =
    calloc (sizeof (unsigned char *), (size_t) (max));

  size_t block_length = (size_t) (1024u * 1024u);

  unsigned char data[3];
  data[0] = 'a';
  data[1] = 'b';
  data[2] = 'c';

  unsigned i = 0u;
  //initialize block_array
  for (i = 0u; i < max; i++)
    {
      do
    {
      if ((timeout > ((time_t) (0)))
          && ((time (NULL) - start_time) > timeout))
        {
          puts ("timeouted!");
          return 0;
        }
      block_array[i] = malloc (block_length);
      if (block_array[i] != NULL)
        {
          unsigned bi = 0u;
          for (bi = 0u; bi < block_length; bi++)
        block_array[i][bi] = data[bi % ((unsigned) (sizeof (data)))];
        }
      else
        {
          printf ("%u error\n", i);
        }
    }
      while (NULL == block_array[i]);
    }
  puts ("init ok");

  unsigned score = 0u;
//do page read test
  if ('r' == argv[2][0])
    for (;;)
      {
    for (i = 0u; i < max; i++)
      {
        if ((timeout > ((time_t) (0)))
        && ((time (NULL) - start_time) > timeout))
          {
        puts ("timeouted!");
        goto show_score;
          }

        unsigned bi = 0u;
        for (bi = 0u; bi < block_length; bi++)
          {
        data[bi % ((unsigned) (sizeof (data)))] = block_array[i][bi];
          }
        score++;
      }
    if (repeat >= 0)
      {
        repeat--;
        if (0 == repeat)
          goto show_score;
      }
      }
//do page write test
  else if ('w' == argv[2][0])
    for (;;)
      {
    for (i = 0u; i < max; i++)
      {
        if ((timeout > ((time_t) (0)))
        && ((time (NULL) - start_time) > timeout))
          {
        puts ("timeouted!");
        goto show_score;
          }

        unsigned bi = 0u;
        for (bi = 0u; bi < block_length; bi++)
          {
        block_array[i][bi] = data[bi % ((unsigned) (sizeof (data)))];
          }
        score++;
      }
    if (repeat >= 0)
      {
        repeat--;
        if (0 == repeat)
          goto show_score;
      }
      }
show_score:
  printf ("score:%u\n", score);
  return 0;
}

I also same test Debian Jessie(Linux 3.16)(lesser test) and Debian Stretch(Linux 4.9)(more test to sure)
I already repeat many times same test to sure this,so I only post a short result.
Test result:
$ cat /proc/meminfo |grep SwapTotal
SwapTotal:             0 kB
$ time ./a.out 100 r  5 -1
init ok
score:500

real    0m2.689s
user    0m2.604s
sys 0m0.080s
$ time ./a.out 100 w  5 -1
init ok
score:500

real    0m2.567s
user    0m2.496s
sys 0m0.060s
$

A: The main assignment inside the loop in both the 'r' and 'w' cases reads from memory and writes back to memory i.e. they are essentially the same - you aren't really testing memory read versus memory write. This is borne out by the fact that the times in each case are pretty close.
The 'w' case may be slightly faster because the cache probably contains the value you want to read from memory, since you aren't changing the source address in that case.


text:
Q: Returning Just count of records found in MYSQL query I have the following MYSQL query which returns the number of photos found for each record where the number of photos is greater than 0.
SELECT advert_id, (SELECT COUNT( * ) FROM advert_images b WHERE b.advert_id = adverts.advert_id) AS num_photos
FROM adverts
WHERE adverts.approve =  '1'
HAVING num_photos > 0

The query works fine, but I want to just return a count of the records found.  i.e. the number of records which have at least one photo.  I've tried to wrap the whole query in a COUNT, but it gives an error.  I want to do this in the query, and not a separate count of records found in php.

A: SELECT COUNT(*) AS TotalRecords
FROM
(
  SELECT a.advert_id, COUNT(*) AS num_photos
  FROM adverts AS a
    JOIN advert_images AS i
    ON i.advert_id = a.advert_id
  WHERE a.approve =  '1'
  GROUP BY a.advert_id
  HAVING num_photos > 0
) AS mq

A: SELECT COUNT(*) FROM (SELECT advert_id, (SELECT COUNT( * ) FROM advert_images b WHERE b.advert_id = adverts.advert_id) AS num_photos
FROM adverts
WHERE adverts.approve =  '1'
HAVING num_photos > 0) AS c

This should do the trick


text:
Q: Block all windows with MessageBox.Show() I'm currently working on a WPF app which has multiple windows. From the "main" window, you should be able to close the entire app. Before the app will be closed, the client wants it to show a dialog box which basically asks "are you sure you want to close the app" and blocks every other window until the user answers.
I'm currently using MessageBox.Show() to create this dialog box, but for some reason it only blocks the main window.
Here's the simplest example of what I'm talking about; if you create a WPF window with two buttons:
private void openChildWindowButton_Click(object sender, RoutedEventArgs e)
{
  var window = new ChildWindow();
  window.Show();
}

private void openDialogButton_Click(object sender, RoutedEventArgs e)
{
  MessageBox.Show(this, "This should freeze all other windows");
}

Opening a dialog will completely freeze the first window. If you click on it or attempt any sort of interaction, the OS makes a "ding!" sound and flashes the border on the message  box. But all of the other windows you've opened can be clicked, moved, resized, etc., and that's what I want to prevent.

A: As it turns out, there is a way to do this, but it's not pretty. It involves using the WinForms version of MessageBox and passing an undocumented option as the last property.
var result = System.Windows.Forms.MessageBox.Show("Are you sure you want to exit this app?", "Exit", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button2, (System.Windows.Forms.MessageBoxOptions)8192 /*MB_TASKMODAL*/);

Source: http://social.msdn.microsoft.com/Forums/vstudio/en-US/8d1bd4a2-455e-4e3f-8c88-7ed49aeabc09/messagebox-is-not-applicationmodal?forum=wpf
Hopefully this is helpful to somebody else in the future!

A: If this works in WPF like in Windows Forms you could just use:
MessageBox.ShowDialog()

chris
Above not working...
Edit:
But there is a workaround: style a Form like a MessageBox (use a fixed Border-Type) and then Show it using ShowDialog(). Then set the Forms Cacel and Ok Button in Properties to your Buttons and you can get a DialogResult just like in a MessageBox. Hope that Helps but it is also from Windows-Forms ;)


text:
Q: Unable to implement boundary conditions for a spherical wave equation coupled to a Laplace equation I am having trouble setting up in Mathematica v 12.1 the following
system of coupled pdes on $r\in[0,10]$
$$ \left(\partial_t^2 - \frac{1}{r^2}\partial_r r^2 \partial_r \right) \theta(t,r) = -(1+2\Phi(t,r))\theta(t,r)$$
$$\frac{1}{r^2}\partial_r r^2 \partial_r \Phi(t,r) = \theta(t,r)^2  $$
For $\theta$ I have the initial conditions
$$\theta(0,r)=e^{-r^2}, \qquad \partial_t\theta(0,r)=0.$$
and smoothness bc at origin and absorbing bc at $r=10$.
$$\partial_r \theta(t,0)=0, \qquad \left.\partial_t(r \theta(t,r))\right|_{r=10}+\left.\partial_r(r \theta(t,r))\right|_{r=10}=0$$
The latter ensures no information comes in from outside the domain.
$\Phi$ can be obtained by integrating the second equation so I don't believe I need to provide initial conditions for it. There are in principle two integration constants however so I must therefore impose two conditions, e.g.
$$\partial_r \Phi(t,0)=0, \qquad \Phi(t,0)=-4$$
Below is how I've tried to implement it in Mathematica. (As far as I understand, the smoothness bc at the origin are taken care of automatically). I get the following error

tend = 100.;
rstart = 1/10^100;
rend = 10;

ic = {\[Theta][0, r] == Exp[-(r)^2], (D[\[Theta][t, r], t] /. t -> 0) == 0};
bc = {\[CapitalPhi][t, 0] == -4};

{teta, phi} = NDSolveValue[Flatten@{-((2 r \!\(\*SuperscriptBox[\(\[Theta]\),TagBox[RowBox[{"(", RowBox[{"0", ",", "1"}],")"}],Derivative],MultilineFunction->None]\)[t, r] + r^2\!\(\*SuperscriptBox[\(\[Theta]\), TagBox[RowBox[{"(", RowBox[{"0", ",", "2"}], ")"}],Derivative],MultilineFunction->None]\)[t, r])/r^2) +\!\(\*SuperscriptBox[\(\[Theta]\), TagBox[RowBox[{"(", RowBox[{"2", ",", "0"}], ")"}],Derivative],MultilineFunction->None]\)[t,r] == -(1 + 2 \[CapitalPhi][t, r]) \[Theta][t, r] + NeumannValue[-Derivative[1, 0][\[Theta]][t, r] - \[Theta][t, r]/r, r == rend] , ((2 r \!\(\*SuperscriptBox[\(\[CapitalPhi]\), TagBox[RowBox[{"(",RowBox[{"0",",", "1"}], ")"}],Derivative],MultilineFunction->None]\)[t, r] + r^2 \!\(\*SuperscriptBox[\(\[CapitalPhi]\), TagBox[RowBox[{"(", RowBox[{"0", ",", "2"}],")"}],Derivative],MultilineFunction->None]\)[t, r])/r^2) == \[Theta][t, r]^2, ic,bc}, {\[Theta], \[CapitalPhi]}, {t, 0, tend}, {r, rstart, rend}]

Animate[Plot[{teta[t, r], phi[t, r]}, {r, 0, rend},PlotRange -> {{0, rend}, {-1, 1}}], {t, 0, tend}]


text:
Q: Synchronous call in vertx We try to refactor our project from servlet to vertx3.x. And we want to reuse the DAO layer which take responsibility for query data:
interace Adapter {
    List<Feature> query(String layer);
}

class DataBaseAdapter implements Adapter {

}

class FileAdapter implements Adapter {

}

class HttpVertx extends AbstractVertx {
    void start() {
        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);
        router.route().handler((h->{
            List<Feature> r=new ArrayList();
            String[] layers=getLayerFromRequest(h.request());
            layers.forEach(l->{
                h.vertx().executeBlocking(future->{
                    future.complete(getAdapter(l).query(l));
                },false,res->{
                    List<Feature> data=res.result();
                    r.addAll(data);
                    //now how can I know that the loop have ended, and I can send the `r` to the client?
                });
            });

        }));
        server.requestHandler(router::accept).listen(8080);
    }

    Adapter getAdapter(String layer){
        //return database or file adapter accordingly
        return null;
    }
}

As shown, the original adapter querying are all block operation, once I execute them in a loop, I do not know when they have all done.
Furthermore, I am not sure if it is necessary to refactor the DatabaseAdapter using the vertx-jdbc? If yes, I will have to change the method signature of  Adapter interface to synchronous, but the FileAdapter does not support that.
What's the proper refactgor solution?

A: *

*try moving the looping logic into the executeBlocking block and changing the handler type to Handler<List<Feature>>

*no, it's not absolutely necessary as wrapping these calls in executeBlocking is already doing the expensive work of your database interactions against the Verticle's worker pool.

A: First, don't use executeBlocking(). It breaks the entire idea of Vert.x
Second, I would recommend to rewrite your DAO to return Future. It will require some work, but the work will be pretty straightforward.
On the high level, it should look something like this:
// Use map(), as it returns value
List<Future> futures = layers.map((l) -> {
   return getAdapter(l).query(l);
});

CompositeFuture.all(futures).setHandler((r) -> {
   if (r.succeeded()) {
    // Continue here
   }
});


text:
Q: Control Elements Visibility from other class/viewModel I am development an app using xamarin forms, and I am trying to build an animated menu, this is what I have used

*

*I created a ContentView and put buttons there and created complete animations there (because same contentview will be used on multiple screens)
animation works fine but buttons can not be clicked after they changed their position using TranslateTo method in xamarin.

*My idea was to use another hidden layout with  buttons on same positions where animated buttons will appear at end, but these button will have 0 opacity this means they will work properly but not visible to user, and when menu gone hidden this layout should be hidden too

The Problem: When I click on menu button animated menu appears correct but I am unable to make other layout visible or hide,
I am not sure if we can hide/show elements from other classes other then View's on class, this what I am trying to achieve.
Here is little sample of my code:
Menus.cs (this is my ContentView which I am using in Detail.cs)
Detail d = new Detail();
d.ToggleBtnLayout();

I am using this method in Menu.cs to show/hide a layout which is inside Detail.cs.


text:
Q: How to use Java Stream API to resolve sliding window problems? Since Java 8, using Stream API has become prevalent. However, some problems can be easily resolved using batch based algorithm may not be easily resolved with stream based solution.
For example, given a stream of transactions of one credit card in timing sequence, I would like to find the card's total transaction amount in each 24 hours so that I can compare it with a threshold value to guess whether the card is stolen.
The stream data can be as simple as
transaction time            amount
2019-01-23T10:12:31.484Z    100
2019-01-24T00:12:30.004Z    50
2019-01-24T09:00:00.000Z    23
2019-01-27T05:10:00.300Z    65

This can be seen as a sliding window problem, which needs to check relations of elements. A batch based solution is not very complex. I can use a queue to keep only transactions happen in 24 hours.
the Algorithm can be roughly described with below steps:

*

*create a queue and put the first transaction into the queue;

*compare the next transaction with the transaction of queue head.

*check the transaction time difference of the 2 transactions
if the time difference is less than 24 hours,

*add the transaction to the queue and return to step 2.
else if it's longer than 24 hours, then
5.1. calculate the total transaction amount of transactions in the queue as those transactions happen in 24 hours
5.2 put the result into a result list.
5.3 poll the queue to delete the oldest transactions until the new transaction happens less than 24 hours with a transaction in the queue.
5.4 loop to step 2.
However, I find it difficult to implement the above algorithm using Java Stream API so I wonder is it a good idea to use Java stream to implement a sliding window problem? If yes, could anyone give some hint or some pseudo code using Java Stream to implement it? It's not necessary to use the above algorithm. Any stream based algorithm is ok.

A: This is an example how it can be done with reduce.
For collecting data class was created:
class Row {

    private LocalDateTime date;
    private Integer value;

    public Row(LocalDateTime date, Integer value) {
        this.date = date;
        this.value = value;
    }

    // getters and setters

First read example data into stream.
Stream<Row> readData = Stream.of(
        "2019-01-23T10:12:31    100",
        "2019-01-24T00:12:30    50",
        "2019-01-24T09:00:00    23",
        "2019-01-25T03:00:00    23",
        "2019-01-27T05:10:00    65")

        .map(s -> s.split("\\s+"))
        .map(a -> new Row(LocalDateTime.parse(a[0], DateTimeFormatter.ISO_LOCAL_DATE_TIME), Integer.valueOf(a[1])));

Than in reduce method collect every 24-hours period of rows to separated list and store it in main list.
List<List<Row>> all = new ArrayList<>();
all.add(readData
        .map(Arrays::asList)
        .reduce(new ArrayList<>(), (a, v) -> {
            if (a.isEmpty()) {
                a.addAll(v);
            } else {
                LocalDateTime first = a.get(0).getDate().plusHours(24);
                if (first.isAfter(v.get(0).getDate())) {
                    a.addAll(v);
                } else {
                    all.add(a);

                    LocalDateTime last = v.get(0).getDate().minusHours(24);
                    a = new ArrayList<>(a.stream()
                            .filter(r -> last.isBefore(r.getDate()))
                            .collect(Collectors.toList()));
                    a.addAll(v);

                }
            }
            return a;
        }));

At the end you can print out all list or calculate transactions values in each period.
all.forEach(System.out::println);

all.stream().map(l -> l.stream()
        .map(Row::getValue)
        .reduce(Integer::sum)
        .get()
)
.forEach(System.out::println);

UPDATE
reduce can be also replace with simple forEach.
Then the main part would be like that and would be less complex:
LinkedList<List<Row>> all = new LinkedList<>(Arrays.asList(new ArrayList<>()));
readData
        .forEach(v -> {
            if (!all.getLast().isEmpty()) {
                // check if in 24h boundary
                LocalDateTime upperValue = all.getLast().get(0).getDate().plusHours(24);
                if (!upperValue.isAfter(v.getDate())) {
                    // create copy with row older earlier than 24h
                    LocalDateTime lowerValue = v.getDate().minusHours(24);
                    all.add(new ArrayList<>(all.getLast().stream()
                            .filter(r -> lowerValue.isBefore(r.getDate()))
                            .collect(Collectors.toList())));
                }
            }
            all.getLast().add(v);
        });

A: The "problem" with doing this via Streams is that they are designed to be easily parallelizable. They are not sequential-only by design, and therefore purely sequential algorithms (as your queue-based algorithm is) do not work well with Streams. This is the leap to take from imperative to functional programming, you sometimes need a new algorithm, new approach. Translating imperative code into functional is not always straightforward.
If your data source can be easily split multiple times (which, I think, is equivalent to being able to provide the required windows efficiently and concurrently), you can do this with Streams. For example, you could (re)use StreamEx's ofSublists() method if your data source is a List. This works because creation of any sublist is efficient and independent of the other sublists, so it can be safely called concurrently.
Alternatively, you can assume your Stream would never run parallelized, and use something focused on pure sequences, e.g. jOOL: Seq.sliding(). This works on any Seq because the implementation can use iterative state without worrying about parallelism.


text:
Q: Excel Addin and overriding save keyboard shortcut Currently I've inherited a Word/Excel addin project that does a custom save process.  The project is in VS2010 and Excel/Word 2007
In the word addin, the following xml is being passed back GetCustomUI call, defining our custom functionality
<commands>
  <command idMso="FileOpen" onAction="WordAddinOpen" />
  <command idMso="FileSave" onAction="WordAddinSave" />
  <command idMso="FileSaveAs" onAction="WordAddinSaveAs" />
</commands>

When I put a breakpoint in my WordAddinSave function, and click either the save icon or press Control-S, the code stops at my breakpoint.  The same happens if I put a breakpoint in my open functionality and press Control-O
In the Excel addin, I have similar xml being passed back
<commands>
  <command idMso="FileOpen" onAction="ExcelAddinOpen" />
  <command idMso="FileSave" onAction="ExcelAddinSave" />
  <command idMso="FileSaveAs" onAction="ExcelAddinSaveAs" />
</commands>

But, if I put a breakpoint in my ExcelAddinSave function, the code only stops if I click on the save icon, but not the keyboard shortcuts.  If I press Control-S or Control-O, the default Excel behavour of saving/opening file happens, instead of my custom functionality.
The ExcelAddinSave/ExcelAddinOpen is defined in a class that inherits BaseRibbon and implements Office.IRibbonExtensibility, as follows:
[ComVisible(true)]
public class CExcelRibbon : BaseRibbon, Office.IRibbonExtensibility
{
    public CExcelRibbon()
    {
    }

    public string GetCustomUI(string ribbonID)
    {
        Assembly asm = Assembly.GetExecutingAssembly();
        return GetResourceText(asm, "CExcelRibbon.xml");  //defines custom functionality
    }

    public void ExcelAddinOpen(Office.IRibbonControl control, bool cancel)
    {
        //custom open functionality snipped
    }

    public void ExcelAddinSave(Office.IRibbonControl control, bool cancel)
    {
      //custom save functionality snipped
    }

    //remaining class functionality snipped
}

Because I've inherited this project, I'm not the expert in Office Addins, but why doesn't the excel call my Excel addin functionality on the keyboard shortcuts Control-S/Control-O?
Note:
The current functionality is setting up a SetWindowsHookEx keyboard hook to preview all keypresses for a Control-S/Control-O.  However, due to our environment, this looks like to be an issue, as it appears Windows 7 is disconnecting our key press hook due it taking too long.  I've tested it with the following reg key set, and it stays.  However, long term I'd like to find a more optimal solution
 HKEY_CURRENT_USER\Control Panel\Desktop\LowLevelHooksTimeout


text:
Q: handling Links and CSS in Flask web proxy So I tried to develop a web proxy using Flask. in the progress I found out that somehow I need to handle Likns so all redirects take place in the web proxy, this is what I write:
import requests
from flask import Flask , request
from requests import get
import re

app = Flask(__name__)
mainURL = ""
myHost = "http://127.0.0.1:5000/"

@app.route("/", methods =["GET", "POST"])
def Home():
    #a small form for users to write thier URL inside it
    mainpage = '<!DOCTYPE html><form action="/" method="post">URL:
<input type="text" id="url" name="url" value="https://www.google.com/">
<input type="submit" value="Open"></form>'

    #check if submit button trigered
    if request.method == "POST":

        mainURL = request.form.get("url")
        response = requests.get(mainURL)

        #this is for handling links and pictures. I know its not optimal, thats why im here!
        a = response.text.replace("='/",f"='{mainURL}")
        a = a.replace('="/',f'="{mainURL}')
        a = a.replace("url(/",f"url({mainURL}")
        a = a.replace('href="http',f'href="{myHost}http')
        a = a.replace("href='http",f"href='{myHost}http")
        a = a.replace(r'href="(?!http)',f'href="{myHost}{mainURL}')
        a = a.replace(r"href='(?!http)",f"href='{myHost}{mainURL}")

        return a
    return mainpage

#decroator for the times when a path opened
@app.route('/<path:path>')
def proxy(path):
    #this RegEx find the website FQDN from path
    if re.match(r"https?://w{3}\.\w*\.\w*/",path):
        temp = re.match(r"https?://w{3}\.\w*\.\w*/",path)
        mainURL = temp[0]
        response = requests.get(path)

        #again links and pictures handler. dont judge me, I wrote a function for it but IDK why it didn't works for pictures!
        a = response.text.replace("='/",f"='{mainURL}")
        a = a.replace('="/',f'="{mainURL}')
        a = a.replace("url(/",f"url({mainURL}")
        a = a.replace('href="http',f'href="{myHost}http')
        a = a.replace("href='http",f"href='{myHost}http")
        a = a.replace(r'href="(?!http)',f'href="{myHost}{mainURL}')
        a = a.replace(r"href='(?!http)",f"href='{myHost}{mainURL}")

        return a
    return "URL is Incorrect!"

if __name__ == "__main__":
   app.run(host='127.0.0.1',port='5000',debug=True)

This is Output:
opening Google using proxy
so its open a webpage but its so slow because of all those replace and with all of these its still can't load CSS!
so what I want is a optimized way to redirect all links to proxy and handling CSS!


text:
Q: Why am I not able to read variable from json output from my php in my controller when it succeeds in angularjs application?  $http({
                method: 'POST',
                url: 'api/userBadgeIdRound.php',
                data: { 'idUser': $scope.idUser },
                headers: { 'Content-Type': 'application/x-www-form-urlencoded;  charset=iso-8859-1' }
            })
            .success(function (data, status) {
                console.log(data);
                //$scope.messages = JSON.stringify(data);
                $scope.userBadges = data.badges;
                $scope.idRound = data.round.idRound;
                console.log($scope.userBadges);
                console.log($scope.idRound);
            })
            .error(function (data, status) {
                console.log("post errore");
            });

TypeError: Cannot read property 'idRound' of undefined
    at controller.js:503
    at angular.js:7976
    at deferred.promise.then.wrappedCallback (angular.js:11408)
    at deferred.promise.then.wrappedCallback (angular.js:11408)
    at angular.js:11494
    at Scope.$eval (angular.js:12518)
    at Scope.$digest (angular.js:12330)
    at Scope.$apply (angular.js:12622)
    at done (angular.js:8234)
    at completeRequest (angular.js:8439)

 console.log(data); with this i am able to get json data from  php file but

Array�����������������������������������������������������������������������������������������������
��������������������(this is output from my php)
 console.log($scope.userBadges);

 console.log($scope.idRound);

output(undefined)

I am unable to assign while assigning it's showing error like undefined and I found one thing to solve to this kind of problem from here  so I changed my
charset from UTF-8 to iso-8859-1. However, in my case it's not working.


text:
Q: Firestore - Use a Where Clause and startAt with different fields I'm in a bit of a bind creating a query in Firestore's Android SDK. I want to limit documents to only those from the past week to reduce the number of docs, and also filter results using user-supplied text. I'd like to use a whereGreaterThan clause with the created field for the date, and startAt and endAt clauses for the filtering the id field.
However, there is a problem. The SDK requires that the first orderBy clause use the same field as the whereGreaterThan clause. On the other hand, the startAt and endAt also seem to be bound to the first orderBy clause.
Calendar oneWeekAgo= Calendar.getInstance();
oneWeekAgo.add(Calendar.DATE, -7);
Query query = firestore.collection(BuildConfig.FULL_PATH)
.whereGreaterThan("created",oneWeekAgo.getTime())
.orderBy("created", Query.Direction.ASCENDING)
.orderBy("id", Query.Direction.ASCENDING)
.startAt(filter)
.endAt(filter + "z");

Is there a way to bind the .startAt and .endAt to the second orderBy? Or otherwise accomplish the goal of getting filtered docs from firestore created after a certain date?
If I delete the whereGreaterThan and first orderBy clauses, the query gets filtered results from all documents, not just those created in the past week.

A: This a limitation of the API because Cloud Firestore doesn't support ordering by a different field than the supplied inequality. In this case you should order the data at client side, in this case your Android app. This is explained here too.