text:
Q: add content to site.master control I have a master page file and I have always added additional style sheets pragmatically using Page.Header.Controls.Add etc. But we have a client that wants the css files in a specific place, so I noticed that in the head section there is a
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
so I thought I could just add it into there.
I have tried
ContentPlaceHolder blar = (ContentPlaceHolder)Master.FindControl("HeadContent");
blar.Controls.Add(css);

But nothing appears, can anyone help?

A: U can add your css file like that;
ContentPlaceHolder blar = (ContentPlaceHolder)Master.FindControl("HeadContent");
HtmlLink css= new HtmlLink();
css.Attributes.Add("rel", "stylesheet");
css.Attributes.Add("type", "text/css");
css.Href = "/Styles/site.css";
blar.Controls.Add(css);

A: Check out the answer to this question: https://stackoverflow.com/a/2969360/1372321
It seems to do what you want :)
Update
To add content at a specific place in the header, and you are using .Net 4.5, you can use the System.Web.Optimatization API and bundle the styles. Then in your head, you can use the provided control:
<webopt:BundleReference runat="server" Path="~/Content/css" />

You can see an example of this in the default WebForms project template.
If you're using an older version of .Net, you can use content placeholder in your master page, and then add controls to that specific placeholder like so:
In master page head
<asp:ContentPlaceHolder runat="server" ID="HeadContent" />

In aspx page
<asp:Content runat="server" ContentPlaceHolderID="HeadContent">
    <asp:PlaceHolder runat="server" ID="placeHolderHead"></asp:PlaceHolder>
</asp:Content>

Then you can simply add the Link controls to the placeholder programatically.


text:
Q: Finding solutions to a single linear equation in n variables, or determine that no solution exists Suppose you have a linear equation in n variables. The goal is to either determine that no  integer solution is possible, or determine the smallest coefficient vector, for an integer solution.
In other words, let ax=b where x is the vector you want to find, and a is a vector of coefficients. b is a scalar constant. Find x such that the sum of x1, ... ,xn is minimized, and all xis are integers. Or, determine that no such x exists. From now on, I will say that |x| is the sum of the xi's.
What is an efficient way to solve this? I feel like this is similar to the Knapsack problem, but I'm not entirely sure.
My Solution
The way I tried to solve this was doing a Breadth-First Search on the space of vectors, where the breadth would be the sum of the vector entries.
At first I did this naively, starting from |x| = 0, but when n is even moderately large, and the solution is non-trivial, the number of vectors generated is enormous (n ^ |x| for each |x| you go through). Even worse, I was generating many duplicates. Even when I found a way to generate almost no duplicates, this way is too slow.
Next, I tried starting from a higher |x| from the beginning, by putting a lower bound on the optimal |x|. I sorted a to have it in decreasing order, then removed all ai > b. Then a lower bound on |x| is b / a[0]. However, from this point, I had difficulty quickly generating all the vectors of size |x|. From here, my code is mostly hacky.
In the code, b = distance, x = clubs, n = numClubs
Here is what it looks like:
short getNumStrokes (unsigned short distance, unsigned short numClubs, vector<unsigned short> clubs) {
    if (distance == 0)
        return 0;

    numClubs = pruneClubs(distance, &clubs, numClubs);
    //printClubs (clubs, numClubs);

    valarray<unsigned short> a(numClubs), b(numClubs);
    queue<valarray<unsigned short> > Q;

    unsigned short floor = distance / clubs[0];

    if (numClubs > 1) {
        for (int i = 0; i < numClubs; i++) {
            a[i] = floor / numClubs;
        }

        Q.push (a);
    }

    // starter vectors
    for (int i = 0; i < numClubs; i++) {
        for (int j = 0; j < numClubs; j++) {
            if (i == j)
                a[j] = distance / clubs[0];
            else
                a[j] = 0;
        }

        if (dot_product (a, clubs) == distance)
            return count_strokes(a);

        // add N starter values
        Q.push (a);
    }

    bool sawZero = false;

    while (! Q.empty ()) {
        a = Q.front(); // take first element from Q
        Q.pop(); // apparently need to do this in 2 operations >_<

        sawZero = false;

        for (unsigned int i = 0; i < numClubs; i++) {
            // only add numbers past right-most non-zero digit
            //if (sawZero || (a[i] != 0 && (i + 1 == numClubs || a[i + 1] == 0))) {
            //    sawZero = true;

                b = a; // deep copy
                b[i] += 1;

                if (dot_product (b, clubs) == distance) {
                    return count_strokes(b);
                } else if (dot_product (b, clubs) < distance) {
                    //printValArray (b, clubs, numClubs);
                    Q.push (b);
                }
            //}
        }
    }

    return -1;
}

EDIT: I'm using valarray because my compiler isn't C++ 11 compliant, so I can't use array. Other code suggestions much appreciated.

A: Your problem is an equality constrained integer knapsack problem:
min |x|
s.t. ax = b
     x integer

If you have access, CPLEX or GUROBI can generally solve such problems quite easily.
Otherwise, consider some reductions of the constraint set
(e.g., http://www.optimization-online.org/DB_FILE/2002/11/561.ps)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tornado Framework (FacebookGraphMixin) I wanted to try sending App request from my Facebook app to a user using Tornado Framework. I was following http://www.tornadoweb.org/documentation/auth.html but I have no idea how to resolve this error. Any professionals out there? Thanks!
Error Log
Traceback (most recent call last):
  File "send.py", line 36, in <module>
    main()
  File "send.py", line 33, in main
    test.get(app_access_token, player_id)
  File "send.py", line 15, in get
    callback=self.async_callback(self._on_post))
AttributeError: 'Send' object has no attribute 'async_callback'

Code
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import httpclient

class Send(tornado.auth.FacebookGraphMixin):
    def get(self, app_access_token, player_id):
        self.facebook_request(
            "/"+player_id+"/apprequests",
            post_args={"message": "I am an app request from my Tornado application!"},
            access_token=app_access_token,
            callback=self.async_callback(self._on_post))

    def _on_post(self, new_entry):
        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

def main():
    key = "xxxxxxxxxxx"
    secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    player_id = "100003395454290" #fake id
    http_client = httpclient.HTTPClient()
    response = http_client.fetch("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id="+key+"&client_secret="+secret+"&redirect_uri=&code=")
    app_access_token = response.body.replace("access_token=","")

    test = Send()
    test.get(app_access_token, player_id)

if __name__ == "__main__":
    main()

A: Okay, my answer does not directly answer the OP's question. But as this shows up in the top search results for the error AttributeError: 'XxxxxHandler' object has no attribute 'async_callback'
It is worth noting that starting Tornado v4.0 the async_callback function has been removed. To quote the Backwards-compatibility notes:

The RequestHandler.async_callback and WebSocketHandler.async_callback
  wrapper functions have been removed; they have been obsolete for a
  long time due to stack contexts (and more recently coroutines).

A: Looks like you forgot to subclass tornado.web.RequestHandler. Change:
class Send(tornado.auth.FacebookGraphMixin):

To:
class Send(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin):


text:
Q: lapply on list of data frames I have a list dat.list of data frames that look like this:
    GeneId  baseMean    log2FoldChange  lfcSE   stat    pvalue  padj    threshold   type    sigtype
    18S_rRNA:18S_rRNA   1209166.39919685    -0.209458177840739  0.234737554962532   -0.892307913295647  0.372227913902729   0.448713101690961   non-sig other   non-sig-other
    28S_rRNA:28S_rRNA   2592930.17340529    -0.180545589669893  0.231050649278924   -0.781411306280031  0.434560623435828   0.513996436321948   non-sig other   non-sig-other
    5.8S_rRNA:5.8S_rRNA 766069.47551055 0.113601345777545   0.191275069218117   0.593916113803629   0.552568220875051   0.615519030848158   non-sig other   non-sig-other
    5S_rRNA:5S_rRNA 2.79711958523178    -1.58909406740344   1.16966935304225    -1.3585839992048    0.174278448339169   0.238886346633129   non-sig other   non-sig-other
    MS2-RNA-control1:MS2-RNA-control1   81986.8654716761    -1.52675604546698   0.617811342665657   -2.47123343329943   0.0134647893998128  0.0283469250522374  sig other   sig-other
    MS2-RNA-control2`:MS2-RNA-control2  4610.31645194732    -4.54922459870619   0.929798724392121   -4.89269825755069   9.94628389868329e-07    4.37636491542065e-06    sig other   sig-other

I want to generate an MA plot for each data frame using this function:
maplot <- function(df) {
  ggplot(df,
    aes(x = baseMean, y = log2FoldChange)) +
    scale_x_continuous(trans = "log10") +
    geom_point(aes(col = threshold), size = 1, shape = 20) +
    scale_color_manual(values = c("non-sig" = "gray70","sig" = "red")) +
    geom_point(data = df[df$sigtype == 'sig-haca', ], pch = 21, fill = NA, size = 3, colour = "blue", stroke = 0.5) +
    ylim(-5, 10) +
    geom_hline(yintercept = 0, linetype = "dashed", color = "black") +
    xlab("mean of normalized counts") +
    ggtitle(paste("MAPLOT_", titlename, sep = "")) +
    theme_classic()
}

I have tried lapply(dat.list, maplot), but that doesn't work. How do I specify titlename in the ggtitle call?


text:
Q: Error installing fbprophet on Google Cloud Platform AI Platform I am trying to install facebook prophet on my Jupyter Notebook in AI Platform
!pip3 install fbprophet

I am getting this error:
DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality.
Defaulting to user installation because normal site-packages is not writeable
Collecting fbprophet
  Using cached fbprophet-0.7.1.tar.gz (64 kB)
Requirement already satisfied: Cython>=0.22 in /home/jupyter/.local/lib/python3.5/site-packages (from fbprophet) (0.29.21)
Collecting cmdstanpy==0.9.5
  Using cached cmdstanpy-0.9.5-py3-none-any.whl (37 kB)
Requirement already satisfied: pystan>=2.14 in /home/jupyter/.local/lib/python3.5/site-packages (from fbprophet) (2.19.1.1)
Requirement already satisfied: numpy>=1.15.4 in /home/jupyter/.local/lib/python3.5/site-packages (from fbprophet) (1.18.5)
ERROR: Could not find a version that satisfies the requirement pandas>=1.0.4 (from fbprophet) (from versions: 0.1, 0.2b0, 0.2b1, 0.2, 0.3.0b0, 0.3.0b2, 0.3.0, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.5.0, 0.6.0, 0.6.1, 0.7.0rc1, 0.7.0, 0.7.1, 0.7.2, 0.7.3, 0.8.0rc1, 0.8.0rc2, 0.8.0, 0.8.1, 0.9.0, 0.9.1, 0.10.0, 0.10.1, 0.11.0, 0.12.0, 0.13.0, 0.13.1, 0.14.0, 0.14.1, 0.15.0, 0.15.1, 0.15.2, 0.16.0, 0.16.1, 0.16.2, 0.17.0, 0.17.1, 0.18.0, 0.18.1, 0.19.0rc1, 0.19.0, 0.19.1, 0.19.2, 0.20.0rc1, 0.20.0, 0.20.1, 0.20.2, 0.20.3, 0.21.0rc1, 0.21.0, 0.21.1, 0.22.0, 0.23.0rc2, 0.23.0, 0.23.1, 0.23.2, 0.23.3, 0.23.4, 0.24.0rc1, 0.24.0, 0.24.1, 0.24.2, 0.25.0rc0, 0.25.0, 0.25.1, 0.25.2, 0.25.3)
ERROR: No matching distribution found for pandas>=1.0.4 (from fbprophet)

It says that my pandas is not >= 1.0.4
When I try to upgrade my pandas the latest version is '0.25.3'. It might be to do with the deprecation warning of python 3.5
I have researched trying to upgrade my Python in AI platform before and the process seems complicated. Does anyone know a workaround? Thanks

A: You can start a new instance which has Python 3.7 then install fbprophet

A: Ref: https://github.com/facebook/prophet/issues/1775
Solution:
pip install pystan==2.18.0.0

pip install fbprophet

After, I did these 2 simple steps, I got no red errors and ready to predict the future with FB Prophet :D


text:
Q: Extending smooth triangulation Can one always extend a smooth triangulation from a smooth submanifold $S$ to the ambient manifold $M$? (For simplicity both $S$ and $M$ are compact without boundary). Is the extension possible when $S$ is a sphere?
What I know is summarized in this answer. Namely, in the PL category the answer is yes, by a result of Armstrong, i.e., one can always extend a triangulation from a locally flat PL submanifold. Also one can always extend a smooth triangulation from a codimension one separating hypersurface (this is due to Munkres). I think, the same is true for non-separating hypersurfaces. Thus it is enough to extend the smooth triangulation of $S$ to a tubular neighborhood of $S$.
Naively, I would expect that the extension is always possible. Otherwise, one can probably use it to define a potentially interesting invariant of smooth manifolds, and I have never heard of such an invariant.


text:
Q: What is the name of this type of problem I've seen the Wikipedia page about it a while ago - but I can't find it now.
The problem is something like:

*

*Mary lives next to Jane

*Rob has a green door

*Mike likes dogs

*Jeff likes cats and can't live next to Mike

*Steve lives across from Rob and Jane

Who lives next door to Jeff?
It's a really old puzzle (I think World War 1) published in a newspaper and possibly to do with Camel Cigarettes advertising at some point.
the Wiki page discussed various solutions using different software languages, as some families of languages are better suited to these types of solutions

A: This is a Constraint Satisfaction Problem. This problem is also a Zebra Puzzle. A kind of Logic Puzzle.
You can find solutions in multiple languages in Rosetta code.
The rest of this answer is a description of how I figured that out.

The problem in the question reminded me of a "riddle" from a TED-Ed video. I found the TED-Ed video searching in the TED-Ed youtube channel for "riddle thief", which gave me the name "Einstein's riddle".
Looking for "Einstein's riddle" in Wikipedia, leaded me to the article Zebra Puzzle. The article says:

The puzzle is often called Einstein's Puzzle or Einstein's Riddle because it is said to have been invented by Albert Einstein as a boy; it is also sometimes attributed to Lewis Carroll. However, there is no known evidence for Einstein's or Carroll's authorship and the Life International version of the puzzle mentions brands of cigarette, such as Kools, that did not exist during Carroll's lifetime or Einstein's boyhood.

Althought there are no code examples in the article.
There are some interesting links, among which a couple papers talk about Constraint programming:

*

*Capturing Contraint Programming Experience: A Case-Based Approach

*Hybrid Algorithms For The Constraint Satisfaction Problem
The name "Constraint Satisfaction Problem" which I'm giving you comes from that last paper. The name "Zebra Puzzle" and the fact that it is a "Logic Puzzle" come from Wikipedia.
I also found the the Rosetta Code link in the Wikipedia article.

A: Think this might be Constraint Programming
https://en.m.wikipedia.org/wiki/Constraint_programming


text:
Q: JS Recursively find element in parent-child array i have a array with a nested parent-child structure. I need to recursively go through this array and find wanted element.
I wrote this function:
recursivelyFindElementByCondition(nodes, isSatisfyingCondition) {

    function recursiveCheck(items) {
        for (const item of items) {
            if (isSatisfyingCondition(item)) {
                return item;
            }

            if (item.rows) {
                recursiveCheck(item.rows)
            }
        }
    }

    return recursiveCheck(nodes);
}

But i don't understand why it returns undefined. It should work correct as far as i understand.
I know that there is a way to create a variable out of scope of recursive function and assign element to it and then return it in the end, just wanted to do it without unnecessary variable and have no idea why is approach above doesn't work.

A: The result of the recursive call must be returned, for it to propagate up to the point of invocation and be returned as the result.

function findNode(nodes, predicate) {
    for (const node of nodes) {
        if (predicate(node)) return node

        if (node.rows) {
            let match = findNode(node.rows, predicate)
            if (match) return match
        }
    }
}

const tree = [{
    value: 'a',
    rows: [{
        value: 'b'
    }]
}, {
    value: 'c',
    rows: [{
        value: 'd',
        rows: [{
            value: 'e'
        }]
    }]
}]

const result = findNode(tree, ({value}) => value === 'e')

console.log(result)


text:
Q: Problem after "sudo apt-get install fglrx-amdcccle" After I enter sudo apt-get install fglrx-amdcccle my Ubuntu 15.04 not enter to desktop and just ask password. When I enter password again ask also change resolution (show big).
What can I do to fix the problem?

A: In your login screen, press ctrl+alt+f1 you should be in tty now, login using your username and password. Now
Issue the commands one by one. Make sure you have a working Internet connection.
sudo apt-get purge "fglrx.*"
sudo rm /etc/X11/xorg.conf
sudo apt-get install --reinstall xserver-xorg-core libgl1-mesa-glx:i386 libgl1-mesa-dri:i386 libgl1-mesa-glx:amd64 libgl1-mesa-dri:amd64
sudo dpkg-reconfigure xserver-xorg
sudo reboot


text:
Q: How do I load an image into the img tag from a python field? I am currently loading an object in HTML using jinja as follows
 {{ object.name }}

The image field is an ImageField in the database. The image URL looks like this
http://127.0.0.1:8000/uploads/testimage.png

How do I render the image correctly in the  tag?

A:
The image URL looks like this
http://127.0.0.1:8000/uploads/testimage.png

This is not the image URL, this {{ object.image }} renders the path to the image in the media directory you specified. But there is (likely) no view listening to this view.
In order to render the images, you use the .url attribute of the FieldFile object, so:
 {{ object.name }}
{% if object.image %}{% endif %}
You should furthermore configure the urls.py to handle a request to these media files. This is explained in the serving files uploaded by a user during development section of the documentation:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # …
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Note that Django does not serve media/static files in production. You will in that case need to configure the webserver like nginx/apache/…


text:
Q: Problem with jenkins pipeline script. No signature of method is applicable for argument types:(java.lang.String) values[string] I have class Emails, that contain loginAndEmaildependency method:
class Emails{
 static List<String> loginEmaildependency (String login){
  Map<String, String> result = new HashMap<>()
  result.put("abc", "abc@gmail.com")
  result.put("cde", "cde@gmail.com")
  ....
  ....
  if(result.get(login.toLowerCase()) != null){
   return [result.get(login.toLowerCase())]
  }
  else {return ["xxx@gmail.com"]}
 }
}

Also I have 2 pipeline scripts:
BuildEmailExt email = null
            if (env.JOB_NAME =~ /TEST-/ || env.JOB_NAME =~ /test-/) {

                def userLogin = currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()

                email = new BuildEmailExt(this, Emails.loginEmailDependency(userLogin.toString()))
                    .jobParams(["gitRepoName"         : env.gitRepoName,
                                "gitBranch  "         : env.gitBranch,
                                "skipInstallationTest": env.skipInstallationTest,
                                "skipDeployNexus"     : env.skipDeployNexus,
                                "dockerImageMq"       : dockerImageMq,
                                "dockerImageWas"      : dockerImageWas,
                                "dockerImageDb"       : dockerImageDb])
            } else {
              email = new BuildEmailExt(this, Emails.repoRecipientEmails(gitRepoName))
                    .jobParams(["gitBranch"      : env.gitBranch,
                                "skipGuiTest"    : env.skipGuiTest,
                                "skipDeployNexus": env.skipDeployNexus,
                                "forceWasInstall": env.forceWasInstall,
                                "dockerImageMq"  : dockerImageMq,
                                "dockerImageWas" : dockerImageWas,
                                "dockerImageDb"  : dockerImageDb])
            }

if (env.JOB_NAME =~ /TEST-/ || env.JOB_NAME =~ /test-/) {

            def userLogin = currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()

            email = new BuildEmailExt(this, Emails.loginEmailDependency(userLogin.toString()))
                .jobParams(["gitRepoName"         : env.gitRepoName,
                            "gitBranch  "         : env.gitBranch,
                            "skipInstallationTest": env.skipInstallationTest,
                            "skipDeployNexus"     : env.skipDeployNexus,
                            "dockerImageMq"       : dockerImageMq,
                            "dockerImageWas"      : dockerImageWas,
                            "dockerImageDb"       : dockerImageDb])
        } else {
            email = new BuildEmailExt(this, Emails.Teams())
                .jobParams(["gitBranch"      : env.gitBranch,
                            "skipGuiTest"    : env.skipGuiTest,
                            "skipDeployNexus": env.skipDeployNexus,
                            "forceWasInstall": env.forceWasInstall,
                            "dockerImageMq"  : dockerImageMq,
                            "dockerImageWas" : dockerImageWas,
                            "dockerImageDb"  : dockerImageDb])
        }

In second script I use this script and all works successfull, but in first script i get exception: No signature of method: java.lang.Class.loginAndEmailDependency() is applicable for argument types:(java.lang.String) values:[abc]
What problem it can be?

A: It wasn't problem with code. It was problem with jenkins settings. Two scripts had different settings and in the second jenkins doesn't seen method "loginEmailDependency"


text:
Q: Ceph source code modifiy I want to modify some source code of ceph and then test it inside cloud based simulator.I want to know how to change ceph source code?? as well as which cloud simulator can be used with ceph?

A: You can modify the source code by following the instructions at Contributing Code in the README file of the sources themselves.
After modifying the code you can run make check and it will create mini clusters to verify the code works as expected.


text:
Q: select a set of products present in all stores all weeks I have a database in postgresql with product_id, store_id, week, price_avg, price_min, price_max and I want to select a set of homogeneous products that it is present in a set of stores and in the same weeks.
I have tried some approaches but it´s difficult since I have 22 million of prices, 2645 different stores and data for 13 weeks.
The goal is to select a set of 20 product_ids that are present in all 13 weeks of  information and that they appear in a set of 10 stores all the time.
First I thought on splitting the database in tables per store and then do an inner join with product_id. But that's costly for SQL.
Second, I took first two weeks in a table. and I run a
select
    count() as quantity, f2.product, f2.key_all_stores
from
    database f2
group by
    product_id, key_all_stores
having
    count() = 2

The having count 2 keeps those products in both week. and then with those products selected I run the following:
select
    count(), product_id
from
    (select
         count() as quantity, f2.product_id, f2.clave_todo_junto
     from
         fer f2
     group by
         producto, key_all_stores
     having
         count() = 2) as subquery
group by
    subquery.product_id
having
    count() = 4

The issue with these two queries is that I am looking at two weeks and doing a sample with 4 different stores.

A:
I have a database in postgresql with product_id, store_id, week, price_avg, price_min, price_max …
  The Goal is to select a set of 20 product_ids that are present in all 13 weeks of information and that they appear in a set of 10 stores all the time.

If all of these columns are still inside a single table, as stated, you may try the following shortcut :
WITH shortlist(product_id,store_id,week) AS
(
    SELECT DISTINCT product_id,store_id,week
               FROM yourtable
              WHERE store_id IN (store1,store2,store3,store4)
                AND week     IN (week1,week2,week3,…)
)

  SELECT product_id,count(*)
    FROM shortlist
GROUP BY product_id
  HAVING count(*) >= 130

You may dismiss the AND row if you're sure that your table contains nothing else than the 13 quoted weeks. Specify the requested store ids the upper one and replace yourtable by the actual name.
The point here is that making a DISTINCT pre-selection first with only concerned fields will get rid of every duplicated row if you have multiple data regarding price for a given price-store-week combination.
Given this, a product that appear all of these 13 weeks in all 10 different stores should produce exactly 130 entries. Thus the final count.


text:
Q: Question about product of invertible matrix Let $A$ be an $n\,\rm{x}\,n$ matrix. Prove that there exists a matrix $B$ of the same size and $B$ is invertible such that $BA$ is upper-triangular.

A: Can you make $A$ upper triangular by performing elementary row operations?
Can you write an elementary row operation as left-multiplication by a simple matrix?
Can you write a sequence of elementary row operations as left-multiplication by a single matrix (which matrix is the product of a bunch of single operation matrices)?

A: We prove this by induction on $n$. For $n = 1$, the statement is obvious.
Let $X$ be the first column of $A$. If $X \ne 0$, there is some invertible $B_1$ such that $B_1 X = (1, 0, \dots, 0)^t$. If $X = 0$, we let $B_1$ be an arbitrary $n \times n$ invertible matrix.
Now write
$$
B_1 A =
\begin{pmatrix}
 * & * \\
0 & A_1
\end{pmatrix},
$$
in block form, where $A_1$ is an $(n-1) \times (n - 1)$ matrix.
By the induction hypothesis, there is some invertible $B_2$ such that $B_2 A_1$ is upper triangular.
Now let
$$
B =
\begin{pmatrix}
1 & 0 \\
0 & B_2
\end{pmatrix}
B_1.
$$
Then $B$ satisfies the required conditions.


text:
Q: C# WebBrowser Control - ignore website security warnings
Possible Duplicate:
How to disable "Security Alert" window in Webbrowser control

I'm currently using WebBrowser (System.Windows.Forms) in my program. When I try to access some websites over https, the message "There is a problem with your websites security certificate" appears. Is there any way I can get WebBrowser to ignore these types of warnings?
There are solutions for WebClient: How to ignore a certificate error with c# 2.0 WebClient - without the certificate
But those solutions do not apply to this problem, as WebBrowser seems to ignore whatever is set in ServicePointManager.

A: You might want to look at http://www.codeproject.com/KB/shell/WebBrowserControlDialogs.aspx from the question Access Intranet via SSL using WebBrowser Winforms Control


text:
Q: How to handle a large number of activities in android studio Iam a student and Iam developing an app for my college for downloading previous year question papers,my college has 14 departments and for each department 8 semesters and in each semester minimum 10 subjects are there so 14*2*8= 1120 java files and XML files I have to create if I keep on intenting from one activity to another it will take a huge time.how handle this huge activities.my app structure would be
Select department(14) >> Select sem(8)>> select subject(10)
Is there any methods like nestedif or something else to reduce the activity files.if there are any methods please do help me to complete the project.thanks in advance

A: No, you don't need that many activities.  You need to write abstract activities that take parameters and displays different data based on those.  At most I see 4 activities here-  department selector, semester selector, subject selector, and the actual subject activity.  And arguably some of those should be fragments instead, although that's more personal choice.


text:
Q: how i can How can I redirect to the correct login page in Laravel carrying different middleware? I made a duplicate of the auth file in the name of admin and modified some related things and everything works fine, but the problem is that when I go to the "/dashboard" link, it is redirected to "login" and I was supposed to be transferred to "dashboard/login" "I think the problem is in the Authenticate.php file, or is it something else? Is there someone who can help me and explain the solution to the problem?

part of admin route code
Route::group(['middleware' => ['guest:admin'], 'prefix'=>'dashboard', 'as'=>'dashboard.'],function(){
Route::get('register', [RegisteredUserController::class, 'create'])->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])->name('password.request');
Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])->name('password.email');
Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])->name('password.reset');
Route::post('reset-password', [NewPasswordController::class, 'store'])->name('password.update');});


text:
Q: Opening multiple directories in C I am trying to make a program that creates a directory in which multiple directories are created, then in each directory I am creating a file. I cannot seem to open those "multiple directories" so that I can put my file there. I tried using name3 as a parameter, and I also tried creating a const char* with name3's value and nothing worked.
error: malloc.c:2379: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed. Aborted (core dumped)
here is my code
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>

int make_directory(char * name) {
    int checker=mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO);
    return checker;
}

char** getNames() {
    char** names=malloc(10*sizeof(char*));
    for(int i=0;i<10;i++) {

        if(i==9) {
            names[i]=malloc(3*sizeof(char));
            names[i][0]='1';
            names[i][1]='0';
            names[i][2]='\0';
        } else {
            names[i]=malloc(2*sizeof(char));
            names[i][0]=49+i;
            names[i][1]='\0';
        }
    }
    return names;
}

int makeTenDirs() {
    char **names=getNames();
    char *name2;
    for(int i=0;i<10;i++) {

        name2=NULL;
        name2=getcwd(NULL,0);
        strncat(name2,"/input/dir",11);
        strncat(name2,names[i],1);
        int s=make_directory(name2);

    }
    name2=NULL;
    name2=getcwd(NULL,0);
    strncat(name2,"/input/dir",11);
    strncat(name2,names[0],1);
    strncat(name2,"0",2);
    int s=make_directory(name2);

}

int main() {
    char **names=getNames();
    FILE *file;
    DIR *dir;
    DIR *dir2;
    struct dirent *dent;
    char * name1="./input";
    char *name3;
    int proceed=make_directory("./input");
    if(proceed==-1) {
        printf("Error making the directory\n");
    }
    makeTenDirs();
    dir=opendir("./input");
    if(dir!=NULL) {
        name3=getcwd(NULL,0);
        while((dent=readdir(dir))!=NULL){
            if(strcmp(dent->d_name,"..")!=0 && strcmp(dent->d_name,".")!=0) {
                name3=getcwd(NULL,0);
                strncat(name3,"/input/",8);

                strncat(name3,dent->d_name,10);
                printf("%s\n",name3);

                dir2=opendir(name3);
                if(dir2!=NULL) {
                    printf("alo");
                }
            }
        }
    }

    closedir(dir);
    free(names);
    return 0;
}

Any tips on how to open the directories (and maybe put the files in them)?

A: Below is a working implementation.  I cleaned up all the warnings (you had some unused variables, makeTenDirs was not returning a value).  Always look at and fix the warnings, use -Wall -Wextra flags to enable them.  As I thought before, you were invoking undefined behavior by overwriting the buffers of name2 and name3.  The way you were using getcwd it was allocating exactly enough space for name2 and name3.  As soon as you strcat to that, you overwrite the buffer, invoking UB.  At that point, the program can behave in completely unpredictable ways, including appearing to work.  You hope your program crashes when there's UB so you're alerted to the problem.  Below, I've used a 2nd operating mode of getcwd that doesn't internally malloc memory and instead keeps everything in automatic memory (on the stack).  This relieves you of having to manage memory manually.  I've included comments that hopefully explain everything, let me know if you have questions.
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <linux/limits.h>  // for PATH_MAX

int make_directory(char * name) {
    int checker=mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO);
    return checker;
}

char** getNames() {
    char** names=malloc(10*sizeof(char*));
    for(int i=0;i<10;i++) {
        if(i==9) {
            names[i]=malloc(3*sizeof(char));
            names[i][0]='1';
            names[i][1]='0';
            names[i][2]='\0';
        } else {
            names[i]=malloc(2*sizeof(char));
            names[i][0]='1'+i;
            names[i][1]='\0';
        }
    }
    return names;
}

int makeTenDirs(char** names) {
    // This is where your problems began.  As I suggested before and confirmed
    // when I actually ran the code, `getcwd(NULL, 0)` returns a pointer to
    // dynamically allocated memory that's just big enough to hold the path.
    // As soon as you strcat to that, you overflow the buffer causing
    // undefined behavior.  It crashed for me 2nd time through the loop, not
    // immediately when the UB occurred.  Your results could be entirely different,
    // that is the essence of UB.  To fix it, I will declare an automatic array
    // of PATH_MAX large (4096 I believe).  That should make this fixed size array
    // able to handle any path on your _linux_ box (this code will not be portable
    // to windows).  Alternatively, you could do what you did before, just be sure
    // to realloc the name2 memory _before_ strcat'ing so there's enough room for
    // "/input/dir"
    char name2[PATH_MAX];
    // only acceptable place for one character variable names are loop index
    // variables, and you'll even get some argument on that.  Give your variables
    // descriptive names (although, I'd probably just make this function void, not
    // much utility in the return value here, which you didn't even return!)
    int directoryMade = 0;

    for(int i=0;i<10;i++) {
        // This returns NULL if the `sizeof name` (==PATH_MAX == 4096) is too
        // small to hold the path.  That shouldn't be the case since no paths
        // on the system should exceed PATH_MAX, but it's always a good idea
        // to check for errors, that's what a lot of your C code should be
        // doing, so get in the habit. Also, realize your old way created
        // a memory leak each time since each call to getcwd would malloc more
        // memory, and you overwrite the pointer to the previous block with the
        // pointer to the new block. Now nothing is pointing at the previous
        // block so you can't free it --> memory leak.
        if (getcwd(name2, sizeof name2) == NULL)
        {
            perror("Path exceeded buffer length");
            exit(-1);
        }
        // should be plenty of space to strcat now
        strncat(name2,"/input/dir",11);
        strncat(name2,names[i],1);
        // not much utility b/c it keeps getting overwritten. You could check it each time
        // and return if there's an error
        directoryMade=make_directory(name2);
    }

    if (getcwd(name2, sizeof name2) == NULL)
    {
        perror("Path exceeded buffer length");
        exit(-1);
    }
    strncat(name2,"/input/dir",11);
    strncat(name2,names[0],1);
    strncat(name2,"0",2);
    directoryMade=make_directory(name2);

    return directoryMade;
}

int main() {
    char **names=getNames();
    DIR *dir;
    DIR *dir2;
    struct dirent *dent;
    int proceed=make_directory("./input");
    if(proceed==-1) {
        // you print an error here, but continue on anyway
        // as if there was no error
        printf("Error making the directory\n");
    }
    makeTenDirs(names);  // you already fetched names, use them!
    dir=opendir("./input");
    if(dir!=NULL) {
        // same problem here. name3 holds _exactly_ how much space it
        // needs when you allow getcwd to malloc memory for it. As before,
        // you can make name3 an array in automatic storage, or realloc it
        // before strcat'ing
        char name3[PATH_MAX];
        // check for NULL return here too. Not showing it because I'm getting lazy
        getcwd(name3, sizeof name3);
        while((dent=readdir(dir))!=NULL){
            if(strcmp(dent->d_name,"..")!=0 && strcmp(dent->d_name,".")!=0) {
                // check for NULL return
                getcwd(name3, sizeof name3);
                strncat(name3,"/input/",8);

                strncat(name3,dent->d_name,10);
                printf("%s\n",name3);

                dir2=opendir(name3);
                if(dir2!=NULL) {
                    // printf is line-buffered, so this won't print right away unless
                    // you put a newline on it (or fflush(stdout);)
                    printf("alo\n");
                    // close this dir too?
                    closedir(dir2);
                }
            }
        }
    }

    closedir(dir);
    // this is NOT a complete free. You have a double pointer. You need to loop and
    // free each of names[0], names[1], .. names[9], _then_ free(names). I'll leave
    // that as an exercise. In general, you should have a matching number of malloc's
    // and free's.
    free(names);
    return 0;
}


text:
Q: OpenCV - native Android integration I have been implemented this project: https://github.com/yaylas/AndroidFaceRecognizer into Android Studio - to my own App. I included OpenCV using tutorial: https://www.youtube.com/watch?v=OTw_GIQNbD8 (this is static initialization) and I created jni folder in src/main and I put these files https://github.com/yaylas/AndroidFaceRecognizer/tree/master/jni into it.
This is Android.mk from this folder:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
OPENCV_CAMERA_MODULES:=on
OPENCV_INSTALL_MODULES:=on
include C:/Users/Piotr/Desktop/Android_App/MyApplication/libraries/opencv/native/jni/OpenCV.mk
LOCAL_SRC_FILES  := DetectionAndRecognition.cpp
LOCAL_C_INCLUDES := C:/Users/Piotr/Desktop/Android_App/MyApplication/libraries/opencv/native/jni/include
LOCAL_LDLIBS     += -llog -ldl

LOCAL_MODULE     := detection_and_recognition_lib

include $(BUILD_SHARED_LIBRARY)

Problem is that, if I try compile project, Android Studio Say:

Error:(2, 33) opencv2/core/core.hpp: No such file or directory

Why it is?

A: this bothers me for while as well, try adding the following:
// begin
sourceSets.main {
    jni.srcDirs = [] //disable automatic ndk-build call
}
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
    commandLine "/your-library-folder/Android/sdk/ndk-bundle/ndk-build",
            'NDK_PROJECT_PATH=build/intermediates/ndk',
            'NDK_LIBS_OUT=src/main/jniLibs',
            'APP_BUILD_SCRIPT=src/main/jni/Android.mk',
            'NDK_APPLICATION_MK=src/main/jni/Application.mk'
}
tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}
//end

into your build.gradle in app folder of your Android Studio project
reference: https://github.com/quanhua92/NDK_OpenCV_AndroidStudio


text:
Q: Creating a task from another task I am trying to create a task from another task. I tried few sources but am not getting any better results. I tried the example given on https://www.instructables.com/id/FreeRTOS-With-Arduino-08-Creating-a-Task-From-Othe/. In the serial monitor it only displays "In Setup function Task3 Running, Creating Task2 and Task4". With reference to creating task inside other task in freertos
I tried checking the value returned by xTaskCreate and printing the return value but that value doesn't print. Can someone help on this? What is it that I am missing?

A: I can't help with project specifics, or instructions on other website, but yes it is perfectly fine to create one task from another.  That is what the strangely named 'death' tasks demonstrate - one of the oldest (very first) standard demo tasks that shipped with FreeRTOS and runs on all the platforms [we support ourselves].


text:
Q: c++ dll windows plugin architecture approach as the title suggests, I'm having trouble with my first approach to plugin architecture and I hope for some advice, but let me be specific...
Suppose you have a pure abstract class BASE with some defined methods...
Suppose also that you have a main executable, and a dll file dynamically linked at runtime with the main executable...
BASE is in a header file included in both the main exe and the dll...
BASE subclasses are defined in the dll, and their abstract methods implemented...
Main exe allocates an array of pointers to BASE.
That array is passed to the dll. The dll creates objects on the heap, and returns the array filled with pointers to instances of those objects.
The problem is, that when I try to call a member method of BASE on one of those instances on the main exe, (which should be overloaded in the dll by the derived class), I get an access violation error.
I'm not passing classes or anything c++ specific through the c interface I have
defined for the main executable and the dll... Just pointers...
This is just for academic purposes really, but still I'm toying with the idea that perhaps different people would create plug ins (dlls) for the main program, so compatibility is an issue.
So I think it is a good idea to keep the dll's interface in c, wouldn't you agree?
I think the dll and the main executable share the same heap space, so
the pointers to the object instances should work, isn't that correct?
On the other hand, a pointer to an object would just give the main program
a place in memory where the instance's variables are stored, but no information about
its methods' code, which the main program knows nothing about, since it's defined in the dll.
So it's logical that without the address of the executable code, it can't
call the abstract classes' method implementation.
Is my speculation correct thus far?
I know I could use function pointers kept inside each object,
but wouldn't that destroy the nice built-in polymorphic mechanism of c++?
Another approach would be, since the abstract methods of BASE are known, to
implement a c-style function (in the dll's c interface), for each BASE class'
methods, with an extra argument, the object's ptr. This way the implemented
method could be handled inside the dll on the specific object. I don't like this idea very much.
Makes the dll's interface bigger and a lot of c functions are used, almost
makes the handling of the derived classes c-style, or at least in need
of wrapping inside other c++ classes. What are your thoughts on it?
What I'm basically asking the community is:
Is the way I'm trying to do it the correct approach? or are my thoughts completely wrong? Am I missing out something important?
What else would you suggest?
Thank you very much for your time and support.
UPDATE:
Since I can't in no way figure out what I'm doing wrong, I will resort to uploading my code...
Main Program - .cpp file
#include "feats.h"

using namespace std;
typedef void* (__cdecl *_connect)(void);

void addFeats(vector<feats::feat*> &vec, void* pluginDllRet) {
    size_t i = 0;
    feats::feat **retVal = (feats::feat**) pluginDllRet;
    while(retVal[i] != NULL) vec.push_back(retVal[i++]);
}

int main(void) {
    HINSTANCE dllFile = LoadLibrary("dllName.dll");
    if(dllFile == NULL) { /*error Handling*/ }

    _connect con = (_connect) GetProcAddress(dllFile, "_connect");
    if(con == NULL) { /*error Handling*/ }

    vector<feats::feat*> featsHolder;
    addFeats(featsHolder, con());

    for(size_t i = 0; i < featsHolder.size(); i++)
        cout << featsHolder[i]->getName() << "\n";
    FreeLibrary(dllFile );
}

Following is the dll file's .cpp file...
#include "feats.h"
using namespace feats;
using namespace std;

extern "C" {
    __declspec(dllexport) void* __cdecl _connect(void) {
        return executableCode();    //<- this is visible in main program
    }
}

namespace feats {
    class acrobatic : public feats::feat {
        public:
        std::string getName(void) {
            return "Acrobatic";
        }
    };

    class powerfull : public feats::feat {
        public:
        std::string getName(void) {
            return "Powerfull";
        }
    };
}

void* executableCode(void) {
    feats::feat **fts = new feats::feat*[3];
    fts[0] = new acrobatic;
    fts[1] = new powerfull;
    fts[2] = NULL;
    return (void*) fts;
}

And last but not least the header in both main program and the dll...
#ifndef FEATS_H
#define FEATS_H

#include <string>

namespace feats {
    class feat {
        public:
        virtual std::string getName(void) = 0;
    };
}
#endif

So with this presented I hope my problem is more clear... I tried to make it as compact as possible... So, thanks again for your help...
UPDATE 2 - Solution
As it seems the above code is correct and working... My problem, working on visual studio was that I compiled the dll in release mode, while the main program was in debug mode. Flipping that fixed the problem...
Such a simple error, causing such contemplation... Anyway,
I'm leaving the above code as an example for future searches...

A: Just define you abstract interface in a header file:
class AbstractBase
{
public:
  virtual int SomeFunction() = 0;

  virtual int SomeOtherFunction() = 0;
};

In that header also define two C functions to create and destory a class:
AbstractBase *CreateClass();

void DestroyClass(AbstractBase *data);

Inside you dll implement the concrete class:
class MyClass: AbstractBase
{
public:
    SomeFunction() {};
    virtual ~SomeFunction() {};

    virtual int SomeFunction() { return 1; }

    virtual int SomeOtherFunction() { return 1; }
};

Inside your dll also implement the create and destroy functions:
AbstractBase *CreateClass()
{
    return new SomeFunction();
}

void DestroyClass(AbstractBase *data);
{
   delete data;
}

Now inside the main executable load the create an destroy dll
entry points at run time.
Call the create entry point to get an object and talk to that
object using the abstract interface.
Call the destroy entry point to destroy the object.


text:
Q: how to use setseed in a function in postgresql I am trying to create a function in postgresq to create a random predictable string (to use as user and password). I wrote the following code:
CREATE OR REPLACE FUNCTION colon.random_user_or_password(integer)
    RETURNS text AS
$BODY$
DECLARE
    letras_o_numeros TEXT[];
    letras_o_numeros_longitud INT;
    rand_user_or_pass TEXT;
    seed REAL;
BEGIN
    letras_o_numeros=array['a','b','c','d','e','f','g','h','i','j','k','l','m','o','p','q','r','s','t','u','b','w','x','y','z','A','B','C','D','E',
                           'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9'];
    letras_o_numeros_longitud=array_length(letras_o_numeros, 1);
    rand_user_or_pass='';
    seed=$1/power(10,ceil(log($1)));
    setseed(seed);
    WHILE char_length(rand_user_or_pass)<8 LOOP
        rand_user_or_pass=rand_user_or_pass||letras_o_numeros[ceil(random()*letras_o_numeros_longitud)];
    END LOOP;
    RETURN rand_user_or_pass;
END
$BODY$
LANGUAGE plpgsql VOLATILE
    COST 100;

but when I try to create the function, it gives me the following error:
    syntax error at or near setseed(seed) in line 15. How is this function used?

A: A function can't be called like that. You either need to use select or in PL/pgSQL if you don't care about the result (which is the case for setseed()) use `perform:
perform setseed(seed);

Or use set seed to 0.5; as shown by lehanh.

A: you can use set seed to 0.5;. Reference: https://til.hashrocket.com/posts/495ed1fb33-set-a-seed-for-the-random-number-generator

A: For use within a function, one should always do a PERFORM for setting the seed.
For example...
CREATE OR REPLACE FUNCTION DETERMINISTIC_RANDOM(p_seed NUMERIC) RETURNS NUMERIC AS $$
BEGIN
  PERFORM SETSEED(p_seed);
  RETURN RANDOM();
END;
$$ LANGUAGE plpgsql;

If you change the PERFORM SETSEED(p_seed); line to SET SEED TO p_seed; it will fail with ERROR:  parameter "seed" requires a numeric value (even though the param is in fact the correct type).


text: Q: Open another form from hyperlink text in RichTextBox in Ms Access form instead using button click I need to open another form or call MessageBox from hyperlink text or a button that is in a RichTextBox control in my Ms Access Application form. Is it possible, if yes, what do I this work?


text:
Q: Is there a way to tell when the result set changes in a MySQL union query? Is there a way to either add a separator or know when the results set has changed in a union query? For example:
SELECT * FROM table1 WHERE name >= 'a' AND name < 'g'
UNION  ALL
SELECT * FROM table1 WHERE name >= 'g' AND name < 'k'

While looping through the results, is there a way while looping through the results to know that it is now going through the results from the second query? I was hoping something simple instead of using PHP to grab the first letter to see if the current result is still between and g or if its now between g and k. Can I add a custom separator field that tells me when the results for the next query is now being accessed? Hope this makes sense.

A: Yes, you can add a computed column to the UNION query, and then sort by it:
SELECT *, 1 AS position FROM table1 WHERE name >= 'a' AND name < 'g'
UNION  ALL
SELECT *, 2 FROM table1 WHERE name >= 'g' AND name < 'k'
ORDER BY position;

This would place the records coming from the a <= name < g query first, followed by the records from the g <= name < k query second.


text:
Q: Effects of passing headers in a requests? I want to know what difference it makes when you pass headers in requests.get i.e. the difference between requests.get(url, headers)  and requests.get(url).
I have these two pieces of code:
from lxml import html
from lxml import etree
import requests
import re

url = "http://www.amazon.in/SanDisk-micro-USB-connector-OTG-enabled-Android/dp/B00RBGYGMO"

page = requests.get(url)
tree = html.fromstring(page.text)
XPATH_IMAGE_SOURCE = '//*[@id="main-image-container"]//img/@src'
image_source = tree.xpath(XPATH_IMAGE_SOURCE)
print 'type: ',type(image_source[0])
print image_source[0]

this whose out put is a url as you'd expect. But this:
from lxml import html
from lxml import etree
import requests
import re

url = "http://www.amazon.in/SanDisk-micro-USB-connector-OTG-enabled-Android/dp/B00RBGYGMO"
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'}
page = requests.get(url, headers=headers)

tree = html.fromstring(page.text)
XPATH_IMAGE_SOURCE = '//*[@id="main-image-container"]//img/@src'
image_source = tree.xpath(XPATH_IMAGE_SOURCE)
print 'type: ',type(image_source[0])
print image_source[0]

has an output that starts with data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoIC
I'm guessing this is the actual image without the rendering, just plain data. Any idea how I could keep it in url form? In what other ways does the presence of a header affect the response we get?
Thank You

A: Save the first code's response to html file and open in your browser:

as you can see, you are banned by amazon without headers.
use this xpath:
XPATH_IMAGE_SOURCE = '//*[@id="main-image-container"]//img/@data-old-hires'

out:
type:  <class 'lxml.etree._ElementStringResult'>
http://ecx.images-amazon.com/images/I/617TjMIouyL._SL1274_.jpg

this is raw html data:
<img alt=".." src="
data:image/webp;base64,UklGRuYIAABXRUJQVlA4INoIAACQQQCdASosAcsAPrFWpEqkIqQhIxN6gIgWCek6r4bUf/..."
data-old-hires="http://ecx.images-amazon.com/images/I/617TjMIouyL._SL1274_.jpg"

the picture url is in data-old-hires attribute.


text:
Q: contentful is not imported into next 13 typescript import {createClient} from "contentful";

const client = createClient({
  space: "*",
  accesToken: "*",
});

export default client;

ERROR: Module '"contentful"' has no exported member 'createClient'. Did you mean to use 'import createClient from "contentful"' instead?


text:
Q: SQL Query Optimization, looking at first x number of records This query works, but is there a better way to write this query?  The current one seems slow.  The scenario is very straight forward.
I have two tables, Customers and Payments.  The Customers table has what you would expect with Customer info.  The Payments table keeps track of the monthly payments that a Customer makes.  It has a few fields we need to look at - DueDate, PaymentDate, and CustomerID.
The query I want is I want all Customers who were late by at least 3 months in their first 12 payments.  The query I have is below, but it seems to be pretty slow.  Is there a better way to write this, than what I have below?
SELECT  CustomerID
FROM    Customers AS C
WHERE   EXISTS ( SELECT DueDate, CustomerID, PaymentDate
                 FROM   ( SELECT TOP 12 *
                          FROM      Payments as P
                          WHERE     P.CustomerID = C.CustomerID
                          ORDER BY PaymentDate
                        ) AS First12Payments
                 WHERE  DATEDIFF(MONTH, First12Payments.DueDate, First12Payments.PaymentDate) > 3 )

Thanks!

A: Well, the suggestions in the comment by Joe Enos and Brandon are great. However, if you can't add that column there 2 minor changes to your SQL statement that will probably make it a little bit faster. to make it better you will probably need to add indexes to columns DueDate and PaymentDate in Payments table.
SELECT  CustomerID
FROM    Customers AS C
WHERE   EXISTS ( SELECT 1 -- no need for a columns list since you only check for existance
    FROM (SELECT TOP 12 DueDate, PaymentDate -- no need for all the columns, only the ones you use
          FROM      Payments as P
          WHERE     P.CustomerID = C.CustomerID
          ORDER BY PaymentDate
         ) AS First12Payments
        WHERE  DATEDIFF(MONTH, First12Payments.DueDate, First12Payments.PaymentDate) > 3


text:
Q: Unable to display Data View result in Power shell I am new to azure data explorer and Kusto Queries. I am learning from below online sample
https://dataexplorer.azure.com/clusters/help/databases/Samples
Here is the query which i am getting results in Data Explorer but unable to display in power shell
   StormEvents
   | where DamageProperty >0
   | limit 2
   | project StormSummary.TotalDamages

Below is reference link for code which i am trying to run query in Powershell (Example2 in below link page)
https://learn.microsoft.com/en-us/azure/data-explorer/kusto/api/powershell/powershell
I had changed only "$Query" and modified last code line as like below
 $dataView | Format-Table -AutoSize

i am getting output as
  StormSummary_TotalDamages
  -------------------------
 {}

I tried modifying query without "TotalDamages" in "StormSummary.TotalDamages" but  resulting dataview which i am unable to get again "TotalDamages" .
 StormSummary
  ------------
 {TotalDamages, StartTime, EndTime, Details}

A: Some one helped me to fix my issue. I am posting it to helps others.
Explanation:
Query result is importing to Json string, converting it from json and converting the columns&rows data-layout back into individual PSObjects really helped my issue.
Code:
As per the Example 2 mentioned in my question . we are calling
 $reader = $queryProvider.ExecuteQuery($query, $crp)

After this I removed existing code and modified like below:
Modified Code to get Projected Field data(TotalDamages):
 $json = [Kusto.Cloud.Platform.Data.ExtendedDataReader]::ToJsonString($reader)
 $data = $json | ConvertFrom-Json

 $columns = @{}
 $count = 0
 foreach ($column in $data.Tables[0].Columns) {
   $columns[$column.ColumnName] = $count
    $count++
 }
$items = foreach ($row in $data.Tables[0].Rows) {
$hash = @{}
foreach ($property in $columns.Keys){
    $hash[$property] = $row[$columns[$property]]
}
[PSCustomObject]$hash
}
foreach($item in $items)
{
   Write-Host "TotalDamages: "$item.StormSummary.TotalDamages
 }

Output:
  TotalDamages:  6200000
  TotalDamages:  2000


text:
Q: Factorial CodeChef error (C++) I'm getting WRONG ANSWER on CodeChef for the following problem even though my answer exactly matches the output. Please help.
PROBLEM:
For any positive integer N, Z(N) is the number of zeros at the end of the decimal  form of number N!.
Input
There is a single positive integer T on the first line of input (equal to about 100000). It stands for the number of numbers to follow. Then there are T lines, each containing exactly one positive integer number N, 1 <= N <= 1000000000.
Output
For every number N, output a single line containing the single non-negative integer Z(N).
Example
Sample Input:
6
3
60
100
1024
23456
8735373

Sample Output:
0
14
24
253
5861
2183837

My code:
`#include<iostream>
 #include<math.h>
 #include<vector>
 using namespace std;

 long long int z(long long int n)
 {    long long int p = 1, count = 0;
 while(n>(pow(5,p)))
 {
    count = count + n/(pow(5,p));
    p++;
 }
 return count;
 }

int main()
{
    long long int T,n;
    cin>>T;
    vector<long long int> myVector;

    for (int i=0; i<T; i++)
    {
        cin>>n;
        myVector.push_back(z(n));
    }

    for(int k=0; k<T; k++)
    {
        cout<<myVector[k]<<endl;
    }
}

A:
while(n>(pow(5,p)))

while(n>=(pow(5,p)))

Also:

*

*You can use n/=5 while n instead of using pow.

*You don't need extra braces in condition.

*You can output result without pushing it into vector.


text:
Q: Появление круглого блока Хочу реализовать следующее: при нажатии на кнопку во все стороны разъезжается круглый блок. вот пример на буржуйском сайте (смотрите кнопки meira и adstod).
Как я понимаю: есть у меня кнопка, есть большой div со скругленными углами изначально скрытый (display: none ?). А как быть дальше - не знаю. буду рад любым наводкам и помощи. заранее спасибо!

A:

var growth = false;
var get = function(obj) {
  return document.getElementById(obj)
};
get('two').onclick = function() {
  if (growth) {
    get('one').style.width = '50px';
    get('one').style.height = '50px';
    get('one').style.left = '0px';
    get('one').style.top = '0px';
    growth = false
  } else {
    get('one').style.width = '500px';
    get('one').style.height = '500px';
    get('one').style.left = '-250px';
    get('one').style.top = '-250px';
    growth = true
  }
}
body {
  margin: 0;
}
#one {
  width: 50px;
  height: 50px;
  border-radius: 500px;
  background-color: black;
  transition: 0.5s;
  position: absolute;
}
#two {
  width: 50px;
  height: 50px;
  z-index: 5;
  border-radius: 50px;
  background-color: white;
  position: absolute;
}

A:

document.getElementById('button').addEventListener('click', function() {
  this.classList.toggle('button_active');
});
.container {
  position: relative;
}

.button {
  position: absolute;
  top: 0;
  left: 0;
  height: 30px;
  width: 30px;
  background-color: red;
  border-radius: 50%;
  transition: all .3s ease;
}

.button_active {
  height: 300px;
  width: 300px;
  transform: translate(-25%, -25%);
}


text:
Q: Reading/writing files to/from a struct/class I'd like to read a file into a struct or class, but after some reading i've gathered that its not a good idea to do something like:
int MyClass::loadFile( const char *filePath ) {

            ifstream file ( filePath, ios::in | ios::binary );

            file.read ((char*)this, 18);

            file.close();

            return 0;

        }

I'm guessing if i want to write a file from a struct/class this isn't kosher either:
void MyClass::writeFile( string fileName ) {

        ofstream file( fileName, ofstream::binary );

        file.write((char*)this, 18);

        file.close();

    }

It sounds like the reason i don't want to do this is because even if the data members of my struct add up to 18 bytes, some of them may be padded with extra bytes in memory. Is there a more correct/elegant way to get a file into a class/struct like this?

A: The preferred general technique is called serialization.
It is less brittle than a binary representation. But it has the overhead of needing to be interpreted. The standard types work well with serialization and you are encouraged to make your class serialize so that a class containing your class can easily be serialized.
class MyClass {
     int x;
     float y;
     double z;
     friend std::ostream& operator<<(std::ostream& s, MyClass const& data);
     friend std::istream& operator>>(std::istream& s, MyClass& data);
};

std::ostream& operator<<(std::ostream& s, MyClass const& data)
{
    // Something like this
    // Be careful with strings (the input>> and output << are not symmetric unlike other types)
    return str << data.x << " " << data.y << " " << data.z << " ";
}

// The read should be able to read the version printed using <<
std::istream& operator>>(std::istream& s, MyClass& data)
{
    // Something like this
    // Be careful with strings.
    return str >> data.x >> data.y >> data.z;
}

Usage:
int main()
{
    MyClass   plop;
    std::cout << plop;  // write to a file
    std::cin  >> plop;  // read from a file.

    std::vector<MyClass>  data;

    // Read a file with multiple objects into a vector.
    std::ifstream  loadFrom("plop");
    std::copy(std::istream_iterator<MyClass>(loadFrom), std::istream_iterator<MyClass>(),
              std::back_inserter(data)
             );

    // Write a vector of objects to a file.
    std::ofstream   saveTo("Plip");
    std::copy(data.begin(), data.end(), std::ostream_iterator<MyClass>(saveTo));

    // Note: The stream iterators (std::istream_iterator) and (std::ostream_iterator)
    //       are templatized on your type. They use the stream operators (operator>>)
    //       and (operator<<) to read from the stream.
}

A: The answer is : there is no silver bullet to this problem.
One way you can eliminate the padding to ensure that the data members in your class is to use(in MSVC which you are using)
#pragma pack( push, 1 )

class YourClass {
    // your data members here
    int Data1;
    char Data2;
    // etc...
};

#pragma pack( pop )

The main usefulness of this approach is if your class matches a predefined format such as a bitmap header.  If it is a general purpose class to represent a cat, dog, whatever then dont use this approach.  Other thing if doing this is to make sure you know the length in bytes of the data types for your compiler, if your code is EVER going to be multi platform then you should use explicit sizes for the members such as __int32 etc.
If this is a general class, then in your save member, each value should be written explicitly.  A tip to do this is to create or get from sourceforge or somewhere good code to help do this.  Ideally, some code that allows the member to be named, I use something similar to :
SET_WRITE_DOUBLE( L"NameOfThing", DoubleMemberOfClass );
SET_WRITE_INT( L"NameOfThing2", IntMemberOfClass );
// and so on...

I created the code behind these macros, which I am not sharing for now but a clever person can create their own code to save named to stream in an unordered-set.  This I have found is the perfect approach because if you add or subtract data members to your class, the save/load is not dependent on the binary representation and order of your save, as your class will doubtless evolve through time if you save sequentially this is a problem you will face.
I hope this helps.


text:
Q: Flash object location Hello i need to know there my flash application is running.
in object src  my domain. but flash running on others domains.
and i want to know where. and send it with request on my server.
Thanks.
sorry for y bad grammar.

A: write some code in your application to send it's domain to a server.
There are also good 3rd party tools that can track your app, i like mochi:
http://www.mochimedia.com/developers/

A: Have a look at: LoaderInfo.url
class Main extends Sprite{

      public function Main(){
           trace(this.loaderInfo.url);
      }

}


text:
Q: Is it possible to generate custom event on s3? I tried to enable notifications in S3 bucket, but i get JSON format long data to my registered email , i want to filter on notifications's attribute such as "object deleted" , "date-time" only, so is it possible ?

A: If you want to either limit the fields returned, or filter the events that get generated, you are going to have to do that yourself.
Easiest way would probably be to have the s3 event notifications sent to a custom lambda function (that you write) that can filter and/or reformat the raw s3eventnotification and then have lambda send it on to your downstream consumer, i.e. via email if you want - but there is nothing built-in to aws to do the filtering/reformatting for you.


text:
Q: Sending push notifications through asp.net windows phone 8 Am trying to send push notifications to windows phone 8 using asp.net. Please guide me.

A: Really, you need to specify whether this is for an app, or a webpage... but I still have answers for you
A simple google search for "asp.net wp8 push notification" revealed this msdn page as the first link. If that page isn't quite what you were looking for, the top 3 links also looked good.
The tutorial walks through it quite nicely, but the basics are,

*

*you have to open a connection to the push notification service using
a client app

*then you create a asp.net page that will push information to the app

*and then you run it.
if you are trying to do this from a website (with no client side app), I've used this implementation of a javascript alert in the past. On my android phone, it looks and works just like a popup notification from an app. I'm thinking it'll be the same for WP8. Note... this will only work if the user is actively viewing the webpage in the browser (not exactly a push notification).


text:
Q: Android: upload file on server PostmanSnapshot
   HttpURLConnection conn = null;
   DataOutputStream dos = null;
   DataInputStream inStream = null;
   String lineEnd = "\r\n";
   String twoHyphens = "--";
   String boundary = "*****";
   int bytesRead, bytesAvailable, bufferSize;
   byte[] buffer;
   int maxBufferSize = 1 * 1024 * 1024;
   try {
    FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
    URL url = new URL(UPLOAD_URL);
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("authToken", authToken);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

    dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes(lineEnd+twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name:\"photo-0\";filename=\"" + selectedPath + "\"" + lineEnd);
    dos.writeBytes("Content-Type: multipart/form-data"+lineEnd+lineEnd);
    dos.writeBytes(lineEnd);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    bytesRead = bytesAvailable;

    while (bytesRead > 0) {
    dos.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    fileInputStream.close();
    dos.flush();
    dos.close();

    } catch (MalformedURLException ex) {
    Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
    Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
    inStream = new DataInputStream ( conn.getInputStream() );
    String str;

    while (( str = inStream.readLine()) != null)
    {
    Log.e("Debug","Server Response "+str);
    }
    inStream.close();

    }
    catch (IOException ioex){
    Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }

This code is for uploading file on server from android app.
Server status is true on running the code but file is not sent over server.
I have attached postman snapshot. Authorisation code is sent in header.
Please help

A: I found something which might help who are looking for the same problem.
It is working. What I was doing wrong is in while loop.
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;
    boundary = "===" + System.currentTimeMillis() + "===";
    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setConnectTimeout(10000);//10 sec timeout
    httpConn.setRequestProperty("Content-Type","multipart/form-data;      boundary=" + boundary);
    httpConn.setRequestProperty("authToken", LoginActivity.authenticationToken);
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}

public void addFilePart(String fieldName, File uploadFile) throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + fieldName+ "\"; filename=\"" + fileName + "\"").append(LINE_FEED);
    writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();
    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();
    writer.append(LINE_FEED);
    writer.flush();
}

public String finish() throws IOException {
    StringBuilder sb = new StringBuilder();
    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }
    return sb.toString();
}

}


text:
Q: Dynamic determination for database I have some entity mapping to a collection in a mongoDB.  However, I have a separate database I want the same code to run against (eg. Constants.db_B).  How can I make this parameter dynamic so I can run this without changing the constant and recompiling?  If I could pass this as a parameter that would be fine too.
@MongoEntity(collection = "sample", database = Constants.db_A)
public class SomeEntity extends PanacheMongoEntity {
}

I tried using ConfigProperty on the Constants class, but it only injects it on a bean instance and not the class itself.
Is this possible?

A: It's not possible right now. This has been issued in the quarkus project.
https://github.com/quarkusio/quarkus/issues/14789
It's not the same casuistry than yours but there's a solution made from the Author of that issue, may be helpful for you
https://gitlab.com/ch3rub1/quarkus-mongo-mutitenant


text:
Q: Flow to Update Entire List Once a Day Okay, I ignorantly stumbled into creating a flow that updates a the Date column for a specific User every 10 min.
Recurrence: 10 min.
Update Item: Site: List: Id: Date: utcNow()
Terminate: Succeeded
The above works. My assumption is if I change the Recurrence to 24 hrs. this action will take place every 24 hrs, yes?
Also, how to I edit the above to my it impact every record on the list, rather than just only mine?

A: If you want to update all the list items, you will need to use the get items action and  Apply to each. Inside the Apply to each control, adding the update list item action to do so.
Example:
https://powerusers.microsoft.com/t5/Building-Flows/Apply-to-each-update-to-all-items-in-the-list/td-p/446536
https://powerusers.microsoft.com/t5/General-Power-Automate/Best-way-to-update-SharePoint-List-every-day-and-few-other/td-p/147198


text:
Q: How do I Scroll parent page to top when child page is click within iframe? When someone clicks on a link within an iframe (child page), how do I get the parent page to scroll to the top? The issue is the child page will remain in the same spot of the page, because the iframe has a lot of height larger than the parent page.
Please note: the parent and child pages are on different sub domains.
I created a demo to show this:
http://www.apus.edu/_test/iframe/index.htm

A: The trick is to append the following onload="window.parent.parent.scrollTo(0,0)" to the iframe and that should do it!

A: Within the Iframe page.
window.parent.ScrollToTop(); // Scroll to top function

On The parrent page:
window.ScrollToTop = function(){
  $('html,body', window.document).animate({
    scrollTop: '0px'
  }, 'fast');
};

A: If you have cross origins (the iframe and the parent have different domains), then just calling window.scrollTo(0,0) won't work.
One solution to cross-origin is to send a trusted message from the iframe to the parent.
Code inside the iframe:
var parent_origin = 'http://your/iframe/domain/here'
parent.postMessage({'task': 'scroll_top'}, parent_origin);

Then code in the parent:
function handleMessage(event) {
    var accepted_origin = 'http://your/iframe/domain/here';
    if (event.origin == accepted_origin){
        if (event.data['task'] == 'scroll_top'){
           window.scrollTo(0,0);
        }
        // you can have more tasks
    } else{
        console.error('Unknown origin', event.origin);
    }
}

window.onload = function() {
    window.addEventListener("message", handleMessage, false);
}

A: Using JavaScript within the iframe, reference the parent and call the scroll() method.
window.parent.scroll(0,0);

(Note. This will not work if the iframe Url is a different domain than the parent.)

A: With animation
           window.parent.scroll({
              top: 0,
              left: 0,
              behavior: 'smooth'
            });


text:
Q: c# Web API calling Post at Endpoint not firing when using React Native Fetch Call API Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace LinkrWebApi.Controllers
{
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [Route("api/values/{country}/{type}")]
    public string Get(string country, string type)
    {

        return "value";
    }

    public class GetResource
    {
        public string countryName { set; get; }
        public string imageLogo { set; get; }
        public string desc { set; get; }
        public string link { set; get; }
    }

    // POST api/values
    public void Post(string countryName)
    {
    }

    // PUT api/values/5
    public void Put(int id, [FromBody] string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}
}

And my Fetch Call:
 fetch('https://localhost:44374/api/values', {
    method: 'post',
    body: "countryName=sc",
    headers: new Headers({
                    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
                })
  }).then(function(response) {
    return response.json();
  }).then(function(data) {
  //navigation.navigate('FinalResource', { companyName: route.params.companyName, imageLogo: route.params.imageLogo, desc: txtD, link: txtL })

  });

But the Post Method in my Web API is not firing, the get works but not the post, can anyone see the mistake?


text:
Q: How to make a field required if the request is POST but if the request is PUT the field not required? (django model) I created a model of 7 fields where all fields blank=True, null=True but one of them is required. The problem is I want to make it required only the the request is a POST otherwise its not required for example: in case if a PUT method users don't need to mention at all.

A: what about making a checker in views.py function itself?
in views.py
def ...(request):
   if request.method == 'PUT':
       if not <field you want>:
           <will run if the field was empty>
       else:
           <will run if there was a value>
   elif request.method == 'POST':
       <will run if the method is POST>

A: You should not base your firlds requirements on your request type, but rather on your props.
I assume that if you're editing a model, you have pre-filled fields, which means you have access to your model data within your component.
SO, instead of focusing on your request type, do something like this:
import React from 'react'

const myComponent = ({ myData = {}}) => {
  return (
    <input type='text' required={ myData && myData.whatever } />
  )
}

export default myComponent

By using this syntax, your field will only be required if you're passing an existing model.


text:
Q: Find the Gradient of $\left \| Ax-b \right \|_2^2$ using Chain Rule We have the Chain Rule for composite matrix-functions,  that given dimensionally compatible functions, then
$\triangledown_Xg(f(X)^T)=\triangledown_Xf^T\triangledown_fg$
So how can I use this Chain Rule to compute the gradient of $f(x) = \left \| Ax-b \right \|_2^2$ without expanding the function like $f(x)=(Ax-b)^T(Ax-b)$?

A: Let $h(x)=Ax-b$ and $g(z) = \|z\|^2$ so that $f = g \circ h$. Show that $\nabla g(z) = 2z$ and $\nabla h(x) = A$.


text:
Q: How to Create Charts With DataTables Inside DataSet does anyone know how can I create different charts with different datatables inside dataset? Let's say I have 3 datatables inside dataset, I want to create 3 charts out with 1 chart=1datatable data. I tried different ways but could not get it work..
This is what I have done so far for my codes:
Chart Chart2 = new Chart();
                Chart2.DataSource = ds;
                Chart2.Width = 600;
                Chart2.Height = 350;

                Chart2.Series.Add(new Series());
                Chart2.Series[0].ChartType = SeriesChartType.BoxPlot;
                foreach (DataTable dt in ds.Tables)
                {
                    List<object> lst2 = dt.AsEnumerable().ToList<object>();

                    foreach (DataRow row in dt.Rows)
                        Chart2.Series[0].Points.AddXY(row["DEPARTMENT"], new object[] { row["MAX"], row["MIN"], row["AVG"], row["PERCENTILE25"], row["PERCENTILE50"], row["PERCENTILE75"] });
                }

                Chart2.Series[0].ChartType = SeriesChartType.BoxPlot;

                //if (dt.Rows.Count > 0)
                //{
                //    string title2 = (tg2.Rows[0]["TITLE"].ToString());
                //    Chart2.Titles.Add(title2);
                //}
                //create chartareas
                ChartArea ca2 = new ChartArea();
                ca2.AxisX = new Axis();
                ca2.AxisY = new Axis();
                Chart2.ChartAreas.Add(ca2);

                //databind
                Chart2.DataBind();
                Chart2.Visible = true;

                AjaxControlToolkit.TabPanel panel = new AjaxControlToolkit.TabPanel();
                panel.HeaderText += item.Text;
                container.Tabs.Add(panel);
                //panel.Controls.Add(tabContent);
                panel.Controls.Add(Chart1);
                panel.Controls.Add(Chart2);

After creating the charts, I would like to add them to the tab panel.
Appreciate if someone can provide me guidance on this for me to continue. Thanks a lot!!

A: Instead of set whole DataSet as datasource of Chart, You can select individual DataTable as given below code.
Chart Chart2 = new Chart();
Chart2.DataSource = ds.Table[0]; //or ds.Table["TableName"] select appropriate DataTable
Chart2.Width = 600;


text:
Q: Can Artifactory and Xray use a common RDS PostgreSQL instance? We already have RDS instance used by Artifactory, and want to deploy Xray. We would like to use the same RDS instance if possible. Configuring the same SQL url/username/password details in for the Xray deployment produced this error:

2021-04-26T16:58:36.852Z [jfxr ] [ERROR] [                ] [sql_layer:253                 ] [main                ] Failed to Initialize xray DB tables: pq: column "name" does not exist

A: There should not be a problem sharing the same DB instance. You should have a dedicated DB schema for each product. The error you got might be related to resources with similar names.
See Artifactory setup and Xray setup.
In the case of Kubernetes, there is a Helm chart to install the whole JFrog Platform using a single PostgreSQL server. You can see how it uses a single setup script to prepare each app's DB schema.


text:
Q: convex hull over selected features I am trying to achieve a convex hull over a feature Set returned by a query. But have been facing the error below which i am not able to figure out
In order to debug to see how the convex hull works i had mocked up features and ran the convex hull for the created poly line features as seen in the below code. This works fine, But the above approach of plotting a convexhull for the feature set fails with the below error.
Error:
1) OPTIONS file:///C:/wip/maps/code/test/proxy.ashx?http://karthikpc:8399/arcgis/rest/se...ver/convexHull Resource failed to load
2) Another is a type error
TypeError
arguments: Array[2]
get message: function () { [native code] }
get stack: function () { [native code] }
set message: function () { [native code] }
set stack: function () { [native code] }
type: "non_object_property_load"
__proto__: Error

Have given my function below.
function bounding_polygon(featureSet){
    var geometries = [];
    var geometries_1 = [];
    var geoms=[];
var symbol =  new
    esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new
    dojo.Color([255,0,0,0.85]), 2);

    //getting geometry from feature set
    var geoms = dojo.map(featureSet.features, function(graphic) {
     return graphic.geometry;
     });
    map.graphics.clear();
     //function that fails
      gsvc.convexHull(geoms,function store_value(result){
    var symbol;
    switch(result.type){
          case "point":
            symbol = new esri.symbol.SimpleMarkerSymbol();
            break;
          case "polyline":
            symbol = new esri.symbol.SimpleLineSymbol();
            break;
          case "polygon":
            symbol = new esri.symbol.SimpleFillSymbol();
            break;
        }
     map.graphics.add(new esri.Graphic(result,symbol));
    },function error_log(error){});

//trying to run the same for manually created geometries
     var new_polyline= new esri.geometry.Polyline(map.spatialReference);
 var other_polyline= new esri.geometry.Polyline(map.spatialReference);
new_polyline.addPath([[103.76794615402221, 1.4416487206261546], [103.76790721700029, 1.4427548269642734], [103.76789991705209, 1.4429139656905441]]);
 other_polyline.addPath([[103.77897404312868, 1.3687951231704805], [103.7789286010334, 1.36900185852713], [103.7788202535522, 1.3694226417416273]]);
 geometries_1[0]=new_polyline;
 geometries_1[1]=other_polyline;

gsvc.convexHull(geometries_1,function store_value(result){
var symbol;
 switch(result.type){
          case "point":
            symbol = new esri.symbol.SimpleMarkerSymbol();
            break;
          case "polyline":
            symbol = new esri.symbol.SimpleLineSymbol();
            break;
          case "polygon":
            symbol = new esri.symbol.SimpleFillSymbol();
            break;
        }
     map.graphics.add(new esri.Graphic(result,symbol));

    },function error_log(error){});

    }

A: Convex hull sample on ArcGIS for Developers site.
This sample shows how to use the Geometry Service convex hull operation to calculate the minimum bounding geometry for the selected points.


text:
Q: Swift: Change the texture of a Sprite Kit object how can i change the texture of a SpriteKit object if a variable changes their value.
Something like:
    var x = 2
    if x == 1 {sprite has texture1}
    else if x == 2 {sprite has texture2}

A: If x is a property then you can use a property observer like this
class Hero: SKSpriteNode {

    var x: Int = 1 {
        didSet {
            switch x {
            case 1: self.texture = SKTexture(imageNamed: "texture1")
            case 2: self.texture = SKTexture(imageNamed: "texture2")
            default: break
            }
        }
    }
}

A: Something like this should work
if x == 1 {
    sprite.texture = SKTexture(imageNamed: "Image1")
} else if x == 2 {
    sprite.texture = SKTexture(imageNamed: "Image2")
}

Hope this helps


text:
Q: Can not read OPC tag value from C# OPCSession until i write a value into tag with external software (UaExpert) in c#:
using Opc.Ua class
1- I initialize an OPCUAServer:
myOPCUAServer = new OPCUAClass(Properties.Settings.Default.OPCServerAddress, Properties.Settings.Default.OPCServerPort, Properties.Settings.Default.OPCServerApplicationName, TagList, false, 1, Properties.Settings.Default.OPCServerNamespace);

1.1
public OPCUAClass(string serverAddres, string serverport, string serverApplicationName, Dictionary<string, TagClass> taglist, bool sessionrenewalRequired, double sessionRenewalMinutes, string nameSpace)
        {
            ServerAddress = serverAddres;
            ServerPortNumber = serverport;
            ServerApplicationName = serverApplicationName;
            ApplicationName = "AB Servicio cosignas y parametros";
            TagList = taglist;
            SessionRenewalRequired = sessionrenewalRequired;
            SessionRenewalPeriodMins = sessionRenewalMinutes;
            OPCNameSpace = nameSpace;
            LastTimeOPCServerFoundAlive = DateTime.Now;
            InitializeOPCUAClient();
            SubscribeItems();

            if (SessionRenewalRequired)
            {
                LastTimeSessionRenewed = DateTime.Now;
                RenewerThread = new Thread(renewSessionThread);
                RenewerThread.Start();
            }
        }

1.2
public void InitializeOPCUAClient()
        {
            var config = new ApplicationConfiguration()
            {
                ApplicationName = ApplicationName,
                ApplicationUri = Utils.Format(@"urn:{0}:" + ApplicationName + "", ServerAddress),
                ApplicationType = ApplicationType.Client,

                SecurityConfiguration = new SecurityConfiguration
                {
                    ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%ProgramData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", ApplicationName, ServerAddress) },
                    TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%ProgramData%\OPC Foundation\CertificateStores\UA Certificate Authorities" },
                    TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%ProgramData%\OPC Foundation\CertificateStores\UA Applications" },
                    RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%ProgramData%\OPC Foundation\CertificateStores\RejectedCertificates" },
                    AutoAcceptUntrustedCertificates = true,
                    AddAppCertToTrustedStore = true
                },
                DiscoveryServerConfiguration = new DiscoveryServerConfiguration
                {
                    BaseAddresses = { "opc.tcp://localhost:4840" },
                    ServerNames = { "UALocalDiscoveryServer" }
                },
                TransportConfigurations = new TransportConfigurationCollection(),
                TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
                ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 360000 },
                TraceConfiguration = new TraceConfiguration()
            };
            config.Validate(ApplicationType.Client).GetAwaiter().GetResult();
            if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
            {
                config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
            }

            var application = new ApplicationInstance
            {
                ApplicationName = ApplicationName,
                ApplicationType = ApplicationType.Client,
                ApplicationConfiguration = config
            };
            application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult();

            string serverAddress = ServerAddress;
            var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + serverAddress + ":" + ServerPortNumber + "/" + ServerApplicationName, useSecurity: SecurityEnabled, discoverTimeout: 15000);

            OPCSession = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult();
            {
                var subscription = new Subscription(OPCSession.DefaultSubscription) { PublishingInterval = 1000 };

                OPCSession.AddSubscription(subscription);
                subscription.Create();
            }
        }

2- I suscribe to tags:
TagList.Clear();

                foreach (string opcTag in tags_opc.Values)
                {
                    TagList.Add(opcTag, new TagClass(opcTag, opcTag));
                }

 myOPCUAServer.TagList = TagList;
 myOPCUAServer.SubscribeItems();

3- I try to read tags after i make sure i am suscribed
MonitoredItem item = OPCSession.Subscriptions.FirstOrDefault()
                .MonitoredItems.Where(mi => mi.StartNodeId.Identifier.ToString().EndsWith(tag_opc)).FirstOrDefault();

            if (item != null)
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = item.StartNodeId;
                nodeToRead.AttributeId = Attributes.Value;

                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
                nodesToRead.Add(nodeToRead);

                // read current value.
                DataValueCollection result = null;
                DiagnosticInfoCollection diagnosticInfo = null;

                OPCSession.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    nodesToRead,
                    out result,
                    out diagnosticInfo);

Note out result
I am using Logix Designer software to access PLC Controller tags, as an OPC Server.
Lets suppose my OPC Server includes:
[003]My_tag.element tag
If i try to read it with C# code:
result[0].StatusCode.ToString()  will be BadNodeIdUnknown
Then i use UaExpert software to write 3 into [003]My_tag.element tag
Afterwards, when i read the same tag with C# code:
result[0].StatusCode.ToString()  will be Good
So it became readable after writing something into it.
Before anything, writing a value into [003]My_tag.element tag through Logix Designer does not solve anything, so it is straightly related to activating something through external software, and not tag value itself.
Any ideas?
Thanks.


text:
Q: geom_line() plot creates weird horizontally layered lines, second question on reducing axis ticks Doing a very simple code in ggplot2 where I have a large df of two columns one showing dates and another percent.
#snippet of df this, goes on for 5,000+ rows

      date        percent
1     1997-04-15  0.78
2     1997-04-16  0.77
3     1997-04-17  0.77
4     1997-04-18  0.77
5     1997-04-21  0.77

# also the dput() of the df not sure if I did this right
structure(list(date = structure(c(9966, 9967, 9968, 9969, 9972,
9973, 9974, 9975, 9976, 9979, 9980, 9981, 9982, 9983, 9986), class = "Date"),
percent = c("0.78", "0.77", "0.77", "0.77", "0.77", "0.79",
"0.79", "0.79", "0.79", "0.79", "0.79", "0.79", "0.79", "0.79",
"0.79")), .Names = c("date", "percent"), row.names = c(NA,

15L), class = "data.frame")
Currently my ggplot() is something simple
ggplot( short_df, aes( date, percent ) ) + geom_line()

I try to plot a small snippet of the df to get a good idea of how the plot is going to look and I was greated by this:

When I do geom_point() the plot seems fine.
My second question is when plotting the entire df the plot seems to include every percent value:

I add scale_y_discrete( breaks = pretty( DF$percent ) ) to the previous code and when I use the short_df the plot seems to split the ticks fine:

However, when I do it on the actual df it shows me a y axis with one tick:

I do get a warning:

Warning message:
  In pretty.default(BSD$percent) : NAs introduced by coercion

A: Your problem is that "percent" is of type character:
str(short_df)

'data.frame':   15 obs. of  2 variables:
 $ date   : Date, format: "1997-04-15" "1997-04-16" "1997-04-17" "1997-04-18" ...
 $ percent: chr  "0.78" "0.77" "0.77" "0.77" ...

As a result, ggplot treats "percent" as categorical, and does not connect lines between categories. Converting "percent" to numeric fixes the problem:
short_df$percent <- as.numeric(df$percent)

ggplot(short_df, aes( date, percent ) ) + geom_line()

Incidentally, the version of the plot that uses geom_point() is not correct. You can see that ggplot is plotting every unique value of "percent" (again, the behavior for character/categorical data types). With "percent" converted to numeric data, ggplot correctly calculates a series of well-spaced axis ticks.


text:
Q: ViewPager findViewById is null after screen rotation in android I'm using a viewPager to display some forms. My problem is when i rotate the screen of the device and the viewPager is created again, it doesn't see the viewPager when he reaches the findViewById, it's always null. I have no idea how to handle it when rotation change.
I tried the onConfigurationChange but it doesn't work, I tried to save the Id of the pager and then retrieve it using that saved id but nothing too. So I'm quite blocked now.
pager = (CustomViewPager) getActivity().findViewById(R.id.pager);
pager.setPagingEnabled(false);

In onViewCreated

A: do this in onActivityCreate of the fragment
pager = (CustomViewPager) getActivity().findViewById(R.id.pager);
pager.setPagingEnabled(false);


text:
Q: JQuery Datatables - Get Column Filter Is there a way in JQuery Datatables to get the current filter status of a column?  I am doing some custom filtering and have bStateSave set to true.  When the page reloads I would like to read out the current filter state in order to populate a different portion on my page.

A: For anybody still looking (like I was):
    var oSettings = oTable.fnSettings();
    $("tfoot input").each(function(i){
        if(oSettings.aoPreSearchCols[i]['sSearch']!=''){
            $(this).val(oSettings.aoPreSearchCols[i]['sSearch']);
        }
    });
    if(oSettings.oPreviousSearch['sSearch']!=''){
        $('.search_field').val(oSettings.oPreviousSearch['sSearch']);
    }

taken from http://www.datatables.net/forums/discussion/992/solved-override-bstatesave-with-osearch-and-aosearchcols/p1


text:
Q: Can't seem to set up url encoding for the Prototype parameters that link_to_remote creates I've been struggling for the past 2 hours to set up url encoding with rails' link_to_remote method.
I'm supposed to be able to submit a user-entered mobile phone number but in the '+4412323424' format.
At present the '+' does not get encoded and as a result the controller receives a white space instead of the '+'.
I've been working with Rails for a while now but I still have many things I need to wrap my head around...

<%= link_to_remote "Add", {:update => 'employees', :url => {:action => 'add_mobile'}, :with => "'employee_mobile = ' + escape($('enter_mobile').value)"}, :class => 'btn_search' %>

This is the HTML that gets generated:

Add

I'm assuming it has to be the parameters within Ajax.Updater that are incorrect?
Can anyone guide me in the right direction?
Thanks!

A: Your parameters is supposed to be an object of objects.
You want it to be something like this:
parameters: { employee_mobile: escape($('enter_mobile').value }

so try this (I am unfamiliar with rails syntax so i'm guessing a bit here):
<%= link_to_remote "Add", {:update => 'employees', :url => {:action => 'add_mobile'},
:with => "'employee_mobile:' + escape($('enter_mobile').value)"},
:class => 'btn_search' %>