text:
Q: How to pass a std::function or a function pointer into qtconnect? This is mainly to clean up a bunch of code from my constructor. I have around 20+ lines of connect(object, func1, this, func2) in the constructor alone and I am trying to clean up the code by having a std::vector<std::tuple<QObject*,std::function<void()>,std::function<void>>>> connections;
It would work out quite nicely if I could do something like:
std::vector<std::tuple<QObject*,std::function<void()>,std::function<void>>>> connections = {
  std::make_tuple(mySlider, std::bind(&QSlider::sliderReleased,mySlider, std::bind(&Foo::onSliderChanged,this)),
  .
  .
  .
};

And then call it like this:
for(auto &&e : connections)
  connect(std::get<0>(e),std::get<1>(e),this,std::get<2>(e));

However, when I do this I get an error that there is a substitution failure and a std::function<void()> cannot be converted into a function pointer. So decide to change it up and create actual function pointers like the following:
typename void(Foo::*fooFunc)();
typename void(QSlider::*sliderFunc)();

std::vector<std::tuple<QObject*,sliderFunc,fooFunc>> sliderConnections = {
  std::make_tuple(mySlider, &QSlider::sliderReleased, &Foo::onSliderChanged),
  .
  .
  .
};

And same thing, I then try to call it:
for(auto &&e : sliderConnections)
  connect(std::get<0>(e),std::get<1>(e),this,std::get<2>(e));

However this also provides a similar error where there are no conversions. Which doesn't make any sense because now I am actually using a function pointer. Which according to the connection documentation it should be able to take a function pointer to connect them. So either I am passing it in incorrectly. Or what I am trying to achieve is not possible.
Any help would be appreciated!

A: After looking at G.M's comment I realized they were correct. A QObject* is not a QSlider* and therefore when trying to call the function QSlider::sliderReleased it couldn't connect the two because QObject does not have a slider. So once I changed that in the vector of tuples the code compiled just fine.
ex:
typedef void(Foo::*fooFunc)();
typedef void(QSlider::*sliderFunc)();
typedef void(QSpinBox::*spinFunc)();

const std::vector<std::tuple<QSlider*, sliderFunc, fooFunc>> sliderConnections = {
  std::make_tuple(slider1, &QSlider::sliderReleased, &Foo::onSlider1Changed),
  std::make_tuple(slider2, &QSlider::sliderReleased, &Foo::onSlider2Changed),
  std::make_tuple(slider3, &QSlider::sliderReleased, &Foo::onSlider3Changed)
};

const std::vector<std::tuple<QSpinBox*, spinFunc, fooFunc>> spinConnections = {
  std::make_tuple(spin1, &QSpinBox::editingFinished, &Foo::onSpin1Changed),
  std::make_tuple(spin2, &QSpinBox::editingFinished, &Foo::onSpin2Changed),
  std::make_tuple(spin3, &QSpinBox::editingFinished, &Foo::onSpin3Changed)
};

These will be private members in whatever class you are in charge of. And then in the constructor, instead of having 6 lines of connect(object,SIGNAL,object,SLOT), you can then put them into a function and call them like:
for(auto && tup : sliderConnections)
  connect(std::get<0>(tup),std::get<1>(tup),this,std::get<2>(tup));

This successfully connects all the objects to their appropriate functions. Again, it's personal preference. I was just wondering if there was a way and G.M pointed me in the correct direction.


text:
Q: Radius of Convergence of Laurent Series How does one prove that if a function as $n$ poles, and domain the complex plane except the poles, then the radius of convergence of the Laurent series at each pole is the distance to the nearest pole.

A: Let $f$ be your function. If the poles are $z_0,z_1,\ldots,z_n$, consider the Laurent series$$\sum_{n=-N}^\infty a_n(z-z_0)^n\tag1$$of $f$ about $z_0$, where $N$ is the order of the pole. Assume the no pole of $f$ is closest to $z_0$ than $z_1$. If $(1)$ converges in a region $D(z_0,R)\setminus\{z_0\}$ with $R>\lvert z_1-z_0\rvert$, then $\lim_{z\to z_1}\sum_{n=-N}^\infty a_n(z-z_0)^n$ exists, which is impossible, since $z_1$ is a pole of $f$.
On the other hande, consider $F(z)=(z-z_0)^Nf(z)$. There is a standard Complex Analysis theorem that says that the radius of convergence of theTaylor series of $F$ about $z_0$ is at least the distance from $z_0$ to the closest point outside the domain of $f$, that is, $\lvert z_0-z_1\rvert$. Since $f(z)=\frac{F(z)}{(z-z_0)^N}$…

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can a formal parameter have the same name as a type? (C) I'm not arguing that this is good programming style, but I was surprised that this compiled[*] and ran without complaint:
#include <stdio.h>

// define function signature
typedef int (*proto_fn)();

int x() { return 22; }

// Note: type name and formal parameter name are the same
void printit(proto_fn proto_fn) {
  printf("%d\n", proto_fn());
}

int main() {
  printit(x);
  return 0;
}

Aside from potentially confusing humans, is there anything in the C standard that would forbid using identical names for a type and a formal parameter?
[*] (In this case, Apple clang version 11.0.0 (clang-1100.0.33.8).)

A: I modified the code to check whether the name proto_fn stands for a type name or an variable of the type proto_fn, inside the function printit.
#include <stdio.h>

// define function signature
typedef int (*proto_fn)();

int x() { return 22; }

// Note: type name and formal parameter name are the same
void printit(proto_fn proto_fn)
{
  printf("%d\n", proto_fn());
  proto_fn;

}

int main() {
  printit(x);
  return 0;
}

Above code works fine.
#include <stdio.h>

// define function signature
typedef int (*proto_fn)();

int x() { return 22; }

// Note: type name and formal parameter name are the same
void printit(proto_fn proto_fn)
{
  printf("%d\n", proto_fn());
  proto_fn kk;

}

int main() {
  printit(x);
  return 0;
}

But this code throws an error :
error: expected ';' before 'kk'
proto_fn kk;
So, from this I concluded that the name proto_fn is just a variable of the type proto_fn, inside the function printit. I think the type proto_fn is not visible, inside the function printit .  I think variable proto_fn shadows the type proto_fn inside the function printit.  This might be the reason, why the code works.


text:
Q: What does this.Validate() do? Called from BindingNavigatorSaveItem_Click put in by VS By default, Visual Studio put this code in my BindingNavigatorSaveItem_Click method.
this.Validate();
this.detimpBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.rDataSet);

What does this.Validate() do and how does it work?  When I set a breakpoint, it doesn't seem to do anything.


text:
Q: Cron stops working after a specific time I am using a cron to execute a python script every 15 minutes during the day.
At nighttime it should only run every hour.
I made 2 entries for this:
0 23-5 * * * python /var/www/script.py > /dev/null 2>&1
*/15 6-22 * * * python /var/www/script.py >/dev/null 2>&1

The one running during the day works fine. This is the last entry from that script in /var/log/syslog:
Jan 26 22:45:01 web CRON[20278]: (sysadmin) CMD (python /var/www/script.py > /dev/null 2>&1)

But there are no entries for that script after 23:00.
The next entry from that script is:
Jan 27 06:00:01 web CRON[26367]: (sysadmin) CMD (python /var/www/script.py > /dev/null 2>&1)

And that is the "day-cron"-entry starting again.
Both entries are made in the same crontab of the user "sysadmin".
Any ideas what the problem here is? Or where else I could look for clues?
I am running Ubuntu 16.04.1 LTS - 4.4.0-42-generic.

A: Change 23-5 to 23,0,1,2,3,4,5 or you can add two lines like so:
0 23 * * * python /var/www/script.py > /dev/null 2>&1
0 0-5 * * * python /var/www/script.py > /dev/null 2>&1

Or even as others have said (I forgot you can mix and match):
0 23,0-5 * * * python /var/www/script.py > /dev/null 2>&1

The reason why? Because 23-5 is not a valid range. The range must be from low value to high value only.


text:
Q: Ruby combine elements in hash I have a has that looks like this:
data = {abc -> [[date1, val1], [date2,val2]], def -> [[date1,val3], [date2,val4]]}

I want to join the abc and def elements so it's like this:
data = {join -> [[date1, val1+val3], [date2, val2+val4]] }

How do I go about this. Note that there are other elements in the hash that should not be modified.

A: I am assuming that abc, def, and join are actually Symbols.
a = Hash[data.delete(:abc)]  # extract data[:abc] and convert it to a Hash ("a")
b = Hash[data.delete(:def)]  # extract data[:def] and convert it to a Hash ("b")
data[:join] = a.map do |k,v| # iterate over one of the extracted Hashes
  [k, v + (b[k] || 0)]       # for each key, return a 2-item array with the key,
end                          #   and the sum of the values from "a" and "b"


text:
Q: How to undeploy an asp.net 2.0 website I have a deployed version of an asp.net 2.0 website developed by visual studio 2005... But unfortunately, the source code has been deleted...
I want to get the source code version of the website from the deployed version
There are tools to extract code from DLL to class libraries but I tried to search a lot I don't find any tools to extract DLL to asp.net code-behind
What can I do?
Thanks in advance

A: Well you could try to de-compile but its not very easy to understand or put the code into any further "easy" development once its de-compiled.But it would of course give you a head start , and if your website was published with enough debug info it probably might give you something real close to the original.
Give this a try :
Red Gate Reflector


text:
Q: Route Client App To Different Port Backend IIS 10 I have a HTTP Listener that listens for incoming traffic on port 11000 in my Azure VM. I want a client app sending data to that port but without having to type the port in the client app and also using https instead of http.
For instance, when typing the URL in the client app, it would be: https://myurl/data. But in the back end, IIS would re-route to http://myurl:11000/data.
I also have an app that is on 443, so I would want it to route from 443 to 11000.
I followed this article's example but still doesn't route the data stream to my HTTP listener to the port provide in the config file. Would I use redirect or rewrite for the web.config file?

A: If I understand correctly, what you want is that

https://myurl/data re-route to http://myurl:11000/data

HTTPS requests can be redirected to HTTP via rewrite rules. But redirecting HTTPS to HTTP is not recommended for many factors.
If you want to send data to port 11000 in the client application, but don't have to type the port in the client application, you need to create the URL rewrite rule on port 80, not on port 11000.
Refer to the following rules and modify it according to your actual requirements:
<rewrite>
    <rules>
        <rule name="Rule1" enabled="true" stopProcessing="true">
           <match url="^data(.*)" />
           <action type="Rewrite" url="http://myurl:11000/{R:0}" />
        </rule>
    </rules>
</rewrite>

Also, you need to double-click Application Request Routing Cache at the server level and select Server Proxy Settings on the right, then enable proxy and apply.
If you haven't installed the ARR module on IIS, you can refer to this link.


text:
Q: XML text extraction Scenario:
Given the following XML file:
<a:root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">

<h:table>
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table>
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>

aaaaaaaaaaaaaa

</a:root>

How do I extract the text inside the main element <a:root>:
"\naaaaaaaaaaaaaa\n"

The code I have right now is:
import java.io.File;
import java.util.Stack;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Proof {
    public static void main(String[] args) {
        Document doc = null;
        DocumentBuilderFactory dbf = null;
        DocumentBuilder docBuild = null;
        try {

            dbf = DocumentBuilderFactory.newInstance();
            docBuild = dbf.newDocumentBuilder();
            doc = docBuild.parse(new File("test2.xml"));

            System.out.println(doc.getFirstChild().getTextContent());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

But it returns the text I desire ("aaaaaaaaaaaaaa") + the inner text for the rest of the elements . Output:
    Apples
    Bananas

  African Coffee Table
  80
  120

aaaaaaaaaaaaaa

The requirement is not to use an additional XML java library !

A: The answer by @Kirill Polishchuk is not corect:
The proposed:
a:root/text()

*

*Is a relative expression and if it isn't evaluated having the root (/) node as the context node it selects nothing in the provided XML document.

*Even the XPath expression: /a:root/text() is incorrect, because it selects three text nodes -- all text node children of the top element -- including two whitespace-only text nodes.
Here is a correct XPath solution:
/a:root/text()[string-length(normalize-space()) > 0]

When this Xpath expression is applied on the provided XML document (corrected to be well-formed):
<a:root
xmlns:a="UNDEFINED !!!!"
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">

<h:table>
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table>
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>

aaaaaaaaaaaaaa

</a:root>

It selects the last (and only non-whitespace-only) text node child of the top element, as required:
aaaaaaaaaaaaaa

XSLT-based verification:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:a="UNDEFINED !!!!"
 >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:text>"</xsl:text>
  <xsl:copy-of select=
   "/a:root/text()
           [string-length(normalize-space()) > 0]"/>"

 </xsl:template>
</xsl:stylesheet>

when this transformation is applied against the provided XML document (above), the wanted, correctly selecte text node is output:
"

aaaaaaaaaaaaaa

"

A: You can use XPath: a:root/text()

A: Use this
import java.io.File;
import java.util.Stack;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Proof {
public static void main(String[] args) {
    Document doc = null;
    DocumentBuilderFactory dbf = null;
    DocumentBuilder docBuild = null;
    try {

        dbf = DocumentBuilderFactory.newInstance();
        docBuild = dbf.newDocumentBuilder();
        doc = docBuild.parse(new File("test2.xml"));

         Element x= doc.getDocumentElement();
       NodeList m=x.getChildNodes();
       for(int i=0;i<m.getLength();i++){
           Node it=m.item(i);
           if(it.getNodeType()==3){
               System.out.println(it.getNodeValue());
           }
       }
    } catch(Exception e) {
        e.printStackTrace();
    }
}

}


text:
Q: LitElement - How to create dom-if restamp behavior with javascript if expression inside LitElement render method? We are using "if" expression inside LitElement to selectively render content in render method and would like to re-create child DOM every time "if" expression get re-evaluated(changes). This is something similar to what dom-if element used to support with "restamp" property in polymer 3.
Really appreciate any pointers here to follow?
Thanks,
Vishal

A: You have 2 options depending on whether the condition will change several times and you want to cache the represented parts or not:
Without cache (vanilla javascript)
render() {
  return html`${
    condition ?
    () => html`Your TRUE HTML here` :
    () => html`Your FALSE HTML here`
  }`;
}

With cache (using cache directive from lit-html)
import { cache } from 'lit-html/directives/cache';
[…]
render() {
  return html`${cache(
    condition ?
    () => html`Your TRUE HTML here` :
    () => html`Your FALSE HTML here`
  )}`;
}

A: Try this:
    render() {
      return html`${
        condition ? html`<p>Hello</p>` : ''
      }`;
    }


text:
Q: Apriori and association rules with Hadoop Is it doable to create an Apriori app using map-reduce?  I am starting out but it's not clear how to create the next Candidate sets based on a previous run.  Does anyone have any experience with this?

A: It could be useful to have a look to Apache Mahout. It is a machine learning and data mining framework in Java which abstracts sending MapReduce jobs for clustering, recommendation and classification tasks.
It seems the apriori algorithm is not implemented (there is one jira issue marked as won't fix: https://issues.apache.org/jira/browse/MAHOUT-108), but maybe other algorithm could be useful for you.
Even if you only need the apriori algorithm, it could be useful to have a look at their source code to get some ideas.


text:
Q: Where can I get a list of all charsets (Content-Type HTTP response header) W3C says there is a full list here, however it seems to be down.
Where can I get a list of them?

A: I found a list at iana:
http://www.iana.org/assignments/character-sets

A: I use the following list
http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm


text:
Q: Angularjs:- button change based on json data Hi I am working on a project based on angularjs and fetching data from json..There is a problem I am stuck up with and was not getting a solution to..
The below is the Html code:-

                <button class="close" ng-click="remove(profile)"></button>

{{profile.basic.display_name }}

23 yrs, 5'4", Gujarati, Hindu Mumbai, India

            <button class="discover_connect_btn btn btn-lg " ng-click="connect(profile)" ng-if="member">Connect</button>

The below is my controller code snippet:-
AppControllers.controller('ProfileListCtrl', ['$scope', 'ProfileData', '$timeout', function($scope, ProfileData, $timeout) {

    //Profile data above is a factory created to connect with the discovery.json
    var promise = ProfileData.query();
    promise.$promise.then(function(response) {

        $scope.profile = response.data;
   //     console.log($scope.profile);
        var profile = $scope.profile;
        for (i = 0; i < profile.length; i++) {

           // console.log(data[0].account.membership)
            profile[i]["show"] = true;
           // console.log(profile[i]);
            //console.log(profile[i].account.membership)

            if(profile[i].account.membership == "free")
                {
                    console.log("This account is free");
                    $scope.member=true;
                }
            else if(profile[i].account.membership == "premium")
                {
                    console.log("This acocunti snot");
                    $scope.member=false;
                }
            else
            {
             console.log("unknown member")
            }

        }

        $scope.alert_message = "Sorry! You don't have any Shortlisted Profile to check";
        $scope.seeAllUrl = "member_who_shortlisted_you";
        // Get the size of an object
        var totalNumberOfProfile = profile.length;

        //console.log(totalNumberOfProfile);
        $scope.totalNumberOfProfile = totalNumberOfProfile;
        $scope.categoryOfProfile = "Member Who Shortlisted You";

Now I want to change the button depending upon the account membership I am getting from the json file..
By default it is Connect but have three more button for different conditions..
I have tried to use ng-if and getting stuck up and have no clue how to change the button based on the data..
I am a newbie on angular..please help me out..Thanks

A: If you want a quick fix, Use 'if' conditions like the following

 <button>Button_1</button>

 <button>Button_2</button>

A: If you have more then one condition for your button user "ng-switch":
<ANY ng-switch="expression">
 < <ANY ng-switch-when="matchValue1">...</ANY>
  <ANY ng-switch-when="matchValue2">...</ANY>
  <ANY ng-switch-default>...</ANY>
</ANY>

angular docs: https://docs.angularjs.org/api/ng/directive/ngSwitch

A: As suggested earlier, you can use ng-switch.
Live example on jsfiddle.
<form name="ExampleForm" id="ExampleForm">
 <select ng-model="condition">
 <option value="1">Condition one</option>
 <option value="2">Condition two</option>
 <option value="3">Condition three</option>
 </select>

   <button ng-switch-when="1">
    Condition one!
   </button>
   <button ng-switch-when="2">
    Condition two!
   </button>
   <button ng-switch-when="3">
    Condition three!
   </button>

</form>

UPDATED
Live example on jsfiddle.
<form name="ExampleForm" id="ExampleForm">

    Yor profile is {{profile.account.membership}}

      <button ng-switch-when="free">
        free profile!
      </button>
      <button ng-switch-when="premium">
        premium profile!
      </button>
      <button ng-switch-when="unknow">
        unknow profile!
      </button>

</form>

And JS
.controller('ExampleController', function($scope) {
$scope.condition = '1';
$scope.profiles = [{
  account: {
    membership: "free"
  }
},
{
  account: {
    membership: "premium"
  }
},
{
  account: {
    membership: "unknow"
  }
}];});


text:
Q: A Temperate Fundamental Solution of a PDE Let
\begin{equation}
P(\xi)=\xi_{1}^2 \xi_{2}^2 + \xi_{3}^2 + i \xi_{4},
\end{equation}
and consider the partial differential operator
\begin{equation}
P(D)=\left( -i \frac{\partial}{\partial x_1},\dots, - i \frac{\partial}{\partial x_4} \right).
\end{equation}
Hörmander (The Analysis of Linear Partial Differential Operators, Vol. II, Example 10.2.15) states that
\begin{equation}
E(x) = \begin{cases} (2 \pi)^{-3} \int \exp[i(x_1 \xi_1+x_2 \xi_2 + x_3 \xi_3)) - x_4 (\xi_{1}^2 \xi_{2}^2 + \xi_{3}^2)] d\xi_{1} d \xi_{2} d \xi_{3} & \textit{ if } x_4 > 0, \\
0 & \textit{if } x_4 \leq 0 \end{cases}
\end{equation}
is the unique temperate fundamental solution of the operator $P(D)$.
There are two big flaws for me in this sentence.
(i) Hörmander's statement about the uniqueness is for sure false, since $P$ has real zeros. So for example, if $T$ is a temperate fundamental solution, e.g. $T + c_0 + c_1 x_1$ is too, for any $c_0, c_1 \in \mathbb{C}$.
(ii) The most relevant fact is that $E(x)$ is not even well-defined for $x_4 > 0$. Indeed, we have
\begin{equation}
\int_{\mathbb{R}^3} \exp \left( - x_4 \left(\xi_{1}^{2} \xi_{2}^{2} + \xi_{3}^{2} \right) \right) d \xi_\ d \xi_2 d \xi_3 = \int_{\mathbb{R}} \frac{\pi}{x_4 |\xi_1|} d \xi_1 = \infty.
\end{equation}
It seems very strange to me that such a great mathematician like Hörmander made two big mistakes like these in the same sentence. What do you think about?
Thank you very much for your attention.
NOTE. Hörmander uses this example of partial differential operator to show that there are partial differential operators which do not admit a "regular" temperate fundamental solution (for the definition of "regular solution", see Hörmander, The Analysis of Linear Partial Differential Operators, Vol. II, Definition 10.2.2). Actually, his proof that the differential operator $P(D)$ defined above does not admit a regular temperate fundamental solution is correct and has nothing to do with the statement above.

A: Let for simplicity $x=(x_1,x_2,x_3)$, similarly for $\xi$.
Let also $Q(\xi) = \xi_1^2\xi_2^2+\xi_3^2$ and define accodringly $Q(D)$.
Consider now the equation $$P(D)u(x,x_4) = Q(D)u(x,x_4) + \partial_{x_4}u(x,x_4) = 0.$$ Note that $Q(D)$ does not act on $x_4$.
Fourier transfrom with respect to $x$ will give us
$$Q(\xi)\hat u(\xi,x_4)  +\partial_{x_4}\hat u(\xi,x_4) = 0,$$
with the obvious solution
$$\hat u(\xi,x_4) = C\exp( - x_4 Q(\xi)).$$
for positive $x_4$ this function is bounded, hence temperate.
If you multiply it by $H(x_4)$ (the Heavyside function) and put $C=1$, you obtain a globally bounded function (hence temperate on $\Bbb R^4$) that solves the equation $$
Q(\xi)\hat u(\xi,x_4)  +\partial_{x_4}\hat u(\xi,x_4) = \delta_{x_4}.
$$
The inverse Fourier transform of the right hand side would give you $\delta_0$, and the inverse FT of $H(x_4) \exp( - x_4 Q(\xi))$ gives the expression for $E(x)$
 that you provided. As the inverse FT is map from $S'\to S'$, we conclude that $E\in S'$, even though the provided integral might not not converge in the usual sense.
For the unicity part, maybe he meant "vanishing on infinity"?

A: This is not a separate answer, but only a long comment to Zakreveskiy's answer.
For sure Zakreveskiy's answer shows how the solution $E$ can be found "formally", but it is cleary not a proof of the fact that $E$ is a temperate fundamental solution of $P(D)$, since we cannot take Fourier transform of distributions "only with respect to some variables". But now I understood what Hörmander meant: the rigorous definition of $E$ is the following:
\begin{equation}
E(\phi)= \int_{\mathbb{R}^4} H(x_4) \exp(-x_4 Q(\xi)) \left( \int_{\mathbb{R}^3} \exp(i \xi \cdot x) \phi(x,x_4) dx \right) d \xi d x_4
\quad (\phi \in \mathcal{S}(\mathbb{R}^4)).
\end{equation}
By using simple inequalities (see e.g. the proof of Theorem (10.2) in Blanchard and Brüning, Mathematical Methods in Physics) we see that the map
\begin{equation}
\phi(x,x_4) \in \mathcal{S}(\mathbb{R}^4)  \mapsto \psi(\xi,x_4)=\int_{\mathbb{R}^3} \exp(i \xi \cdot x) \phi(x,x_4) d x
\end{equation}
is a linear continuous map from $\mathcal{S}(\mathbb{R}^4)$ into $\mathcal{S}(\mathbb{R}^4)$.
So the map $E$ defined above is actually a tempered distribution. By using the definition of $E$ and the properties of Fourier transforms on $\mathcal{S}(\mathbb{R}^3)$  it is a plain exercise to give a rigorous proof that $P(D)E=\delta_{0}$. Indeed we have for each $\phi \in \mathcal{S}(\mathbb{R}^4)$ (note that all the monomials of $Q$ have even degree):
\begin{multline}
(P(D)E)(\phi)= E \left[Q(D)\phi - \frac{\partial \phi}{\partial x_4} \right] = \\ = \int_{\mathbb{R}^4} H(x_4)\exp(-x_4 Q(\xi)) \left( \int_{\mathbb{R}^3} \exp(i \xi \cdot x) \left[(Q(D)\phi)(x,x_4) - \frac{\partial \phi}{\partial x_4} (x,x_4) \right] dx \right) d \xi d x_4 = \\ = \int_{\mathbb{R}^4} H(x_4)\exp(-x_4 Q(\xi)) \left[ Q(\xi) \psi(\xi,x_4)-
\frac{\partial \psi}{\partial x_4}(\xi,x_4) \right] d \xi d x_4 = \\
= \int_{\mathbb{R}^3} \left( \int_{0}^{\infty} \exp(-x_4 Q(\xi)) \left[ Q(\xi) \psi(\xi,x_4)-
\frac{\partial \psi}{\partial x_4}(\xi,x_4) \right] d x_4 \right)d \xi = \\
= \int_{\mathbb{R}^3} \left( \int_{0}^{\infty} \left[ - \frac{\partial (\exp(-x_4 Q(\xi))}{\partial x_4} \psi(\xi,x_4) - \exp(-x_4 Q(\xi))
\frac{\partial \psi}{\partial x_4}(\xi,x_4)  \right] d x_4 \right) d \xi = \\
= \int_{\mathbb{R}^3} \left( \int_{0}^{\infty} - \frac{\partial [\exp(-x_4 Q(\xi))\psi]}{\partial x_4}   d x_4 \right) d \xi = \\
= \int_{\mathbb{R}^3} \psi(\xi,0) d \xi = \int_{\mathbb{R}^3} e^{-i 0 \cdot \xi} \psi(\xi,0) d \xi = \phi(0),
\end{multline}
where the last passage derives from the Inversion Theorem.
As for the "uniqueness" issue, I don't think Hörmander meant something about the behavior at infinity, otherwise he would have explicitly stated what he precisely meant (hi style was incredibly precise). I think this was only a slip of tongue and the reason why I think so is the following. In the notes to Chapter X of The Analysis of Linear Partial Differential Operators, Vol. II, he says that Example 10.2.15 is taken from On Fundamental Solutions.
Actually Enqvist at p.29 gives an example of a partial differential operator $P(D)$ which has no real zeros, so that there is only one temperate fundamental solution of the operator $P(D)$ and he proves that this solution is not "regular". But this is not the example 10.2.15 of Hörmander! It is very likely that Hörmander included Enqvist's example in a first draft of his masterpiece, but then for some reason he changed his mind and decided to give another example, while the sentence "unique tempered fundamental solution" remain unchanged by a simple distraction.


text:
Q: The irreduciblity of $X^{2r}-X^{r}+1$ The question is that $e^{2\pi i/6r}$ is a root of the polynomial $X^{2r}-X^{r}+1 \in \mathbb Q[X]$ , we want to prove that $X^{2r}-X^{r}+1$ is irreducible if and only if $r$ is of the form $2^{a}3^{b}(a,b\geq 0)$, and the following question $X^{2r}+X^{r}+1$ is irreducible if and only if $r$ is of the form a power of $3$.

A: Note that
$$X^{2r}-X^r+1=\frac{X^{3r}+1}{X^r+1}=\frac{X^{6r}-1}{(X^r+1)(X^{3r}-1)}$$
$\Rightarrow$
Assume by contradiction that $r$ has a prime factor $p \geq 5$.  Let $r=pq$. Then
$e^{\frac{2 \pi i }{6q}}$ is a root of $X^{6r}-1$ but not of $(X^r+1)(X^{3r}-1)$.
This shows that the minimal polynomial of $e^{\frac{2 \pi i }{6q}}$ divides $X^{2r}-X^r+1$. Since the degree of the minimal polynomial is $\phi(6q) \neq 2r$, it follows that the minimal polynomial of $e^{\frac{2 \pi i }{6q}}$ is a proper divisor of $X^{2r}-X^r+1$.
$\Leftarrow$
If $r=2^a3^b$. It should be easy to prove from
$$X^{2r}-X^r+1=\frac{X^{6r}-1}{(X^r+1)(X^{3r}-1)}$$
that $X^{2r}-X^r+1$ is a cyclotomic polynomial. Note that
$$\phi(6r)=2^a\cdot 3^b \cdot 2=2r=6r-r-3r=\deg(X^{6r}-1)-\deg(X^r+1))-\deg(X^{3r}-1)$$
The second part should follow by the same idea, using
$$X^{2r}+X^r+1=\frac{X^{3r}-1}{X^r-1}$$

A: In general, the degree of the minimal polynomial for $e^{\frac{2\pi i}n}$ is $\phi(n)$. So if $x^{2r}-x^r+1$ is irreducible, then $2r=\phi(6r)$. Write $r=2^a3^bD$ with $(6,D)=1$. Then $$2r = \phi(6r)=\phi(2^{a+1})\phi(3^{b+1})\phi(D)=2^a(2-1)3^b(3-1)\phi(D) = 2r\frac{\phi(D)}D$$
So $\phi(D)=D$, so $D=1$.
For the second case, $e^{\frac{2\pi i}{3r}}$ is a root, so for $x^{2r}+x^r+1$ to be irreducible, $2r=\phi(3r)$.  Write $r=3^aD$ with $(D,3)=1$.
Then $2r = \phi(3r)=\phi(3^{a+1}D)=(3-1)3^a\phi(D) = 2r\frac{\phi(D)}D$, and again $D=1$.

A: This solution requires familiarity with Cyclotomic polynomials, specfically their irreducibility. I will factor $x^{2r}-x^{r}+1$ completely.
As N.S. observed, $$x^{2r}-x^{r}+1 = \frac{x^{3r}+1}{x^r+1}=\frac{x^{6r}-1}{x^{3r}-1}\frac{x^r-1}{x^{2r}-1}$$
Remember that $\prod_{d|n} \phi_d(x) = x^n-1$, thus:
$$x^{2r}-x^{r}+1 = \frac{\prod_{d|6r} \phi_d(x)}{\prod_{d|3r} \phi_d(x)}\frac{\prod_{d|r} \phi_d(x)}{\prod_{d|2r} \phi_d(x)}$$
Most of the terms cancel -
$$\frac{\prod_{d|6r} \phi_d(x)}{\prod_{d|3r} \phi_d(x)} = \prod_{d|6r, d\nmid 3r} \phi_{d}$$
$$\frac{\prod_{d|r} \phi_d(x)}{\prod_{d|2r} \phi_d(x)} = \frac{1}{\prod_{d|2r, d\nmid r} \phi_{d}}$$
So
$$x^{2r}-x^{r}+1 = \prod_{d|6r,d\nmid 3r,(d|r \text{ or } d\nmid 2r)} \phi_{d}(x)$$
When $r=3^a 2^b$, the unique positive integer satisfying the three conditions $d|6r,d\nmid 3r,(d|r \text{ or } d\nmid 2r)$ is $d=6r$ itself - the condition $d|6r,d\nmid 3r$ requires that $d$ is divisible by the maximal power of $2$ dividing $6r$, so $d=2^{b+1}3^{k \le a+1}$. $d$ can't divide $r$, so it must not divide $2d$, provided $k\ge a+1$, i.e. $k=a+1$. Thus $x^{2r}-x^r+1 = \phi_{6r}(x)$.
When $r$ is not a product of a power of 2 and a power of 3, $d=6r$ appears in the product, but also any $\frac{6r}{q}$ where $q$ divides $r$ but $(q,2)=(q,3)=1$:
$$x^{2r}-x^{r}+1 = \prod_{d=6r/q,q|r,(q,6)=1} \phi_{d}(x)$$
(this formula is always valid.) If we write $r=2^{a}3^{b}r', (r',6)=1$, we find that the number of factors in the factorization of the polynomials equals the number of divisors of $r'$.
EDIT:
In general, by using $\phi_{n} (x) = \prod_{d|n} (x^d - 1)^{ \mu (n/d) }$, one can show:
$$\phi_{n}(x^m) = \prod_{d|m,(d,n)=1} \phi_{nm/d}(x) $$
So $\phi_{n}(x^m)$ is irreducible iff $p|m \implies p |n$, in which case $\phi_{n}(x^m) = \phi_{nm}(x)$.
To prove the last statement (without using my identity), notice that $\phi_{n}(x^m)$ must be divisible by $\phi_{nm}(x)$, and by comparing degrees as in the other solutions, to have equality we must have $m\phi(n)=\phi(nm)$, i.e. $nm \prod_{p|n}(1-\frac{1}{p}) = nm\prod_{p|nm}(1-\frac{1}{p})$, or $\prod_{p|nm, p \nmid n} (1-\frac{1}{p}) = 1$, which is equivalent to $p|m \implies p|n$.


text:
Q: Which field matched query in multi_match search in Elasticsearch? I have  query with multi_match in Elasticsearch:
{
  "query": {
    "multi_match": {
      "query": "luk",
      "fields": [
        "xml_string.autocomplete",
        "state"
      ]
    }
  },
  "size": 10,
  "fields": [
    "xml_string",
    "state"
  ]
}

It works great, result returns expected value:
{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.41179964,
    "hits": [
      {
        "_index": "documents",
        "_type": "document",
        "_id": "11",
        "_score": 0.41179964,
        "fields": {
          "xml_string": "Lukas bla bla bla",
          "state": "new"
        }
      }
    ]
  }
}

I've searched a lot, but I am not able to find out which field matched the query(if it was xml_string OR state)

A: I have found solution: I have used highlight feature and it's working great
This is how my curl looks like:
 curl -X GET 'http://xxxxx.com:9200/documents/document/_search?load=false&size=10&pretty' -d '{
    "query": {
        "multi_match": {
            "query": "123",
            "fields": ["some_field", "another_field"]
        }
    },
    "highlight": {
        "fields": {
            "some_field": {},
            "another_field": {}
        }
    },
    "size": 10,
    "fields": ["field","another_field"]
}'

A: As far as I know there is no feature for telling you which field has matched the query.
But you can use the explain feature for debugging your query. You only have to add to your query the pamameter &explain=true. With this parameter you will see an explanation for each field of why it is in the result set and you will guess which field matched the query.


text:
Q: ValueError: Math domain error (for a 2nd grade equation function) I've tried to solve the problem myself but i cant. Its a function in order to solve 2nd grade equations when y=0 like 'ax2+bx+c=0'. when i execute it it says me there is math domain error. if u can help me it will be nice thx.
a=raw_input('put a number for variable a:')
b=raw_input('put a number for variable b:')
c=raw_input('put a number for variable c:')

a=float(a)
b=float(b)
c=float(c)`

import math

x=(-b+math.sqrt((b**2)-4*a*c))/2*a
print x`

x=(-b-math.sqrt((b**2)-4*a*c))/2*a`
print x

PD:im starting with python so im quite a disaster sorry.

A: The issue here is that the standard math library in python cannot handle complex variables. The sqrt you've got up there reflects this.
If you want to handle a function that could have complex variables (such as the one above) I would suggest using the cmath library, which has a replacement cmath.sqrt function.
You could change your above code to the following:
from cmath import sqrt

a = raw_input('put a number for variable a:')
b = raw_input('put a number for variable b:')
c = raw_input('put a number for variable c:')

a = float(a)
b = float(b)
c = float(c)`

x = (-b + sqrt((b**2) - 4 * a * c)) / 2 * a
print x`

x = (-b - sqrt((b**2) - 4 * a * c)) / 2 * a`
print x

and it should fix your problem (I also made some edits to make the code look a little more pythonic (read: pep8 compliant))

A: First, it's worth noting that in "2nd grade math", that equation doesn't have a solution with the values you (presumably) entered.* When you get to high school math and learn about imaginary numbers, you learn that all quadratic equations actually do have solutions, it's just that sometimes the solutions are complex numbers. And then, when you get to university, you learn that whether or not the equations have solutions depends on the domain; the function to real numbers and the function to complex numbers are different functions. So, from either a 2nd-grade perspective or a university perspective, Python is doing the right thing by raising a "math domain error".
* Actually, do you even learn about quadratic equations before middle school? That seems a bit early…

The math docs explain:

These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don't is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.

But there's another reason for this: math was specifically designed to be thin wrappers around the standard C library math functions. It's part of the intended goal that you can take code written for another language that uses C's <math.h>, C++'s <cmath>, or similar functions in Perl, PHP, etc. and have it work the same way with the math module in Python.

So, if you want the complex roots, all you have to do is import cmath and use cmath.sqrt instead of math.sqrt.

As a side note: In general, the operators and other builtins are more "friendly" than the functions from these modules. However, until 3.0, the ** operator breaks this rule, so ** .5 will just raise ValueError: negative number cannot be raised to a fractional power. If you upgrade to 3.x, it will work as desired. (This change is exactly like the one with integer division giving a floating-point result, but there's no __future__ statement to enable it in 2.6-2.7 because it was deemed to be less of a visible and important change.)


text:
Q: How to open url from table cells in webview iOS I have just figured out how to make a tabbed navigation controller open in two table views. I would like to be able to click on one of the table cells (6 on a page), and for this to open the url in a webview.
This is my code:
 #import "FlashTopicsEViewController.h"
#import "ADVTheme.h"

@implementation FlashTopicsEViewController
@synthesize webView;

NSArray *flashtopicsEth;
NSArray *urlLinks;

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.;

self.view.backgroundColor = [ADVTheme viewBackgroundColor];
self.view.tintColor = [UIColor whiteColor];

flashtopicsEth = [NSArray arrayWithObjects:@"Topic1",@"Topic2", nil];
urlLinks = [[NSArray alloc] initwithObjects:@"http://url1.com", @"http://url2.com",nil];
 webView.delegate = self;

NSURL *URL = [NSURL URLWithString: urlLinks[indexPath.row]];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:URL];
[webView loadRequest:requestObj];
}

and this is the code below it:
 - (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
static NSString *simpleTableIdentifier = @"FlashTopicECell";

UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
   reuseIdentifier:simpleTableIdentifier];
}
UIImage *image1 = [UIImage imageNamed:@"flashImage.png"];
cell.imageView.image = image1;

cell.textLabel.text = [flashtopicsEth objectAtIndex:indexPath.row];
return cell;
}

and this is what I have in my .h file
#import <UIKit/UIKit.h>

@interface FlashTopicsEViewController : UIViewController

@property NSArray *urlLinks;
@property NSArray *flashtopicsEth;

@property (nonatomic,strong) IBOutlet UIWebView *webView;

@end

A: @matt is right, this is beyond trivial to do lol :) But anyway, what you need to do is to make use of one of UITableView's delegate methods called "didSelectRowAtIndexPath". This will detect when a cell is tapped:
Your question is very basic and not detailed, so for the purposes of this basic answer, I am going to declare a UIWebView in the header file and then use that. You will need to add it to your ViewController and link it up. I also do NOT know how you are storing your URLs, I presume you are using an array? Well for the purposes of this answer, I will too.
IBOutlet UIWebView *websiteView;
NSArray *urlLinks;

Now on to the implementation code:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     // Get the cell number that was tapped and then
     // use that to access your array of URLs.
     // Then pass that URL to a UIWebView.
     NSURL *URL = [NSURL URLWithString:urlLinks[indexPath.row]];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:URL];
     [websiteView loadRequest:requestObj];
}

Also in the viewDidLoad, set the webview delegate like so:
websiteView.delegate = self;

Update - In answer to your comments
Ok so in my answer I just assumed you are using an array for the list of URLs. But there are other ways too. You don't have to use an array if you don't want to.
As to how you populate the array? Well that depends on quite a few things:
1) Are you downloading a list of URLs from a server?
2) Are you setting the list of URLs in your code?
If you are doing option 1, then you are probably parsing something like a JSON file which you are downloading from a server. In this case you may want to use something a long the lines of:
urlLinks = [[feed objectForKey:@"items"] valueForKey:@"url"];

The above code will put all the url links into your array. (This is just a very tiny snippet - not the whole code - just to give you an idea).
If you are going with option 2, so you already know the list of URLs and you want to define them in your app, then just do this:
NSArray *urlLinks = [[NSArray alloc] initwithObjects:@"http://url1.com", @"http://url2.com", ...etc.... , nil];

Right so to then access the URLs, you need to basically get the string from the correct array object and then turn that into an NSURL and then pass that to your webview like so:
 NSURL *URL = [NSURL URLWithString:urlLinks[indexPath.row]];
 NSURLRequest *requestObj = [NSURLRequest requestWithURL:URL];
 [websiteView loadRequest:requestObj];

Lastly, how you present your UIWebView is up to you. It doesn't have to be in a seperate ViewController if you dont want it to. Thats up to you. But if you do, then yes, the next bit is to present the next view controller on screen. Just remember you will have to pass your URL to it, if you want the UIWebView in that view controller to present your website.
Update 2 - in answer to your question/code
Ok there are a few things wrong with your code:

*

*Get rid of the "etc...." bit in your array declaration.... Lol I only added that to help you understand how to populate the array. So it should really be:
flashtopicsEth = [NSArray arrayWithObjects:@"Topic1",@"Topic2", nil];

*You have just randomly inserted your array code in your implementation (.m) file.... that's not where you put it. You can insert it in methods such as the viewDidLoad or other methods that you make yourself. You can't just randomly add it wherever you feel like. So for the purposes of keeping things simple, lets start with just assigning the arrays in the viewDidLoad like so:
-(void)viewDidLoad {

[super viewDidLoad];
// Do any additional setup after loading the view.

flashtopicsEth = [NSArray arrayWithObjects:@"Topic1", @"Topic2", nil];
urlLinks = [[NSArray alloc] initwithObjects:@"http://url1.com",@"http://url2.com", nil];

webView.delegate = self;

NSURL *URL = [NSURL URLWithString: urlLinks[indexPath.row]];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:URL];
[webView loadRequest:requestObj];

}

*Declare your NSArray's in your header file and assign them in the implementation (.m) file. Don't declare them in the viewDidLoad because they will then be local to the viewDidLoad and the other UITableView methods will not be able to access them unless your pass the array to them. For the purposes of keeping things simple (as you are a beginner), just declare them like this in your header (.h) file:
#import <UIKit/UIKit.h>
   @interface FlashTopicsEViewController : UIViewController {

    NSArray *flashtopicsEth;
    NSArray *urlLinks;
}

@property (nonatomic,strong) IBOutlet UIWebView *webView;

@end


text:
Q: bad_alloc with pointers, references and values I'm actually very new to c++. I tried to write a function template, passing a parameter as reference.
While doing so I got a std::bad_alloc. So I also tried to pass it as value and even by pointer. I always got a std::bad_alloc, but I'm very sure, the object exists and the adress is correct (checked it with debugger).
My last try was to create the object right in the function. It works, if I use hard-coded data, but not if I pass the data, needed to create the object, as function parameter.
I'm using a specific framework for numeric simulation (http://www.dune-project.org/), so I'm not sure, if example code is helpfull. I just contacted the framework support and they had no idea, where this problem comes from.
I hope anyone could help me or has an idea, how to fix this/work arround!
code example:
 template<const int dim, const int k>
int solvePoissonPDE2(int maxlevel, Dune::YaspGrid<dim>& grid)
{
    /*
    * Debugging Notes:
    * function works, if grid, fieldvector, array AND bitset are created inside the function
    * BUT NOT if grid OR the components used to create a grid are passed as reference, value or pointer parameters (SEGMENTATION FAULT)
    */
    try {

        /*// make grid
        Dune::FieldVector<double, dim> L(1.0);
        Dune::array<int, dim> N(Dune::fill_array<int, dim>(1));
        std::bitset<dim> B(false);
        Dune::YaspGrid<dim> grid(L, N, B, 0);*/
        grid.globalRefine(maxlevel - 1);

        // get view
        using GV = typename Dune::YaspGrid<dim>::LeafGridView;
        const GV &gv = grid.leafGridView();

        const int q = 2 * k;
        // make finite element map
        using DF = typename GV::Grid::ctype;
        using FEM = Dune::PDELab::QkLocalFiniteElementMap<GV, DF, double, k>;
        FEM fem(gv);

        BCTypeParam bctype;
        // solve problem
        using Constraints = Dune::PDELab::ConformingDirichletConstraints;
        poisson_driver<GV, FEM, BCTypeParam, Constraints>(gv, fem, "poisson_yasp", bctype, false, q);

        return 0;
    }
    catch (Dune::Exception &e){
        std::cerr << "Dune reported error: " << e << std::endl;
        return false;
    }
    catch (std::string &e){
        std::cerr << "An error has been detected: " << e << std::endl;
        return false;
    }
    catch (std::exception &e){
        std::cerr << "STL reported error: " << e.what() << std::endl;
    }
    catch (...){
        std::cerr << "Unknown exception thrown!" << std::endl;
        return false;
    }

}

all used functions are working and are tested.


text:
Q: Using Castle Windsor with FluentValidation In MVC I'm working on getting FluentValidation working with Castle Windsor.  I already have a wrapper around Castle Windsor.  Here is the code for that:
public class ResolveType
{
    private static IWindsorContainer _windsorContainer;

    public static void Initialize( IWindsorContainer windsorContainer )
    {
        _windsorContainer = windsorContainer;
    }

    public static T Of<T>()
    {
        return _windsorContainer.Resolve<T>();
    }
}

I am trying to build the FluentValidation factory as is explained at http://www.jeremyskinner.co.uk/2010/02/22/using-fluentvalidation-with-an-ioc-container
The article uses StructureMap, but I thought I could adapt it to Castle Windsor like this:
public class CastleWindsorValidatorFactory : ValidatorFactoryBase
{

    public override IValidator CreateInstance( Type validatorType)
    {
        return ResolveType.Of<validatorType>();
    }
}

Notice, I'm just trying to call into my wrapper so that Windsor can resolve the type reference.
The problem is that this doesn't compile.  I get 'The type or namespace name 'validatorType' could not be found (are you missing a using directive or an assembly reference?)'
How can I make this work?

A: Add this method to your ResolveType class:
public static object Of(Type type) {
  return _windsorContainer.Resolve(type);
}

Then in your CastleWindsorValidatorFactory:
public class CastleWindsorValidatorFactory : ValidatorFactoryBase {
    public override IValidator CreateInstance(Type validatorType) {
        return ResolveType.Of(validatorType) as IValidator;
    }
}


text:
Q: Automatic brightness missing from settings in Ubuntu 20.04 I'm running Ubuntu 20.04 on my Thinkpad T495s and I wanted to enable adaptive brightness. However, the automatic brightness is missing from my Settings/Power.

I tried to google and found this article which mentioned using  gsettings set org.gnome.settings-daemon.plugins.power ambient-enabled true
to enable automatic brightness but it doesn't seem to work.
Any ways to fix the system settings? I'm also open to using third-party apps if I can't use the system settings.


text:
Q: java generic class cast Hello i have got hash map with value:
    private static final LinkedHashMap<Class<? extends Annotation> , Class<? extends AGenerator<?>>> annotationGeneratorMap = new LinkedHashMap<Class<? extends Annotation>, Class<? extends AGenerator<?>>>();

and my numeric Generator looks like :
public abstract class NumericGenerator<T extends Number> extends AGenerator<T>{

public NumericGenerator(Field field) {
    super(field);
    // TODO Auto-generated constructor stub
}

public T random() {
    // TODO Auto-generated method stub
    return null;
}

  }

And i have got problem when i need to put this class into hashmap :
annotationGeneratorMap.put(GenerateNumeric.class, NumericGenerator.class);

And in eclipse i have got error the method is not applicable for the argument ???
but :
        annotationGeneratorMap.put(GenerateNumeric.class, (Class<? extends AGenerator<?>>) NumericGenerator.class);

and @SuppressWarnings("unchecked") is good ..:/
Can i do this without casting ?? (Class<? extends AGenerator<?>>) NumericGenerator.class

A: use Class<? extends AGenerator> instead
LinkedHashMap<
    Class<? extends Annotation>,
    Class<? extends AGenerator> > annotationGeneratorMap = new LinkedHashMap<>()

In Java, class can represent a raw type, but cannot represent a generic type.
There is a class for List, but there is no class for List<String>.
So you can declare Class<? extends List>, which is compatible with ArrayList.class etc. because raw type ArrayList is a subtype of List.
But Class<? extends List<?>> doesn't make much sense, because there is no class that is a subtype of List<?>.
And all thanks to erasure.

A: Compile time check won't allow you to do that unless you cast it of course.
Information about generic types is lost at runtime, not compile time.

A: Following compiles without error on version 1.7.0_02:
import java.util.*;
import java.lang.annotation.*;

interface AGenerator<T> {}

interface A extends Annotation {}
class X implements AGenerator<X> {}

class E7 {
    private static final LinkedHashMap<Class<? extends Annotation>,
        Class<? extends AGenerator<?>>> annotationGeneratorMap
        = new LinkedHashMap<Class<? extends Annotation>,
                            Class<? extends AGenerator<?>>>();

    void foo() {
        annotationGeneratorMap.put(A.class, X.class);
    }

}


text:
Q: Ununderstood Tutte's theorem proof I am reading Tutte's theorem proof:
(The part which I don't understand follows).
We have a graph $G$ with vertices $x,a,b,c\in V(G)$ s.t. $ac,xb\notin E(G)\ni xa,ab$. We are given that $G$ hasn't a perface matching but $G+xb$ has a perfact matching $M_1$ with $xb\in M_1$ and $G+ac$ has a perfact matching $M_2$ with $ac\in M_2$.
In the proof, a path $P$ is defined to be a maximal path that starts from $c$ such that $P$ is altermating between edges from $M_1$ and edges from $M_2$.
I don't understand why if $P$ ends up with an edge from $M_2$ then necesserily the last vertex in $P$ has to be $x$ or $b$.

A: Note that $P$ is a path in $G$. I.e., it is not allowed to use either of the added edges $xb$ or $ac$.
$P$ starts at $c$. It is not allowed to follow $ac$, which is the edge connecting to $c$ in $M_2$, so it has to instead use the edge for $c$ from $M_1$. For any vertex $v$ other than $a,b,c,x$, when it arrives at $v$ by the edge from $M_1$, it can leave by the edge from $M_2$, and if it arrives by the edge from $M_2$ it can leave by the edge from $M_1$. There is nothing to stop $P$ from continuing at any of these vertices.
But with $a, c, b$ or $x$, things are different. It cannot arrive at $a$ or $c$ by an edge in $M_2$, because the edge for these points is $ac$, which is not in $G$. So it arrives at $a$ by an edge in $M_1$, and must leave by the edge in $M_2$. But that is $ac$, and $P$ cannot follow it. So $P$ stops. Similarly, $P$ can only arrive at $x$ or $b$ by an edge in $M_2$, and must leave by $M_1$, i.e., by $xb$, which is not in $G$. Again, it must stop.
Finally, note that once $P$ visits a vertex, it can never visit it again. Suppose otherwise. Let $v$ be the first vertex that $P$ visits twice. $v \ne c$, since the only way $P$ can reach $c$ a second time is by its $M_1$ edge. Let $u$ be the vertex on the other side of that edge. In order to take $uc$ to $c$, $P$ has to visit $u$ a second time, so $c$ cannot be the first. But then $u$ cannot be the first repeat visit either, since $P$ cannot reach $u$ again from its $M_1$ edge $uc$, since it cannot have visited $c$, and it cannot reach $u$ again from its $M_2$ edge, since the other vertex for that edge would have to be visited twice before $u$. This same logic recursively shows that no vertex can on $P$ can be the first visited twice. Therefore $P$ can never visit a vertex twice, and since it started out at $c$, $c$ cannot be its ending place.
Thus the only possible places that $P$ can end are $a, b, x$. (And note that contrary to your post, the proof does allow $a$ as a possible ending place.) And since $P$ cannot cycle, and cannot stop anywhere else, it has to encounter one of them.


text:
Q: How many ContentProvider? In my application I access drectly to database through a SQLiteOpenHelper object.
Now I want to use ContentProviders. In the database I have 14 tables and 6 views. What is the best practice between the following?

*

*One Content Provider to access all tables and views

*One Content Provider for each tables and views (total 20 Content Providers)

*One Content Provider for each group of tables and views (totale 5/6 Content Providers)

A: One content provider to access all the tables and views in a database. Content Provider is a abstraction for application to share data with other applications. One Content Provider for a database should be the approach.


text:
Q: Approximate the integral $\int_0^{0.5}{x^2e^{x^2}}dx$ correct to four decimal places using a Maclaurin series. I got $$\int_0^{0.5}{\sum_0^\infty}\frac{x^{2n+2}}{n!}dx$$ for the taylor series representation, but I'm not sure what to do next.
Do I use 0 and 0.5 as bounds for z for the Lagrange Error Bound? And what does the remainder have to be less than for it to be correct to 4 decimal places?

A: I took the integral and did trial and error with x = 0.5 (the whole thing = 0 when x = 0) until I got a term that was less than 0.0001. It requires 3 terms, or n = 3.

A: Integrating gives $$\sum_{n=0}^\infty\frac{2^{-n-3}}{n!(2n+3)}$$  If we drop all the terms before $n=k$ the remainder is
$$2^{-3}\sum_{n=k}^\infty\frac{4^{-n}}{n!(2n+3)}<\frac{2^{-3}}{k!(2k+3)}\frac{4^{1-k}}{3}$$
No doubt one can do something more sophisticated, but this ought to be good enough.


text:
Q: I want to use href to decide which modal needs to be toggled open I have two modal with id="detailsModal" and id="messageModal". Depending on the response I receive from the backend, I set the value for errorMessage which in case of no error is null. Depending on this, I wish to decide the href. I have used the following code to do so, but it is not working.
href="{{errorMessage === null ? '#detailsModal' : '#messageModal'}}"

A: You could do this with ng-template and NgIf. https://angular.io/api/common/NgIf
You can do this with your error:
<div *ngIf="errorMessage === null; then thenBlock; else elseBlock">this is ignored</div>
<ng-template #thenBlock>Then text to show</ng-template>
<ng-template #elseBlock>Else text to show</ng-template>


text:
Q: HTML upload file directory does not exist I am attempting to upload a file using an HTML form and php, the code goes like this:
$targetPictureLocation = "/files/images/team/" . strtolower(str_replace(" ","", $_POST['name'])) . ".png";
move_uploaded_file($_FILES['file']['tmp_name'], $targetPictureLocation);

Now I believe the $targetPictureLocation refrences www.domain.com/targetpath/ because there is a slash infront of files.  Is this proper?  If so then the directory does exist however I am getting these errors:
Warning: move_uploaded_file(/files/images/team/foobar.png) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/content/08/11798508/html/domainname/files/scripts/userManagement.php on line 259

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpwzO4X7' to '/files/images/team/foobar.png' in /home/content/08/11798508/html/domainname/files/scripts/userManagement.php on line 259

What am I doing wrong?
Thank you so much

A: Try :
$targetPictureLocation = $_SERVER['DOCUMENT_ROOT']."/domainname/files/images/team/" . strtolower(str_replace(" ","", $_POST['name'])) . ".png";`

You are only adding the relative path which will point PHP to :

/home/content/08/11798508/html/domainname/files/scripts/files/images/team/

which is the wrong location. PHP's $_SERVER['DOCUMENT_ROOT'] will return the scripts' base directory URL. Since the folder you want to upload is in the parent folder. You should use $_SERVER['DOCUMENT_ROOT'] and the location becomes :

/home/content/08/11798508/html/domainname/files/images/team/


text:
Q: Looking for a way to pass Image from bitmap using EmguCV Currently, I'm looking for a solution to my problem which is the fact that I need
to pass the Image<Bgr, byte> object to one of recognizer method while so far I operate with Bitmap object (which by the way is a rectangle cropped from original Bitmap).
So the question is how can I recreate an Image<Bgr, byte> from Bitmap.
For now I use the solution that passes two arguments but I consider it redundant. I belive OpenCV or maybe EmguCV itself should provide some conversion solution but I wasn't able to track it so far.
Thanks for any help.

A: I am not sure if I understand your question correctly, but if you need to create an Image<Bgr, byte> from a Bitmap, the Image class has a constructor just for that.


text:
Q: Using flavors for publishing an app on AppGallery and Google Play I am trying to figure it out how to publish my app on AppGallery and Google Play. (My app is currently available on Google Play)
I am researching it for three hours and the best option looks like using flavors. Because I want to use same code base for different stores. To do that I decided to I add flavors like this:
productFlavors {
    gms {
        dimension "services"
        buildConfigField "String", "SERVICE_USED", '"g"'

    }
    hms {
        dimension "services"
        buildConfigField "String", "SERVICE_USED", '"h"'
    }
}
gmsImplementation 'com.google.firebase:firebase-analytics:17.2.0'
gmsImplementation 'com.google.firebase:firebase-messaging:20.0.0'
gmsImplementation 'com.google.firebase:firebase-ads:18.2.0'
gmsImplementation 'com.google.firebase:firebase-crashlytics:17.2.2'
hmsImplementation 'com.huawei.hms:ads-installreferrer:3.4.34.301'
hmsImplementation 'com.huawei.hms:ads-identifier:3.4.34.301'
hmsImplementation 'com.huawei.hms:hianalytics:5.0.5.301'
hmsImplementation 'com.huawei.hms:iap:5.0.4.301'
hmsImplementation 'com.huawei.hms:push:5.0.4.302'

Now I have a question:
Please correct me if I am wrong, I need to use an abstraction layer for common services right? For example, If I need to use IAP, I need a wrapper class that decides to use GMS or HMS which depends on the device type. If I go with this way I need something like that:

*

*Need an interface that needs to be implemented on HmsIAP and GmsIAP classes for the common methods like requestProduct method, purchaseMethod. etc

*A parent class that creates these classes and manages which class to use. That will called "AppIAP" class. The logic layer will use that class for IAP operations which will be not depented to the platform.
This approach makes sense to me, there will be one codebase for two platforms. It looks clean and easy to manage in the future. But the problem is I added flavor for the platform dependencies. So If I try to build hms variant of my code, it won't compile because Gms libraries will be missing. And I still has a GmsIAP class that needs to be build despite I am on the Hms variant.
To resolve that I could try to not use the flavors, with this approach I need to package my app with both platform's libraries, and my app will compile fine. But as looks like in the below link Google play will reject my app due to Hms libraries.
Is Huawei HMS tolerated on Google Play Store?
How can I resolve that?

A: I think the most maintainable solution is to use dependency injection with different source sets for different flavors. You can put your GMS dependent code inside src/gms/java and your HMS dependent code inside src/hms/java. Only the selected product flavor source set will be compiled. Very basic example with Hilt would look like this:
Inside your main source set you will have
src/main/java/your/package/AppMobileServices.kt
interface AppMobileServices {
    val isAvailable: Boolean
}

Then for GMS source set
src/gms/java/your/package/GmsModule.kt:
@Module
@InstallIn(SingletonComponent::class)
class GmsModule {
    @Provides
    fun googleMobileServices(@ApplicationContext context: Context): AppMobileServices {
        return GmsServices(context)
    }
}

src/gms/java/your/package/GmsServices.kt:
@Singleton
class GmsServices(@ApplicationContext private val context: Context) : AppMobileServices {
    override val isAvailable: Boolean
        get() = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
}

And then HMS source set
src/hms/java/your/package/HmsModule.kt:
@Module
@InstallIn(SingletonComponent::class)
class HmsModule {
    @Provides
    fun huaweiMobileServices(@ApplicationContext context: Context): AppMobileServices {
        return HmsServices(context)
    }
}

src/hms/java/your/package/HmsServices.kt:
@Singleton
class HmsServices(@ApplicationContext private val context: Context) : AppMobileServices {
    override val isAvailable: Boolean
        get() = HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS
}

Then in your main source set you can just inject the AppMobileServices and the correct one will be provided. Also, all code that is dependent on either GMS or HMS would go inside their flavor source sets.
@Inject
lateinit var appMobileServices: AppMobileServices


text:
Q: Postback in Website and webapplication I'm confused on how the postback works in website and web application because,
I have a button and in that I have given a sleep time for about 30 seconds and in another page on the same time when I try to do any activities like, click redirect etc.
In Web application the above scenario works without any issue.
In Web Site till the button event comes out the sleep time all the other activities will be hang up.
Please explain me on this.
Thanks in advance.

A: If Session state is enabled, requests within the session will be processed one by one. In your case, request is not completed until button handler comes out of sleep. Other requests are waiting until first request is completed.
To enable concurrent requests you must specify EnableSessionState="ReadOnly" in ASPX file which contains button. Or just disable Session state in webconfig.
<%@ Page EnableSessionState="ReadOnly" MasterPageFile="..." CodeBehind="xxx.cs" Inherits="xxx" %>


text:
Q: Python web communication between files I have my game created in pygame and now i want to create some sort of multiplayer, where one player will be hosting and the other will join the room. At the moment i have no idea about internet connection between two programs on different PCs and haven't found anything on google either. Thanks for any clues

A: You can use sockets. Right now I'm working on a multiplayer game its still in bata so i can't show it to you but i can give you my subprogram that simplify sockets. I suggest learning about sockets first so you can understand my program beater. here's a tutorial I used:
https://www.youtube.com/watchv=Q1a12QFq3os&index=1&list=WL
My code with an example:
https://gist.github.com/Blackwolf04
it's the Format_.py and Format_example.py


text:
Q: Adding a callback to a class function in swift In my project I created a public class to handle my network interfacing for data requests (JSON, images, etc). The function inside of the class uses Alamofire to establish a network connect and download the JSON file.
The class and the function are below:
import Foundation
import Alamofire

public class DataConnectionManager {

    public class func getJSON(AppModule:String, callback:(Int) -> Void) -> Void {

        switch(AppModule) {

        case "Newsfeed":
            Alamofire.request(.GET, "http://some-site.com/api/", encoding: .JSON).responseJSON { (_, _, JSONData, _) in
                if JSONData != nil {
                    jsonHolder.jsonData = JSONData!
                    print("start")
                    callback(1)
                }
                else {
                    callback(0)
                }
            }
            break

        default:
            break

        }

    }

}

I call the function in my project as seen below:
DataConnectionManager.getJSON("Newsfeed", callback: { (intCheck : Int) -> Void in
    if intCheck == 1 {
        println("Success")
    }
    else {
        println("Failure")
    }
})

The app will launch without any errors, however my sanity checks don't print out. In fact, when I do it this way the Alamofire.request doesn't grab the JSON feed either.
Am I heading in the right direction with this?

A: I got this to work, but I'm not sure how, exactly. I changed a couple of things based on user suggestions (adding error checking, etc) and it magically started working. Here's my updated code so people can see how to add a callback to their functions.
My "ConnectionManager":
import Foundation
import Alamofire

public class DataConnectionManager {

    public class func getJSON(AppModule:String, callback:(Int) -> Void) -> Void {

        switch(AppModule) {

        case "Newsfeed":
            Alamofire.request(.GET, "http://some-site.com/api/", encoding: .JSON).responseJSON { (_, _, alamoResponse, error) in
                if (error != nil){
                    println("You've got a response error!")
                    callback(0)
                }
                else {
                    if alamoResponse != nil {
                        jsonHolder.jsonData = alamoResponse!
                        callback(1)
                    }
                    else {
                        println("You've got some random error")
                        callback(0)
                    }
                }
            }
            break

        default:
            break

        }

    }

}

My call to the function:
DataConnectionManager.getJSON("Newsfeed", callback: { (intCheck : Int) -> Void in
    if intCheck == 1 {
        self.createTable()
    }
    else {
        println("Failure")
    }
})

A: I'm using swift 2.0 + SwiftyJSON and this is my code to implement this:
 class func getJSON(AppModule:String, urlToRequest: String, resultJSON:(JSON) -> Void) -> Void {
    var returnResult: JSON = JSON.nullJSON

    switch(AppModule) {
    case "all":
        request(.GET, urlToRequest)
            .responseJSON { (_, _, result) in
            if (result.isFailure){
                print("You've got a response error!")
                resultJSON(nil)
            }
            else {
                if (JSON(result.value!) != nil) {
                    returnResult = JSON(result.value!)
                    resultJSON(returnResult)
                }
                else {
                    print("You've got some random error")
                }
            }
        }
        break

    default:
        break

    }

}

And call the function like this:
    DataManager.getJSON("all",urlToRequest: "myurl.com", resultJSON: { (result: JSON) -> Void in
        if (result == nil){
            // error with result json == nil
            return
        }else{
            //do something with json result
        }
    })

Hope this can be helpful.


text:
Q: FLASK RESTful API using GET to get a specific id and returning 201 using Python I'm trying to get a todo_ID using GET method. I'm still new at using sqlalchemy and most of the things i have tried are telling me that sqlalchemy doesn't use them. Also, can someone tell me how to use HEAD, i want my methods to return http statuses, i kinda tried using them and imported the render template but when i try to use them it says it has no idea what they are.
this is my attempt at looking at a tutorial and making changes
from flask import Flask, jsonify,json, request, render_template, abort
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_pyfile('Config.py')
db = SQLAlchemy(app)

class JsonModel(object):  # Class for making objects JSON serializable
    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

class User(db.Model, JsonModel):  # Class which is a model for the User table in the database
    User_ID = db.Column(db.Integer, primary_key = True)
    FirstName = db.Column(db.String(20))
    LastName = db.Column(db.String(20))

    def __init__(self,User_ID,FirstName, LastName):
        self.User_ID = User_ID
        self.FirstName = FirstName
        self.LastName = LastName

class Todo(db.Model, JsonModel):  # Class which is a model for the Todo table in the database
    todo_ID = db.Column(db.Integer, primary_key = True)
    UserID = db.Column(db.Integer, db.ForeignKey("user.User_ID"))
    details = db.Column(db.String(30))

    def __init__(self, UserID, details):
        self.UserID = UserID
        self.details = details

@app.route('/todo', methods = ['GET'])  # Uses GET method to return all information in the database.
def index():
    return json.dumps([u.as_dict() for u in User.query.all()+Todo.query.all()]), 201

@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    query = Todo.query.get()
    return {'todo': [dict(zip(tuple(query.keys()), i)) for i in query.cursor if i[1] == todo_ID]}

@app.before_first_request #Creates everything before the first request.
def startup():
    db.create_all()

if __name__ == '__main__':
    app.run()

My most recent attempt was:
@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    query = Todo.query("select * from Todo")
    return {'todo': [dict(zip(tuple(query.keys()), i)) for i in query.cursor if i[1] == todo_ID]}

And the error that I get is this.
query = Todo.query("select * from Todo")
TypeError: 'BaseQuery' object is not callable
127.0.0.1 - - [30/Nov/2016 21:15:28] "GET /todo/1 HTTP/1.1" 500 -

A: If you want to query Todo by primary key and only return one record you can use:
from flask import jsonify

@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    response = {}
    todo = Todo.query.get(todo_ID)
    response['id'] = todo.id
    response['user_id'] = todo.UserID
    response['details'] = todo.details
    response['status_code'] = 201
    return jsonify(response)

Or you can use Marshmallow to have a serializer for each of your models so it can serialize them for you automatically.

A: Not sure I understand your problem, if your intention is to return json output as response and you want to control the status code, you could
use jsonify
from flask import jsonify

@app.route('/todo/<int:todo_ID>', methods = ['GET'])
def get(todo_ID):
    query = Todo.query("select * from Todo")
    response = {'todo': [dict(zip(tuple(query.keys()), i)) for i in query.cursor if i[1] == todo_ID]}
    response = jsonify(response)
    response.status_code = 201
    return response


text:
Q: Python beautifulsoup find_all can't find  I'm trying to use beautifulsoup to find content in HTML tags.
But when the tags are /div class=" "/ , it doesn't work.
It cannot be recognized correctly when there is a space in double quotation marks.
This is my code:
from bs4 import BeautifulSoup
if __name__ == "__main__":
soup = BeautifulSoup(open("1946.html", encoding='utf-8'), 'lxml')
for k in (soup.find_all('div', class_=" ")):
    print(k)

Thanks for any help.

A: The whitespace is the delimiter in a list of class names, so you wont find it. Just remove the whitespace from your selection to get your result and take look at the output, cause that is the way it would be recognised by the parser.
Note: It will interpret it in the way, that there is no class available. So you may have to change your selector strategy and use other attributes or elements - Question needs improvement / example to get more specific answers.
Example
from bs4 import BeautifulSoup

html='''

a

b

c

d

x

'''

soup = BeautifulSoup(html, 'html.parser')
for k in (soup.find_all('div', class_="")):
    print(k)

Output

a

b

c

d


text:
Q: I need to create a trigger to automatically increment the no_of_books in member table and book table Upon issue, the value of no_of_books must be decremented in book table and incremented in member table
create or replace trigger trans_s_t3
after insert on trans_s
select member_s as m1, book_s as b1
for each row
begin
  update book_s , member_s
  set no_of_books=:old.no_of_books - :new.no_of_books;
  where book_S=:new.book_no;
end;

A: Do like this
 create or replace trigger trans_s_t3
    after insert on trans_s
    select member_s as m1, book_s as b1
    for each row
    begin
      update book_s
      set no_of_books=:old.no_of_books - :new.no_of_books;
      where book_S=:new.book_no;
 update  member_s
      set no_of_books=:old.no_of_books - :new.no_of_books;
      where book_S=:new.book_no;
    end;

A: I noticed a problem with Narasimha's answer, since it doesn't include the column name in the WHERE clause (as the original didn't).  I guessed it was BOOK_NO below, since it was never explicitly mentioned as a field in the book_s or member_s tables.
I think it should be:
CREATE OR REPLACE TRIGGER trans_s_t3
    AFTER INSERT ON trans_s
    FOR EACH ROW
BEGIN
    UPDATE book_s
       SET no_of_books = :old.no_of_books - :new.no_of_books;
    WHERE book_s.BOOK_NO = :new.book_no;
    UPDATE member_s
       SET no_of_books = :old.no_of_books - :new.no_of_books;
    WHERE book_s.BOOK_NO = :new.book_no;
END;

Please mark this answer as useful if you find this to be, I could use the points.
Thanks,
Stew


text:
Q: DNS resolution via Proxy in Java In our enterprise network we have to use a proxy to reach the internet. For some services there are set up VPNs connecting to external partners.
Unfortunately some of them can't guarantee a static IP address therefore they usually create public DNS entries.
So these DNS entries are publicly accessible but point to IP addresses that are only reachable from our network through the VPN.
Would it be possible to ask the proxy to do only the DNS resolution and return the IP address?


text:
Q: How to calculate iteration of gauss siedel method in matlab I want to calculate i´the number of iteration of gauss siedel method in matlab
here is my code
alpha=1;
A=zeros(30,30);
A(1,1)=-(2+alpha);
A(1,2)=1;

for i=2:29
    A(i,i-1)=1;
    A(i,i)=-(2+alpha);
    A(i,i+1)=1;
end

A(30,29)=1;
A(30,30)=-(2+alpha);

D=diag(diag(A));
R=A-D;
x=zeros(30,1);
list=[];
count=0;

for k=1:150
    xkk= inv(L)*(b-(U*x));
    count=count+1;
    list(count,:)=xk;
    if(norm(xkk-x)<=10^-5)
        break;
    end
    x=xkk;
end

count

when I ran it I got cound=150 so it seems that count does not works good
How to correct it?
Thanks

A: Change the last part like this:
xkk= inv(L)*(b-(U*x));
e=norm(xkk-x);
while(e>10^-5)
    xkk= inv(L)*(b-(U*x));
    count=count+1;
    list(count,:)=xk;
    e=norm(xkk-x)
    x=xkk;
end


text:
Q: How to call a specific cookie is JS I have 2 cookies in my index page which comes from a user prompt. The cookies are "user=userinput" and "pass=userinput". How would I call these cookies to be able to edit DOM HTML?
The code I have setting the cookies is basic document.cookie = "user=Jeff; path=/pages/" and document.cookie = 'pass='+passToCheck+'; path=/pages'.
So how do I call document.cookie["user="] or document.cookie["pass="], is this possible?


text:
Q: Interceptor for all calls in servicemix What is the best way to add an interceptor to servicemix that would log all webservice calls (or calls to osgi components would also work)?
I know of the NMR interceptors, but these apparently don't work for CXF.
And I know about "jaxws:inInterceptors" but these need to be added to each endpoint manually.
I would like to intercept the calls to all endpoints (WS and RS) with a single configuration/interceptor, is this possible in servicemix?

A: you can just add CXF logging feature like this
<!-- adding the feature to the bus-->
<cxf:bus>
    <cxf:features>
        <cxf:logging/>
    </cxf:features>
</cxf:bus>


text:
Q: How to know image was binding in xaml in windows phone? I have a image url and I binding it to xaml. But i don't know when it was show in xaml. So i can't put ProgressBar.
My code :
XAML:  <Image Grid.Row="1" x:Name="viewimg"/>
.CS : viewimg.Source = (ImageSource)new ImageSourceConverter().ConvertFromString((string)          (App.Current as App).linkimage480);

A: Use ImageOpened event, there is also ImageFailed in case there is a problem.
Edit:
Add ImageOpened event to your XAML:  <Image Grid.Row="1" x:Name="viewimg"/>
And then in code I would do:
BitmapImage bm = new BitmapImage();
bm.ImageFailed += delegate { // Code to execute when binding fails };
bm.UriSource = new Uri("http://imagesource.com", UriKind.Absolute);
viewimg.Source = bm;

Because I think when you add ImageFailed to XAML Image control and the failure occurs in your ImageSource then the event won't be fired.


text:
Q: How to convert string of image urls in android I am have a list (100's) of image urls which I want to display in a ListView together with text. The problem I am having is that my listview displays all the URLs as string and not IMAGE. I have implemented a BITMAP class and tested it with a sigle image url, and on an IMAGEVIEW, it worked. I have read some post but can't really figure it out working with ListView. How to load an ImageView by URL in Android?
In the my code below, imageUrls holds all the image urls as string and concatString holds img + text, which was used in the adapter. My question is how do I apply the BITMAP class on a STRING that holds all the urls before putting it in the adapter, that is imageUrls? Or is ther a better approach.
Bitmap bitmap;
String temp, json, namesImg, imageUrls, allImageANDnames;
StringBuffer sb = new StringBuffer();
ArrayList<String> concatString = new ArrayList<String>(); // ARRAYLIST THAT HOLDS IMG & TXT
JSONObject object;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact);

    // Reading json file from assets folder
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open(
                "myjson.json")));
        while ((temp = br.readLine()) != null)
            sb.append(temp);

        json = new String(sb);
        JSONArray jsonArray = new JSONArray(json);

        for (int i = 0; i < jsonArray.length(); i++) {
            // Creating JSONObject from JSONArray
            object = jsonArray.getJSONObject(i);
            namesImg = object.getString("name"); // holds all text
            imageUrls = object.getString("url"); // holds all image urls (HERE IS WHERE I NEED HELP)
            allImageANDnames = imageUrls + "\t\t" + namesImg; // holds text and img urls
            concatString.add(allImageANDnames); //(I WANT THIS TO HOLD IMAGES & TEXT) not urls & text
        }

    } catch (IOException e) {
        e.printStackTrace();
    }  catch (JSONException e) {
        e.printStackTrace();
    }finally {
        if ((br != null)) {
            try {
                br.close(); // stop reading
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // adapter to show list in activity
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, concatString); // I USED THE HOLDER HERE

    ListView list = (ListView) findViewById(R.id.listView);
    list.setAdapter(adapter); // LIST THAT POPULATE THE IMG & TXT
}

    // HOW CAN I APPLY THIS CLASS ON ***imageUrls***
    public class ImageFromUrl extends AsyncTask<String, Void, Bitmap> {
    ImageView imageView;
    public GetImageFromUrl(ImageView img){
        this.imageView = img;
    }
    @Override
    protected Bitmap doInBackground(String... url) {
        String stringUrl = url[0];
        bitmap = null;
        InputStream inputStream;
        try {
            inputStream = new java.net.URL(stringUrl).openStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    @Override
    protected void onPostExecute(Bitmap bitmap){
        super.onPostExecute(bitmap);
        imageView.setImageBitmap(bitmap);
    }
}

.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" >
    </ListView>
</androidx.constraintlayout.widget.ConstraintLayout>

Sorry I am ney on this.

A: Use ImageView for showing images with recyclerview instead of the listview.
and the solution is simple. Use library(like glide, Picasso, etc) that coverts the URL into Image and set on to the location.
Picasso.get()
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)
Use this Library Picasso


text:
Q: React-Native переиспользование готового кода с Android Приступил к изучению ReactNative, сразу возникли вопросы:
1) component'ом являются только Ui-элементы, или им может быть любой класс, который скажем выполняет какую то логику (к примеру по работе с сетью)?
2) Есть необходимость динамически создавать Ui элементы из пришедших извне параметров, т.к. изначально нет ничего статического, всё создаётся динамически по данным с сети. Могу ли реализовать это через ReactNative?

A: 1)Компонент - это class extends Component, View-элемент, который выполняет свою логику. Например, кнопочка, при нажатии на которую выполняется функция обновления данных, передаваемая из родителя:
button.js:
'use strict';

import React, {
PropTypes,
Component
} from 'react';

import {
TouchableHighlight,
Text
} from 'react-native';

let Button = class extends Component {

constructor(props) {
    super(props);
}

render() {
   return (<TouchableHighlight onPress={this._update.bind(this)}>
           <Text>Update</Text>
           </TouchableHighlight>
            );
}

_update() {
    this.props.update();
}

}

Button.propTypes = {
update: PropTypes.func
}

export default Button;

parent.js:
'use strict';

import React, {
Component
} from 'react';

import {
View,
Text
} from 'react-native';

import Button from './button.js';

class Parent extends Component {

constructor(props) {
    super(props);
    this.state={
    valueToUpdate: ''
    };
}

render() {
   return (<View>
           <Text>{this.state.valueToUpdate}</Text>
           <Button update={this.update.bind(this)}/>
           </View>
            );
}

update() {
    this.setState({valueToUpdate: 'Updated!'});
}

}

Логика по работе с сетью запихивается во внутреклассовый метод, например в метод update в примере. Если метод используется в нескольких классах, его можно экспортировать:
'use strict';

import React from 'react';

const getSomething = (data, callback) => {

fetch('someurl/get/something.php', {
      method: 'POST',
      dataType: 'json',
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
      },
      body: JSON.stringify({
                           data: data
                           })
      })
.then((response) => { return response.json() })
.then((responseData) => { return responseData; })
.then((newData) => {
      callback(newData);
      })

}

export default getSomething;

И вызывать из компонента:
...
import getSomething from './getSomething.js';
...
update(newData) {
this.setState({data: newData});
}
...
getSomething(this.state.data, this.update.bind(this));
...

2)Динамическое создание View-элементов выглядит как-то так:
...
let myViews=[];

class Parent extends Component {

constructor(props) {
    super(props);
}

render() {
   return (<View>
           {myViews}
           <TouchableHighlight onPress={this._addView}>
           <Text>AddView</Text>
           </TouchableHighlight>
           </View>
            );
}

_addView() {
    myViews.push((<Text>New View is created!</Text>));
}

}

Насчёт использования кода с Android, я поднял здесь эту тему и сам жду ответа: React Native: Android UI component


text:
Q: Multidimensional Numpy ndarray to csv or pandas df I have a multidim ndarray with 60 columns and 40 rows with raw returns of stocks. When exporting to a csv file with nummpy.savetxt I got 40 rows but only one column. How can I export this matrix?
output when reading out the ndarray:
Out[88]:
array([[-0.0038,  0.0002, -0.0017, ..., -0.0057,  0.0073,
         0.0025],
       [ 0.0006, -0.0021,  0.0103, ...,  0.0049, -0.0087,
         0.0123],
       [-0.0138, -0.0294,  0.0276, ...,  0.0474, -0.007 ,
         0.0031],
       ...,
       [-0.0049, -0.0232, -0.0356, ..., -0.0273,  0.0677,
        -0.0227],
       [ 0.002 , -0.0034, -0.0158, ...,  0.015 , -0.0002,
        -0.0044],
       [-0.0049,  0.0227,  0.0335, ...,  0.0025, -0.0222,
         0.0168]])

A: You need to specify a delimiter. CSV files are default comma seperated.
E.g.
arr = np.random.rand(4,6)
np.savetxt('file.csv', arr, delimiter=',')`

A: You have to state the delimiter between values. By default it uses a space ' ', but you will want ',', which is default for csvs.


text:
Q: How to expand Jpanels into GridBagLayout My Question is how to expand my 3 JPanels into my GrigBadLayout.
I added 2 photo, the first sample and displays the result and the second as I would like it to be.
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JPanel;

public class ListMembersView extends JPanel{
    JPanel headerPanel;
    JPanel containerPanel;
    JPanel footerPanel;

    public ListMembersView(){

        initComponents();
        initLayout();
    }

private void initComponents(){

    this.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255),5));

    headerPanel = new JPanel();
    headerPanel.setBackground(Color.red);
    containerPanel = new JPanel();
    containerPanel.setBackground(Color.yellow);
    footerPanel = new JPanel();
    footerPanel.setBackground(Color.blue);
}

private void initLayout(){
    this.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    /*Not expand JPanel?*/
    c.fill = GridBagConstraints.HORIZONTAL;

    c.gridx=0; c.gridy=0;
    this.add(headerPanel,c);

    c.gridx=0; c.gridy=1;
    c.gridwidth = 3;
    this.add(containerPanel,c);

    c.gridx=0; c.gridy=2;
    this.add(footerPanel,c);

}
}

My result is:

I would like be that way:

A: You need to set columnWeights = {1} and rowWeights = {1, 1,1} and fill to BOTH like:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ListMembersView extends JPanel{
    JPanel headerPanel;
    JPanel containerPanel;
    JPanel footerPanel;

    public ListMembersView(){

        initComponents();
        initLayout();
    }

private void initComponents(){

    this.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255),5));

    headerPanel = new JPanel();
    headerPanel.setBackground(Color.red);
    containerPanel = new JPanel();
    containerPanel.setBackground(Color.yellow);
    footerPanel = new JPanel();
    footerPanel.setBackground(Color.blue);
}

private void initLayout(){
    GridBagLayout gridBagLayout = new GridBagLayout();
    this.setLayout(gridBagLayout);

    gridBagLayout.columnWeights = new double[] {1};
    gridBagLayout.rowWeights = new double[] {1, 1, 1};
    GridBagConstraints c = new GridBagConstraints();
    /*Not expand JPanel?*/
    c.fill = GridBagConstraints.BOTH;

    c.gridx=0; c.gridy=0;
    this.add(headerPanel,c);

    c.gridx=0; c.gridy=1;
    c.gridwidth = 3;
    this.add(containerPanel,c);

    c.gridx=0; c.gridy=2;
    this.add(footerPanel,c);

}

public static void main(String[] args) {
    JFrame frame = new JFrame("test");
    frame.setLayout(new BorderLayout());
    frame.add(new ListMembersView());
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}

The fill=BOTH teels, that panels should be extended in both directions.
the weights tells how to divide the space beetwen the rows or columns proportionally to the overall sum of their weights.


text:
Q: ormlite query with multiple tables in where conditions I'd like to do something like this:
    Select * from A join B where (A.a=x and B.b=y);

I've tried:
    qbA = aDao.queryBuilder();
    qbB = bDao.queryBuilder();
    whereA = qbA.where();
    whereB = qbB.where();
    join = qbA.join(qbB);
    whereJ = join.where();
    whereJ.and(whereA.eq(A.a, x), whereB.eq(B.b, y));

It gives me compilation error. I have also tried to use only joins where like:
    whereJ.and(whereJ.eq(A.a=x), whereJ.eq(B.b=y));

I got runtime error: "A doesn't have 'b' attribute".

A: Yeah, you can't combine where statements like that.  You should do the following:
whereA = qbA.where();
whereA.eq(A.a, x);
whereB = qbB.where();
whereB.eq(B.b, y);
join = qbA.join(qbB);

ORMLite should take care of doing the AND and putting together the 2 different WHERE statements.


text:
Q: Program that asks for numbers until a letter is input in C Hi so im trying to make a program that asks for numbers until a letter is typed in C.This is what I have
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void){
    long siz = 10;
    float *biglist = malloc(sizeof(float)* siz);
    int n, sum = 0;
    while ((n  = getchar() )!= "d"){
        scanf("%d",n);
        sum = sum + n;
    }
    printf("The sum is : %d",sum);
}

A: While you can do character-oriented input with getchar() and look for some special character to break the loop, that probably isn't the best way to go. Instead when you are reading user-input, you want to use line-oriented input functions to ensure you consume a complete line of input at a time. This ensures there are no offending characters left unread in stdin that will mess up your next input. Now while that is mitigated by reading a character at a time -- the logic you will need to employ to handle all tests and conversions reinvents the wheel.
Instead, if you read a line at a time, you can allow the user to enter as many numbers as they like (one-per-line, up to the limit of your allocation) and then simply press Enter alone on an empty line to stop input. The standard approach is to read a line of input into a buffer (character array) and then parse the needed information from the buffer using sscanf() or if more error detection and reporting is warranted, using strtol(), strtof(), strtod(), etc..
When reading a line at a time, simply provide a sufficiently sized buffer to handle the longest anticipated line (and the cat stepping on the keyboard). If you are on an embedded device, just reduce the buffer size accordingly. To size the buffer (or anything else needing a fixed size), #define a constant or use a global enum for the same purpose, e.g.
#define MAXF 1000       /* if you need a constant, define one (or more) */
#define MAXC 1024
....
    char line[MAXC] = "";
    float *ma = malloc (MAXF * sizeof *ma),     /* or float ma[MAXF] = {0}; */

Now you simply read input checking that the number of inputs fit in your array and checking that '\n' alone wasn't entered, e.g.
    puts ("enter one float per-line, [Enter] alone when done");

    /* while ma not full, and line read and not empty line */
    while (nfloat < MAXF && fgets (line, MAXC, stdin) && *line != '\n') {

For converting the input to float, simply use sscanf() to parse a float from the buffer line validating that a successful conversion took place before incrementing your sum and counter, e.g.
        /* if valid conversion to float */
        if (sscanf (line, "%f", &ma[nfloat]) == 1) {
            sum += ma[nfloat];                  /* sum float */
            nfloat += 1;                        /* increment counter */
        }

Putting it altogether, you could do:
#include <stdio.h>
#include <stdlib.h>

#define MAXF 1000       /* if you need a constant, define one (or more) */
#define MAXC 1024

int main (void) {

    char line[MAXC] = "";
    float *ma = malloc (MAXF * sizeof *ma),     /* or float ma[MAXF] = {0}; */
        sum = 0;
    size_t nfloat = 0;

    if (ma == NULL) {
        perror ("malloc-ma");
        return 1;
    }

    puts ("enter one float per-line, [Enter] alone when done");

    /* while ma not full, and line read and not empty line */
    while (nfloat < MAXF && fgets (line, MAXC, stdin) && *line != '\n') {
        /* if valid conversion to float */
        if (sscanf (line, "%f", &ma[nfloat]) == 1) {
            sum += ma[nfloat];                  /* sum float */
            nfloat += 1;                        /* increment counter */
        }
    }

    printf ("The sum is : %f\n", sum);
    free (ma);      /* don't forget to free what you allocate */
}

(note: the memory allocated is freed. While this will happen automatically on program exit, you won't always allocate in main(). Failure to free the memory you allocate in that case will lead to a memory-leak if the ability to free the memory is lost)
Example Use/Output
./bin/sumfloats
enter one float per-line, [Enter] alone when done
10.1
10.3
10.3
10.3

The sum is : 41.000000

If you want to output all stored floats, then simply add an output loop before you output the sum, e.g.
    for (size_t i = 0; i < nfloat; i++)
        printf (i ? " %.1f" : "%.1f", ma[i]);

    printf ("\nThe sum is : %.2f\n", sum);
    free (ma);      /* don't forget to free what you allocate */
}

In that case, you would output each float that is part of sum with precision to 1 digit and the sum with a precision of 2, e.g.
./bin/sumfloats
enter one float per-line, [Enter] alone when done
10.1
10.3
10.3
10.3

10.1 10.3 10.3 10.3
The sum is : 41.00

This is a slight variation on what you were attempting, but this approach will save you a lot of grief (and potential logic errors). Look things over and let me know if you have further questions.

A: Your getchar() call won't function as you imagine it would.
To begin with, "x" is a string literal, what you actually wanted is, 'x', a single character.
Your malloc() call is correct but you never seem to use the allocated memory and you never call free().
Checking the return value of scanf() would be an easy to exit if anything but a floating point is entered. You can also use fgets() with sscanf(), since scanf() is prone to arithmetic overflow.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t i = 0;
    size_t tam = 1000;
    float *ma = malloc(sizeof(float) * tam);
    float chr, sum = 0;

    if (ma == NULL) /* check that malloc succeded */
    {
        fprintf(stderr, "Allocation failed\n");
        exit(EXIT_FAILURE);
    }

    while ((scanf("%f", &chr) == 1) && i < tam) /* check for overflow and scanf return value */
    {
        sum = sum + chr;
        ma[i++] = chr;
    }

    /* if you are planning on receiving input again you have to reset/clear the input buffer */

    printf("The sum is : %.1f", sum);

    free(ma);

    return 0;
}

EDIT: If you want to resize the array, you need to use realloc(),
 while ((scanf("%f", &chr) == 1)) /* check scanf return value */
    {
        if (i >= tam)
        {
            float *tmp = realloc(ma, (tam + 100) * sizeof(float)); /* resize by 100 or desired size, dont forget to add the previous size */
            if (tmp == NULL)
            {
                fprintf(stderr,"Re - Allocation failed\n");
                free(ma);
                exit(EXIT_FAILURE);
            }
           ma = tmp;
           tam += 100; /* increase the new size */
        }

        sum = sum + chr;
        ma[i++] = chr;
    }