text:
Q: The error when extending String in ES6

 'use strict';

 class ReverseString extends String {
   reversed() {
     let res = '';
     for (let i = this.length - 1; i >= 0; --i) {
       res += this[i];
     }
     return res;
   }
 }

 let rs = new ReverseString("wangyang");
 console.log(rs.reversed());

when i run this code, i meet an error:
C:\Users\elqstux\Desktop>node wy.js
C:\Users\elqstux\Desktop\wy.js:14
console.log(rs.reversed());
               ^

TypeError: rs.reversed is not a function
    at Object.<anonymous> (C:\Users\elqstux\Desktop\wy.js:14:16)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at startup (node.js:141:18)
    at node.js:980:3

I can't find the root cause for this error.
the output of console.log(rs); is String {0: "w", 1: "a", 2: "n", 3: "g", 4: "y", 5: "a", 6: "n", 7: "g", length: 8, [[PrimitiveValue]]: "wangyang"}].
Here is my node version:
C:\Users\elqstux\Desktop>node -v
v5.3.0

A: String is currently not subclassable in Node 5.3, according to:
https://kangax.github.io/compat-table/es6/#test-miscellaneous_subclassables
Your example should work fine on Firefox 45+ and Edge 13+


text:
Q: css doesn't work in firefox, but in all other browser it does I have a bit of an issue with Firefox(v30). I'm making a site, using jQuery Fullpage scroller and the whole site works in Chrome(v35), IE(11), Opera(v22), but not in firefox. Some of the stylings appear, like the font and colors, but none of the images or the backgrounds and even the Sections are not displaying properly. Could you look at it please, because I have made another site with the Fullpage script and it's working under firefox and I've used the same method everywhere and now it just doesn't want to work. The address is: http://sikitomi.hopto.org/bts
Here is my index file:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="description" content="">
    <meta name="keywords" lang="en" content="">
    <meta name="robots" content="INDEX,FOLLOW">

    <title>Body Training Solutions</title>

    <link rel="stylesheet" href="./css/style.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="./css/jquery.fullPage.css" type="text/css" media="screen" />

FULL SITE

COMING SOON

UPCOMING EDUCATION COURSES

OUR CLASSES

And here's the style.css I've made:
/* Font */

@font-face
{
    font-family: 'canterbold';
    src: url('canter_bold-webfont.eot');
    src: url('canter_bold-webfont.eot?#iefix') format('embedded-opentype'),
         url('canter_bold-webfont.woff') format('woff'),
         url('canter_bold-webfont.ttf') format('truetype'),
         url('canter_bold-webfont.svg#canterbold') format('svg');
    font-weight: normal;
    font-style: normal;
}

/* Defaults */

html, body, p, h1, h2, h3, h4, h5, h6, div, ul
{
    padding: 0;
    margin: 0;
    font-weight: normal;
    list-style: none;
}

img
{
    border: 0;
    width: auto;
    height: 100%;
}

p img
{
    width: auto;
    height: auto;
}
/* Customisations */

body
{
    background: #fff;
    font-family: 'canterbold';
    color: #fff;
}

#section0
{
    display: inline-block;
    background: url('../img/slide01bg.jpg') no-repeat center center;
    background-size: cover;
}

#section0 .left
{
    position: absolute;
    top: 5%;
    left: 0px;
    width: 36%;
    height: 95%;
    text-align: center;
    font-size: 10vh;
    font-size: 600%;
}

#section0 p
{
    padding: 2% 0px;
}

#section0 .arrow
{
    position: absolute;
    right: 0px;
    bottom: 2%;
    left: 0px;
    width: 36%;
    height: 12%;
    text-align: center;
}

#section1
{
    background: url('../img/slide02bg.jpg') no-repeat center top;
    background-size: cover;
}

#section1 h1
{
    position: absolute;
    top: 4%;
    left: 2%;
    display: inline;
    text-align: left;
    font-size: 8vh;
    font-size: 480%;
}

#section1 .arrow
{
    position: absolute;
    right: 0px;
    bottom: 2%;
    left: 0px;
    height: 12%;
    text-align: center;
}

#section2
{
    background: url('../img/slide03bg.jpg') center bottom;
    background-size: cover;
    text-align: center;
}

#section2 h1
{
    position: absolute;
    top: 1%;
    left: 5%;
    display: inline;
    text-align: left;
    font-size: 8vh;
    font-size: 480%;
    color: #3c3c3c;
    z-index: 10;
}

#section2 .bg
{
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    width: 100%;
    height: 70%;
    background: url('../img/slide03middle.png') no-repeat center center;
    background-size: contain;
    z-index: 0;
    text-align: center;
}

#section2 .arrow
{
    position: absolute;
    right: 0px;
    bottom: 2%;
    left: 0px;
    height: 12%;
    z-index: 10;
    text-align: center;
}

#section2 ul
{
    display: block;
    position: absolute;
    right: 0px;
    bottom: 0px;
    left: 0px;
    height: 37%;
}

#section2 li
{
    width: 33%;
    height: 35%;
    display: inline-block;
    font-size: 0;
}

#section3
{
    background: url('../img/slide04bg.jpg') center bottom;
    background-size: cover;
}

Any help appreciated, because this is really driving me nuts at this stage... :(
Thanks a lot!

A: the doctype is missing, try adding <!DOCTYPE html>before the  tag

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter in MSSQL query fails to match "identical" strings when they include a special character. How can this be rectified? We use a PHP script to read data from an API.  For each returned record, we compare a field from that record with data in a MSSQL database.  Different logic is implemented depending on whether or not these two fields (strings) match.
Matches are case-insensitive and we also do not care about trailing/leading white space.
//value of $p['organizationName'] = 'Forté Initiative'
$groupNameForMatching = trim(strtolower($p['organizationName']));

//there is a group name in this table = 'Forté Initiative'
$matchCountPrep=$conn->prepare("SELECT COUNT(*) AS MatchCount FROM schema.table WHERE LOWER(LTRIM(RTRIM(GroupName))) = :OrganizationName);
$matchCountPrep->bindParam(":OrganizationName", $groupNameForMatching);
try {
    $matchCountPrep->execute();
}
catch (PDOException $matchCountError) {
    echo "ERROR: " . $matchCountError->getMessage();
    exit();
}
$matchCount=$matchCountPrep->fetchColumn();

This code works as expected for all groups which do not contain special characters.  For example:
"Chess club " and "Chess Club" match and the value of $matchCount = 1 for this group.
However "Forté Initiative" and "Forté Initiative" somehow do not match, even though they are identical strings.  I believe this is probably due to the character encoding used for the character "é".
I do not have administrative nor dba access to the database server or instance.  I do have administrator access to the web server and PHP configuration executing the script.  However, this script will be migrated to another web server which I do not have administrative access to in the near future.
For the above reasons, I am looking for an in-code solution.  Is there a way to force like-encoding on the two strings while making the comparison in the filter clause of the query?
Thank you for any suggestions.  This is my first posting on Stack Overflow so please let me know if my question is lacking in any way and I will update.  I appreciate your help!
EDIT:
I received guidance on another site which led me to the problem with my code and two solutions.
The problem is that strtolower is not a multi-byte safe function and will not preserve native encoding.  The accented character's encoding is broken when I use it.  Additionally I was operating under a false assumption that the string comparisons would be case sensitive.  The entire need for using strtolower does not actually exist.
Solution one:  use mb_strtolower instead of strtolower.  mb_strtolower successfully preserves the encoding and the MSSQL comparison behaves as expected when this function is used.
Solution two:  compare the strings after trimming the white space but without forcing either side of the comparison to lower case.  The filter clause of the query will still evaluate the strings as matching even if they do not match strictly by case.  NOTE: this is true by default, but may not be true in all environments depending on the collation of your database.


text:
Q: Levy's Theorem (a form of CLT for random variables with infinite variance) Possible extension to Levy's Theorem e.g., Theorem 3.8.2 of Durrett (p 186, version 5 of ``Probability: Theory and Examples").
Theorem 3.8.2 of Durrett (p 186) is, roughly speaking, a kind of form of the CLT for random variables with infinite variance: Loosely, the sum of i.i.d. random variables with a stable distribution converges in distribution to another stable distribution as the number of terms in the sum tends to infinity.
My question is: Does there exist a version where the random variables are independent but NOT identically distributed? This may often be the case in applied examples in engineering or economics? For example, is the following result true for random variables with a power law distribution (each has the same tail index)?
Theorem?
Let $\alpha$ be a constant, satisfying $0 < \alpha < 2$. $ \, $
Suppose $X_1, X_2, \ldots$ are independent random variables drawn from distributions that
satisfy
$P(X_j > x) = c_j \, x^{-\alpha}$, where $c_j$, for each $j \geq 1$, are constants, with $0 < c_j < \infty$.
Let $S_n = X_1 + ~ \ldots ~ + X_n$.
Then there exist constants $a_n$ and $b_n$ such that as $n \rightarrow \infty$,
$ \, $ $(S_n ~ - ~ b_n ) / a_n$ $~ \rightarrow Y$ where $Y$ has a nondegenerate stable distribution.
Does anyone know of such a result? In essence, I am hoping that one can extend Theorem 3.8.2 of Durrett analogously to how Lyapunov's form of the CLT relaxes Lindeberg's form of the CLT to variables that may have different means and variances. Does anyone have a reference, a proof or a counterexample? This is for an application - its not my homework!


text:
Q: Proprieties of the solutions of the Cauchy problem associated to $f'' = -f$ Consider the Cauchy problem $$f'' (x) = -f(x)$$ with initial conditions $f(0) = 0$ and $f'(0) = 1$.
I know that it has one (and only one) solution $f$, namely $f = \sin x$, but my endgame here is to define $f:=\sin x$ and $f' := \cos x$.
What I need to prove is the following:

Let $f$ be the unique solution of the Cauchy problem. Then

*

*$f^2(x) + f'^2(x) = 1$;

*$f(x+y) = f(x)f'(y) + f(y)f'(x)$;

*$f'(x+y) = f'(x)f'(y) - f(x)f(y)$;

*there exists $\epsilon > 0$ such that for all $x \in (0,\epsilon)$ we have $0 < f(x) < x < \frac{f(x)}{f'(x)}$.

How do I do this?

A: By multiplying both sides of (1) by $f'(x)$, one obtains
$$ f(x)f'(x)+f'(x)f''(x)=0 $$
or
$$ \frac{d}{dx}[f^2(x)+f'^2(x)]=0 $$
and hence
$$ f^2(x)+f'^2(x)=C $$
By using the initial conditions, one can have $C=1$ and so Part 1 is done.
For Part 2, let
$$ F(x)=f(x+y)-f(x)f'(y) - f(y)f'(x) $$
and then
\begin{eqnarray}
F'(x)&=&f'(x+y)-f'(x)f'(y) - f(y)f''(x)=f'(x+y)-f'(x)f'(y) + f(x)f(y),\\
F''(x)&=&f''(x+y)-f''(x)f'(y) + f'(x)f(y)=-f(x+y)+f(x)f'(y) +f'(x)f(y).
\end{eqnarray}
So $F(x)$ is a solution of the DE
$$ F''(x)=-F(x) $$
Noting that $F(0)=0,F'(0)=0$, by the Existence and Uniqueness Theorem of DEs, one has $F(x)\equiv0$, namely
$$ f(x+y)=f(x)f'(y)+f(y)f'(x). $$
Repeating the above, it is easy to get Part 3. Note $f'''(x)=-f'(x)$ and $f''(0)=f(0)=0$. Since $f'(0)=1$, there is $\epsilon>0$ such that in $(0,\epsilon)$, $f'(x)>0$. Now using the Taylor expansion of $f(x)$ in $(0,\epsilon)$ at $x=0$ up to order 3, one has
$$ f(x)=f(0)+f'(0)x+\frac12f''(0)x^2+\frac16f'''(c)x^3=x-\frac16f'(c)x^3<x, c\in(0,\epsilon).$$
Let $g(x)=f(x)-xf'(x)$. Then $g(0)=0,g'(0)=0,g''(x)=xf'(x)$ and
$$ g(x)=g(0)+g'(0)x+\frac12g''(c)x^2=\frac12g''(c)x^2>0,c\in(0,\epsilon) $$
which implies $f(x)>xf'(x)$ or $x<\frac{f(x)}{f'(x)}$. So Part 4 is done.


text:
Q: Remote debugging error using JDWP from a JUnit test I am using Eclipse Juno w/ Maven and have a JUnit test which uses Jemmy to start up another Java application and run automated testing on it via event queue. Because of limitations of the application being tested, and we want to run multiple instances of the application, it has to be run in its own process.
So the main class I run my JUnit test from sets up the environment, then creates a process via ProcessBuilder, and executes that process to spawn a Jemmy worker & target application in the same process/jvm.
My problem is that I want to debug the spawned process and I seem to be unable to do so following all the other Eclipse remote debugging guides. My processbuilder looks like this
ProcessBuilder builder = new ProcessBuilder(
                javaBin,
                "-Xmx512M",
                "-Xdebug",
                "-Xrunjdwp:transport=dt_socket,address=8002,server=y,suspend=y",
                "-cp", classpath, "-Djava.library.path=./native", "-D"
                        + PID_PROP + "=" + newPid, MyJemmyTestHarness.class
                        .getCanonicalName());

No matter what port I specify I get the same error
ERROR: transport error 202: bind failed: Address already in use

I've tried dozens of ports, ones I know that are not in use, and the processbuilder simply refuses to start with a JDWP port open. So I think I have a systematic problem with how I'm trying to do this but I am not very experienced in this area. I have followed the remote debugging guides almost to the letter e.g.:
Remote debugging a Java application
http://javarevisited.blogspot.nl/2011/02/how-to-setup-remote-debugging-in.html
Yet the Address Already in Use error persists. Any ideas?


text:
Q: How to get FB access_token from python console app? I have a console application that should get a list of people who liked my page.
As far as I understood I should run something like
QUERY = 'SELECT user_id FROM like WHERE object_id=__MY_PAGE_ID__'
url = "https://graph.facebook.com/fql?q=" + QUERY
data = requests.get(url)

but iI need to use some access token, and I don't understand what kind of. I have log and pass for user with administrative rights on this PAGE. But thay said that I can't get user token without interacting with web browser.
So I need to use app? Should I create it before somehow? How can you allow this app to get admin account on the page?
Thanks


text:
Q: How to make Finder remember the column width of List View? I always use List View in Finder. When I open a new Finder window, the "Name" column is too narrow to see the full file name. (Like the screenshot below.)
Sometimes Finder column width of List View is so narrow
So, is there any way to make Finder remember the column width of List View, or change the default column width?
I did some search, and there's one solution said "press option key at the same time of changing column width" ... but that's work for "Column View", instead of column of "List View". So, please don't repeat that solution.
My operating system is macOS Catalina 10.15.2 ... It's said to that this issue is a Catalina bug, is that true ?


text: Q: How could I modify/alter setup content in typo3 template? I am a newbie to typo3. I have installed 10.2.2. Typo3 does not allow me to alter or modify content in template setup. It seems something I might have missed in installation. I am a window user. Kindly guide me to sort out this one. I have attached the screenshot below:


text:
Q: Azure Test Plans: Track Manual Tests across multiple projects Azure Devops Server Test plans: Is there any way to record manual Test case work items for the same product on separate projects to make them easier to relate/query?
I could modify the test case work item to include a product name, thus enabling creation of a query over all projects for a single product. Is the better way to handle this problem?

A: You can try the following methods:

*

*Similar to as you have mentioned, you can add a same tag to all the of the Test cases for the same product. For example, you can use the product name as the tag. Then you can create a query to filter these Test cases across projects. For more details, see "Query across or within projects".

*Another method you can try is to link all these Test cases for the same product with a same parent work item (such as an User Story). Then you can track and view all these Test cases under this parent. For more details, see "Link user stories, issues, bugs, and other work items".


text:
Q: How to display intermediate result in a VB calculator program I am writing a simple Visual Basic four function calculator (add, subtract, multiply, and divide) application and I want to display an intermediate result when an operator is pressed.
The Windows form that I have created contains buttons, therefore inputs are only required via mouse clicks on the GUI (no keyboard input)
As defined in the requirements, a complete "problem" will be entered according to the following sequence rules:

*

*A number, followed by

*An operator key, followed by

*Another number, followed by

*Optionally repeat to step 2 (displaying intermediate result as the operator is pressed), or the equals button.

I understand that the changes need to be made in the operator click_events to meet this requirement, but I have no idea how to do it.
here is the code for the add, subtract, multiply, divide, and equals button
Dim txtNumber As String
Dim variable1 As Decimal
Dim variable2 As Decimal
Dim answerResult As Decimal
Dim arithmeticProcess As String

 Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
    If answerResult <> 0 Then
        answerResult = variable1 + variable2
        variable1 = CDec(lblDisplay.Text)
        lblDisplay.Text = ""
        arithmeticProcess = "+"
    Else
        variable1 = CDec(lblDisplay.Text)
        lblDisplay.Text = ""
        arithmeticProcess = "+"
    End If

End Sub

Private Sub btnSubtract_Click(sender As System.Object, e As System.EventArgs) Handles btnSubtract.Click
    variable1 = CDec(lblDisplay.Text)
    lblDisplay.Text = ""
    arithmeticProcess = "-"
End Sub

Private Sub btnMultiply_Click(sender As System.Object, e As System.EventArgs) Handles btnMultiply.Click
    variable1 = CDec(lblDisplay.Text)
    lblDisplay.Text = ""
    arithmeticProcess = "*"
End Sub

Private Sub btnDivide_Click(sender As System.Object, e As System.EventArgs) Handles btnDivide.Click
    variable1 = CDec(lblDisplay.Text)
    lblDisplay.Text = ""
    arithmeticProcess = "/"
End Sub

Private Sub btnEqual_Click(sender As System.Object, e As System.EventArgs) Handles btnEqual.Click
    variable2 = lblDisplay.Text
    If arithmeticProcess = "+" Then
        answerResult = variable1 + variable2
    ElseIf arithmeticProcess = "-" Then
        answerResult = variable1 - variable2
    ElseIf arithmeticProcess = "*" Then
        answerResult = variable1 * variable2
    Else
        answerResult = variable1 / variable2
    End If

    answerResult = Math.Round(answerResult, 9)
    Select Case answerResult
        Case Is > 4000000000
            MessageBox.Show("The answer is too large to be displayed.")
            variable1 = 0
            variable2 = 0
            lblDisplay.Text = ""
        Case Is < -4000000000
            MessageBox.Show("The answer is too small to be displayed.")
            variable1 = 0
            variable2 = 0
            lblDisplay.Text = ""
        Case Else
            lblDisplay.Text = CStr(answerResult)
    End Select

End Sub

A: First, I need to politely point out that I think you're going to run into issues with your logic as you continue with this program, but figuring that out is part of the fun of programming. You may want to step back and flow-chart your calculator application, and then get back into it.
Now, what does the code for your number buttons (0-9) look like, specifically, how do you know if the user is typing variable1 or variable2? Assuming you're performing that operation in a 'logical' way, here's what I would do:

*

*Dim variable1 As Decimal = 0 to give your numbers a 'default value' of sorts, and do the same for variable2.

*Pull the code out of btnEqual_Click and put it in its own method, let's call it Public Sub DoMaths(), then simply put DoMaths() in btnEqual_Click(...).

*For every 'arithmeticProcess' button (plus, minus, ...) you are also going to call DoMaths() after doing what you already are.

Now here's the tricky part. You'll have to carefully track which variableX you're displaying on the screen at a given time.

*In DoMaths(), after performing your calculations, you're going to want to move the value of answerResult to variable1, and reset variable2 to zero. I would put this at the end of your Case Else block.
Case Else
    lblDisplay.Text = CStr(answerResult)
    variable1 = answerResult
    variable2 = 0

This puts you back to a state where you would be if the user had just entered in their first number (variable1) and is ready to press the next arithmetic operator key.

Edit, in response to your digit button code:
First, a suggestion: txtNumber += "1" should really be txtNumber &= "1". Although there are arguments otherwise, plus is for adding numbers, ampersand is for concatenating two strings.
Second, in order to achieve intermediate calculations like you desire, you're going to have to keep track of whether or not a "final calculation" (with the Equals key) has been performed. I suggest doing this by using your variable1. When any Plus/Minus/Equals/etc.. button is pressed, you can [generally] assume there is nothing to be done, so long as variable1 is zero.

*

*The user types in a number, then presses an arithmetic key. You store the arithmetic operator (as you already are) and move the number to variable1.

*Now the user enters a second number, which you store in variable2 because variable1 is non-zero.

*The user then has two options: 1. press the Equals key and perform logic normally, or press another arithmetic key and continue calculating. In the second case, perform the action on your two variables, display the result and store it in variable1, and clear the values of variable2 and arithmeticProcess.

Now, you're essentially back in the same place you would be if the user had just started the application, and entered the first number in the calculation. You should be able to continue as normal from here.


text:
Q: Java HTTP full duplex I have a RESTful web service running on Jersey (GlassFish 3.1.1). This one's a bit unusual - it uses HTTP streaming. The client and server have a long running conversation in which they keep sending each other messages encoded as XML tags. The main reason for doing this is so the server can push to the client.
I have a test client that uses HttpURLConnection. The problem is that the either the client's OutputStream or server's InputStream are being closed prematurely. When I try to send a bit of XML from the client, I get a ProtocolException thrown (cannot write output after reading input).
When I test using WizTools RESTClient, I can post an XML request, but this tool doesn't allow for keeping the connection alive. But at least I know the web service is functioning at least in this scenario. (It's probably just fine in the streaming scenario; my guess is the HttpURLConnection is letting me down.
Is there a way to make the HttpURLConnection stay alive and give me the chance to actually send something to the OutputStream? And, on top of that, is there a way to allow it to keep writing to the OutputStream even after it has received data via the InputStream?
Update:
It looks like HttpURLConnection is enforcing the conventional usage of HTTP, namely that a client cannot process the response until it has completely sent the request (and closed the output stream). Is there an alternative that will allow for the request and response to temporally overlap? I just started looking at Apache HttpClient, but I haven't yet found anything to indicate it's possible, so I'm not sure if I'm wasting my time.

A: You are not supposed to write more data after reading from the InputStream because this does not follow the nature of HTTP Protocol which is Request-Response. Check more on this here.


text:
Q: node.js request.get in a loop -> very low perfomance I need to download around 5000 pages, I do it in a loop with request.get() inside like that, so every cycle runs with 400ms timeOut, but that didnt help, after around 1000 cycles, all just freeze and nothing downloaded or  I see Socket hang up errors. I think problem might be in system sockets limit, or something else. Here is my code:
function downloadDescription(url,iterator, downloadDescriptionCallback) {

    request.get(url, function (err, response, body) {
        if (err) {
            if(iterator < 3) {
                setTimeout(function () {
                    downloadDescription(url, iterator, downloadDescriptionCallback)
                }, 1300);
            }else{
                log.warn("Request.get error link iterator limit");
                return downloadDescriptionCallback(null, "");
            }
        }else if (response.statusCode === 404) {
            if(iterator < 3) {//here I just change my Url, cause I dont exactly know the right path, and if I reach 3 iterator limits, I just forget him
                url =  desc_base_url + url.substring(url.indexOf("/", 27) + 1, url.length);
                iterator++;
                setTimeout(function(){ downloadDescription(url, iterator, downloadDescriptionCallback) }, 1300);
            }else{
                return downloadDescriptionCallback(null, body);
            }
        }else{
            return downloadDescriptionCallback(null, body);
        }

    }).on('error', function(err) {
        console.log(err)
    });
};

So after time its around 100-200 cycles, I got a weird behaviour, donwloading time so slow and I even never reach the full 5000 pages, I think I can speedUp my perfomance some with tuning options?


text:
Q: How to create an array of interface of different size in system verilog I have a configurable module which contains an interface for one of the ports. I use a generate statement and a for loop to create different configuration of each module instance and I bring the interface ports out in an array. My issue is the individual interfaces are different based of the config of each module instance. Is there a way to configure each interface in the array individually? This is how I correctly configure the interface
test_if    #(.NUM_CUTS(NUM_CUTS_WRITE_CLIENT),.AW(AW_WRITE_CLIENT),.DW(DW_WRITE_CLIENT)) mem_test_if [NUM_OF_MEMS-1:0]();

Is it possible to do something like this with an array of interfaces
test_if    #(.NUM_CUTS(2),.AW(AW_WRITE_CLIENT),.DW(DW_WRITE_CLIENT)) mem_test_if [0]();
test_if    #(.NUM_CUTS(4),.AW(AW_WRITE_CLIENT),.DW(DW_WRITE_CLIENT)) mem_test_if [1]();
test_if    #(.NUM_CUTS(6),.AW(AW_WRITE_CLIENT),.DW(DW_WRITE_CLIENT)) mem_test_if [2]();

I don't want to have to instantiate each module instance separately outside of the generate statement.

A: You should be able to do this nested inside your generate
for(genvar MEM=0;MEM<NO_OF_MEMS;MEM++) begin : ID
   test_if    #(.NUM_CUTS((MEM+1)*2),.AW(AW_WRITE_CLIENT),.DW(DW_WRITE_CLIENT)) mem_test_if();
end


text:
Q: Log4net always generates a new file inside a Windows Service as a WCF Service Declaring my Logger:
private static readonly ILog Logging = LogManager.GetLogger(typeof(Service1));

My constructor:
public Service1()
{
    InitializeComponent();
    InitializeLogging(@"c:\log\");
}

And this is how I initialize my logger:
public static void InitializeLogging(String Path)
{
    var patternLayout = new PatternLayout()
                        {
                            ConversionPattern = "%utcdate{yyyy-MM-dd HH:mm:ss.fff}"
                                                + "|%level"
                                                + "|%class"
                                                + "|%method"
                                                + "|%line"
                                                + "|%timestamp"
                                                + "|%message"
                                                + "%newline"
                        };

    patternLayout.ActivateOptions();

    RollingFileAppender roller = new RollingFileAppender()
                                     {
                                         AppendToFile = true,
                                         File = Path,
                                         DatePattern = "yyyyMMdd HHmmss'.log'",
                                         Layout = patternLayout,
                                         StaticLogFileName = false,
                                         RollingStyle = RollingFileAppender.RollingMode.Date
                                     };
    roller.ActivateOptions();

    BasicConfigurator.Configure(roller);
}

When the Windows Service isn't started, log4net generates a log file with one line of code, "service started".
When a WCF method is called, log4net generates a new file with one line of log, always. And when the service is stopped, log4net writes in every file "service is stopped".
One log file a day is enough :(

A: I have moved the declaring position for
private static readonly ILog Logging = LogManager.GetLogger(typeof(Service1));
from class Service1 : ServiceBase to static class Program
and I also changed private to public for the Logger and Service1 to Program.


text:
Q: MySQL cannot use ":=" in SSRS I want to assign an index to each row of the query result, I am following this method to achieve that.
This index number is not for displaying purpose, if it is only for displaying, using RowNumber() in SSRS is enough. Instead, I will be using that index number for filtering purpose. Please also note that SSRS cannot use RowNumber() in Filter Expression.
For example, I want the results with index < 10 to be displayed in tablix 1, index >= 10 will be displayed in tablix 2, something like that.
My query works fine in MySQL, until I run it with SSRS, it comes out the error. Looks like SSRS does not support the := operator in @curRow := @curRow + 1 AS row_number. If I remove the colon : from the operator, the error gone, but row number does not increment.
Why SSRS does not support the := operator?  is there any other workaround?

A: I have found a workaround for this case from here

DISCLAIMER:

*

*Does not work on older versions of mySQL It is based on using
  variables that only reset when time changes.

*If the function is invoked in 2 separate places in the same
  microsecond(1 millionth of a second), the output will not be as
  expected. The variable will not reset, the output will not start
  counting from 1.

*If you run the function more than once in the same query, it will
  increment every time it is run, so possibly multiple times per row.

The workaround is to create a MySQL function to generate the row number:
DROP FUNCTION IF EXISTS rownum;
DELIMITER $$
CREATE FUNCTION rownum()
  RETURNS int(11)
BEGIN
  set @prvrownum=if(@ranklastrun=CURTIME(6),@prvrownum+1,1);
  set @ranklastrun=CURTIME(6);
  RETURN @prvrownum;
END $$
$$
DELIMITER ;


text:
Q: Apple mail and a POP3-only mail account I have set up a mail account with Apple Mail. What I realized only when it was "too late", the mail server does not provide IMAP (only for a fee), and thus roundabout 100 E-Mails were downloaded and removed from the server.
Can I somehow upload those emails back up to the server?

A: With a POP account you can't "send" (upload) email to the server.
As "Buscar 웃" told you, if you have another email account (with IMAP of course), you can upload emails from the first account (POP account) to a folder on the second account (IMAP account).
To do that, first you create a new folder on the IMAP account, then you select all the emails you want to "transfer", then do a right-click on the selection and select "Copy To > the folder previously created". I recommend you to copy (Copy To) emails instead of move (Move To) them, to prevent any emails' loss if an error occurs during the transfer.

A: If you have a second email account, send the emails in question back to the first one.
They will appear in your online email.

A: Only by forwarding, POP does not allow uploading/syncing of messages.
But why would you want the mails to be on the server if you already have them on your mac?


text:
Q: How to add Audio into QGIS recorded and geotagged using OSMand app Is there a plugin or easy way of adding audio recordings, recorded and tagged using OSMand app, into QGIS.
I'm using a PC and have no coding knowledge!
I was able to  load the photographs using the "load photos" plugin then pop them up using the eVis plugin.
I understand that I could also use eVis for audio but seems to require a database set up which I don't have.

A: I am just a beginner, and I dont think this is the best way, but it works - so here is my solution:

*

*import the gpx-file as a new layer into qgis, which osmand exports with all the audio-files and pictures

*export this new layer as a new shp-file from qgis and import it again into qgis - now you can edit this layer;

*in the attribute table you can see now all the notes from osmand

*insert a new column (e.g. "path") into the attribute table and fill in the absolute or relative file-paths on your pc to the notes

*start the evis-event browser; in "configure external applications" you can set up for the audio files (3gp files) that qgis should use VLC-Player (or any other player)

*Finished! With the eVis event tool you can click on the layer Points. Images will be shown in the small window; With audio files you have to click on the path and your media player will launch...

If you have a lot of notes I used the following method:

*

*Use directory printer to print a excel (CVS) sheet with information (absolute or relative path to the notes) of all the notes

*add some kind of matching ID in this list so that you can Join this list with your points layer in QGIS

*import this list as text layer to qgis

*use JOIN-function to add the path information from the excel sheet (CSV) to the point layer


text:
Q: Convergence of modified alternating harmonic series I was going thorugh some of my old math quizzes, and found this question, which I am currently unable to solve.

Show that the series converges. $$\sum_{n=1}^\infty a_n\,,\qquad a_n = \begin{cases}2/n & \text{if } 3\mid n \\ -1/n & \text{if } 3\nmid n\end{cases}$$

So here's what I have done.

*

*Well obviously, alternating series wouldn't work.

*I tried to apply the ratio test with $\limsup$, but $\limsup \left\lvert\frac{a_{n+1}}{a_n}\right\rvert = 2$, so the test was inconclusive.

*This series didn't look like it would converge absolutely (to me, at least), so I couldn't rearrange or group the terms and check for convergence.

*So I went online and found this question. Which gave me the idea to consider the $3N$-th, $3N+1$-th, $3N+2$-th partial sums respectively. Well, I could show that each of the partial sums converges, but I thought that wasn't enough because I would have to show that the 3 partial sums converge to the same value.

Should I continue on with my reasoning on 4? Or is there a better way to approach this question?
Any help is greatly appreciated. Thanks in advance.

A: Let $S_n$ be the $n^\text{th}$ partial sum.  You have shown $S_{3n}$, $S_{3n+1}$, and $S_{3n+2}$ each converge.  Since $S_{3n}>S_{3n+1}>S_{3n+2}$, you could try to show

*

*the sequence $(S_{3n})_n$ is strictly monotonically decreasing, acting as successively tighter upper bounds for all subsequent partial sums,

*the sequence $(S_{3n+2})_n$ is strictly monotonically increasing, acting as successively tighter lower bounds for all subsequent partial sums, and

*that $|S_{3n} - S_{3n+2}|$ converges to zero.

You might recognize that this was the method used in the proof of the alternating series test -- the partial sums alternated between an improved upper bound and an improved lower bound for all subsequent partial sums and the gap between the upper and lower bounds goes to zero.
Here, you have three sequences of partial sums -- one gives improving upper bounds, one gives improving lower bounds, and the third is always sandwiched between the other two.  So the bounds are bounds for all the subsequent partial sums.  If you can show the gap between the upper and lower bounds converges to zero, you will have shown that all three sequences of partial sums converge to the same thing, without having to know what that thing is.
(If you didn't have the two monotonicities, you could try to show that $| \lim_{m \rightarrow \infty, n \rightarrow \infty} (S_{3m} - S_{3n+2} )|$ converges to zero; i.e., try to show that the partial sums are enveloped by a Cauchy sequence.)

A: The series converges by Dirichlet's test since the terms are of the form $a_n=b_nc_n$ with $b_n=2$ if $3\mid n$ and $b_n=-1$ otherwise, and $c_n=\frac1n$. The premises of the test are satisfied, since the partial sums of $b_n$ are bounded by $2$ and $c_n$ is monotonically decreasing and converges to $0$.


text:
Q: Python3 custom decode When i migrate my code from python2 to python3.My code is not producing desired result instead it generate error: code snippet and error log as shown below.
import os
import sys
import base64
def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    print(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        print(key_c)
        dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
        print(dec_c)
        dec.append(dec_c)
    return "".join(dec)

contents = "p6KisaignLOinZqgmqKin6OT0uTZ0tSTlaKmpI+klJ+loI"
decodedLicense = decode('crab',contents)

Error Log:
File "s.py", line 16, in decode
    dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
TypeError: ord() expected string of length 1, but int found

A: I have no idea if the final result is correct since you didn't indicate what the desired or expected output was in your question, which makes that very difficult to determine.
Anyhow, as I said in a comment, initially I was getting a different error complaining about the the length of contents having Incorrect padding, so the first thing I did was add something to fix that. Afterwards. I started getting the TypeError: ord() expected string of length 1, but int found exception you did mention in your question.
That was fixed by just using the bytes that base64.urlsafe_b64decode() returned direct and not trying to take their ord().
Here's code with these changes made that at least runs...:
import os
import sys
import base64

def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc).decode('latin1')
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc[i] - ord(key_c)) % 256)  # ord(enc[i]) -> enc[i]
        dec.append(dec_c)

    return "".join(dec)

contents = "p6KisaignLOinZqgmqKin6OT0uTZ0tSTlaKmpI+klJ+loI"  # 46 chars

# Pad contents so its length is a multiple of 3 and it's valid Base64 data.
contents = contents + {0: '', 1: '==', 2: '='}[len(contents) % 3]

decodedLicense = decode('crab', contents)
print(decodedLicense)  # -> D0AOE.;Q?+9>70A=@!q?v`s120EB,23=B.


text:
Q: Intersection of Generic String Literals I have a large object describing different features. For each feature, there may be other fields providing more details, e.g., comments. This may look similar like this:
type Object = {
  a: Feature,
  aComment: string,
  b: Feature
}

Now, I want to make a function which does something with the comments. What I came up with is this:
type Comment<K extends string> = `${K}Comment`;

type RequiredShape<K extends string> = {
  [Key in K]: Feature;
} & {
  [Key in Comment<K>]: string
}

function doSomethingWithComment<K extends string>(
  obj: RequiredShape<K>,
  key: K,
) {
  // no issues here, I can use this as a Feature
  const feature = obj[key];

  const commentKey = `${key}Comment` as Comment<K>;
  const comment = obj[commentKey];

  // now here comment is not treated as string, this won't work
  doSomethingWithLength(comment.length);
}

I want it to only be possible to pass "valid" keys into this function, so keys for which a comment exists in the object. I believe my issue lies somewhere in the type intersection, but don't quite get what's going on there.

A: Typescript is a bit iffy on string template types as well as using them as indexors. Instead cast using as keyof object. Then also assert the comment as as string.
function doSomethingWithComment<K extends string>(
  obj: RequiredShape<K>,
  key: K,
) {
  // no issues here, I can use this as a Feature
  const feature = obj[key];

  const commentKey = `${key}Comment` as keyof RequiredShape<K>;
  const comment = obj[commentKey] as string;

  doSomethingWithLength(comment.length)
}

TS Playground Link


text:
Q: Menu page not showing in WP Admin section I have a WordPress eCommerce website in this website all working but admin menu page not working and the page showing blank, and I was trying to add a new image that image does not upload and not showing the old image in media library only loading process see attachment

A: In order to solve this issue, you need to see what error is causing this blank page. By default, PHP suppresses errors display for security reasons, but Wordpress has a setting to show the errors.
In order to turn on error display, open your wp-config.php in the root folder
And add these two lines:
define( 'WP_DEBUG_DISPLAY', true );
define( 'WP_DEBUG', true );

NOTE: You must insert this BEFORE /* That's all, stop editing! Happy blogging. */ in the wp-config.php file.
You can read more here: https://wordpress.org/support/article/debugging-in-wordpress/
Only after you do that you will be able to see the error instead of a blank page, and then share it here to help us solve it or google for solution yourself.


text:
Q: Security Warning for SQL 2016 after Upgrade to 2017 After an inplace upgrade from MSSQL 2016 to MSSQL  2017, our security scan still reports that an unpatched 2016 version is running on the system.
Scan says there is a setup.exe in "C:Program Files\Microsoft SQL Server\130\Setup Bootstrap\SQLServer2016"
What can be done to completely remove 2016? Is this even possible after an upgrade?


text:
Q: A linear function on the space $c_{00}$ that is not continuous Consider the space of eventually zero sequences:
  $$c_{00} = \left\{ x = (x^{(1)},x^{(2)},\dots,x^{(k)},\dots)\in\ell^\infty \,\middle|\, \exists k_0 \text{ such that $x^{(k)}=0$ for $k>k_0$}\right\}$$
What would be an example of a linear function from $c_{00}$ to $\mathbb R$ that isn't continuous? I'm thinking of something of the form $\frac 1 x$, because it would not be defined if $x$ equaled zero, but I'm not sure where to go from there.

A: Hint: (if you'll allow me to put the indices back in their usual place as subscripts): is $(x_1, x_2, x_3, \ldots) \mapsto \sum_n nx_n$ continuous? (It's certainly well-defined and linear if only finitely many $x_n$ are non-zero.)

A: Hint: use the fact that continuous is equivalent to bounded in normal spaces. I think you're onto this with $1/x $, but it needs to be more clear. Pick a sequence in c00 that has bounded norm and make its image in $\mathbb{R}$ blow up.
Edit: to give a concrete answer, note that $x_n = (1,\frac 1 2, \frac 1 3, \dots, \frac 1 n, 0, 0, \dots)$ is a bounded sequence (in the sup norm), but the sequence $A x_n = \sum_{i=1}^n \frac 1 i$ is unbounded.


text:
Q: How to make a field in a model only exist on a condition met on another field? I'm trying to make it so that only if MusicPackState.type equals loan will there be
a reference to the member who is currently loaning it. Am I going about the right way for doing this?
class Member(models.Model):
    firstName = models.CharField(max_length = 20)
    lastName = models.CharField(max_length = 20)
    address = models.ForeignKey(models.ForeignKey(Address)
    memberContactInfo = models.ForeignKey(MemberContactInfo)

class MusicPack(models.Model)
    title = models.CharField(max_length = 20)
    composer = models.CharField(max_length = 20)
    arranger = models.CharField(max_length = 20)

class MusicPackState(models.Model)
    TYPES_CHOICES = (
        ('ISSUED', 'Issued'),
        ('LIBRARY', 'Library'),
        ('LOAN', 'Loan'),
        ('ENTERTAINMENTFOLDER', 'Entertainment Folder')
    )
    type = models.CharField(_('Type'), max_length = 20, choices = TYPES_CHOICES)

    def if_loan(self)
        if type == 'Loan'
                member = models.ForeignKey(Member)


text:
Q: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: I have the following route definition:
@Component
public class CamelRoutes extends RouteBuilder {
    @Override
    public void configure() throws Exception {
           from("seda:second")
                .bean("helloWorld?method=smth")
                .process(exchange -> {
                    System.out.println("Message:" + exchange.getIn().getBody());
                })
                .log("body:${body}");

and following bean:
public static class HelloWorld {
       public void execute(String str){
           System.out.println("HelloWorld#execute: " + str);
       }
        public void smth(String str){
            System.out.println("HelloWorld#smth: " + str);
        }
    }

But application doesn't start.
trace:
org.apache.camel.RuntimeCamelException: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth
    at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1831) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:136) ~[camel-spring-2.20.0.jar:2.20.0]
    at org.apache.camel.spring.SpringCamelContext.onApplicationEvent(SpringCamelContext.java:174) ~[camel-spring-2.20.0.jar:2.20.0]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at SpringBootCamelIntegrationApplication.main(SpringBootCamelIntegrationApplication.java:9) [classes/:na]
Caused by: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1298) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:204) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:1135) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:3714) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3428) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:208) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3236) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3255) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:3155) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:133) ~[camel-spring-2.20.0.jar:2.20.0]
    ... 15 common frames omitted
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: helloWorld?method=smth
    at org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:94) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.component.bean.RegistryBean.createCacheHolder(RegistryBean.java:69) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.BeanDefinition.createProcessor(BeanDefinition.java:251) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.ProcessorDefinition.makeProcessorImpl(ProcessorDefinition.java:549) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:510) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:226) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1295) ~[camel-core-2.20.0.jar:2.20.0]
    ... 27 common frames omitted

What wrong with my code base ?
update:
According Romat Vottnet advice I've wrote following:
@Component
public class CamelRoutes extends RouteBuilder {
    @Override
    public void configure() throws Exception {

        from("seda:second")
                .bean("helloWorld?method=smth()");

    }

    public static class HelloWorld {
        public void execute(String str) {
            System.out.println("HelloWorld#execute: " + str);
        }

        public void smth(String str) {
            System.out.println("HelloWorld#smth: " + str);
        }
    }

    @Bean(name = "helloWorld")
    public HelloWorld helloWorld() {
        return new HelloWorld();
    }
}

But I see:
org.apache.camel.RuntimeCamelException: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth()] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth()
    at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1831) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:136) ~[camel-spring-2.20.0.jar:2.20.0]
    at org.apache.camel.spring.SpringCamelContext.onApplicationEvent(SpringCamelContext.java:174) ~[camel-spring-2.20.0.jar:2.20.0]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at SpringBootCamelIntegrationApplication.main(SpringBootCamelIntegrationApplication.java:9) [classes/:na]
Caused by: org.apache.camel.FailedToCreateRouteException: Failed to create route route4 at: >>> Bean[ref:helloWorld?method=smth()] <<< in route: Route(route4)[[From[seda:second]] -> [Bean[ref:helloWorld?me... because of No bean could be found in the registry for: helloWorld?method=smth()
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1298) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:204) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:1135) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:3714) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3428) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:208) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3236) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3255) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:3232) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:3155) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:133) ~[camel-spring-2.20.0.jar:2.20.0]
    ... 15 common frames omitted
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: helloWorld?method=smth()
    at org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:94) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.component.bean.RegistryBean.createCacheHolder(RegistryBean.java:69) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.BeanDefinition.createProcessor(BeanDefinition.java:251) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.ProcessorDefinition.makeProcessorImpl(ProcessorDefinition.java:549) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:510) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:226) ~[camel-core-2.20.0.jar:2.20.0]
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1295) ~[camel-core-2.20.0.jar:2.20.0]
    ... 27 common frames omitted

when application starts.
I checked - method marked as @Bean is invoked.

A: this works:
 from("seda:second")
     .bean(HelloWorld.class, "smth")

A: As you're already using Spring, why not annotate your bean with @Component and use an autowired instance inside your route?

A: The way you give the class name and method to "bean" is wrong!
If you wanna use bean then these are acceptable ways for how to work with it:
from("direct:a").bean(ClassName.class , "methodName").to("direct:b");

from("direct:a").bean("registeredClassName","methodName").to("direct:b");
// this registered named is the name that you give to spring annotations like
//@Component , @Configuration , @Service , @Controller , @Bean etc...
// If you are using Camel stand alone then registeredClassName is the name that
// you gave to  camel's registry.
//For example:

SimpleRegistry simpleRegistry = new SimpleRegistry(); // this class is just a mapper
simpleRegistry.put("registeredClassName",new ClassName());

CamelContext camelContext = new DefaultCamelContext(simpleRegistry);

// In Spring Boot
@Autowired
private ClassName instanceOfClassName;
from("direct:a").bean(instanceOfClassName , "methodName").to("direct:b");

And this is the right way for using class and method together like the way you went through:
from("direct:a").to("bean:registeredClassName?method=methodName").to("direct:b");
// remember no parenthesis () for methodName

from("direct:a").to("bean:FullyQualifiedClassName?method=Name").to("direct:b");

Also this is another way of invoking bean and its' method although it is a little advance and you need to know what is Simple-Language.
from("direct:start").bean("registeredClassName","methodName(${body},${header.customerId},${header.customerType}");

That's all :))

A: I was trying to execute a method under another class using camel beans. so i had to use 'to' instead of bean. this is what worked for me.
        //add class instance and add it to the registry as a bean
    MyService myService = new MyService();

    SimpleRegistry registry = new SimpleRegistry();

    registry.bind("myServiceBean", myService);

    CamelContext context = new DefaultCamelContext(registry);

    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                    .to("bean:myServiceBean?method=messageReciever");
        }
    });
context.start();


text:
Q: How to get current userdata from firestore in flutter? Im new to flutter and firestore. I´m building a social media app and need to get some userinformation from the current logged in user to the user profilepage. Surch as username, email etc.
I have manage to get the userdata up to firestore, but Im struggling to get the current userinformation back to my project.
I've tryed this method, and it does get the userinformation back from firestore, but not the current userinformation unfortuinetly.
I guess the plroblem is that Im stuck on the first document in my database on firestore?
StreamBuilder(
  stream:
      Firestore.instance.collection('userData').snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return CircularProgressIndicator();
    }

    return Container(
      child: Padding(
        padding: const EdgeInsets.only(top: 75.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              snapshot.data.documents[0]['userName'],
              style: TextStyle(fontSize: 25.0),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 5.0),
              child:
                  Text(snapshot.data.documents[0]['email']),
            ),
          ],
        ),
      ),
    );
}),

I would really appreciate any potential solutions.
Thank you!

A:       Future<void> _getUserName() async {
        Firestore.instance
            .collection('Users')
            .document((await FirebaseAuth.instance.currentUser()).uid)
            .get()
            .then((value) {
          setState(() {
            _userName = value.data['UserName'].toString();
          });
        });
      }

Add the _userName to the initstate like this
 void initState() {
    super.initState();
    _getUserName();
  }

and call it like this
  child: Text('Hello $_userName,'),

I hope this will work

A: If you are using Firebase authentication, then
import 'package:firebase_auth/firebase_auth.dart';

FirebaseUser user = await FirebaseAuth.instance.currentUser();

will get you the current logged in user. After that, you can do
var email = user.email;
var userName = user.displayName;

to get relevant user info.


text:
Q: Trick to pass WCAG auditor re contrast issue. I am using http://achecker.ca to validate my HTML/CSS and verify that I am WCAG 2.0 compliant. I'm quite happy with it for the most part but it is giving me an inappropriate error that is frustrating my efforts to get a clean validation. I was wondering if anyone had a suggestion for getting around that?
It's complaining about the contrast of some text I am displaying, saying that the background color and the text color are too similar. That's actually true - background-color is #f2eecf and text color is #f2f2f2 - but it isn't really relevant because I have a photograph appearing above the background color so there is actually good contrast between the photograph and the text color. Also, I've added a 1 pixel black text-shadow around the text to make it even clearer. Unfortunately, the tool doesn't seem to take the shadow or photograph into account. (It makes sense that it wouldn't know how to handle the photograph since it is not a uniform colour but I'm disappointed that the text shadow doesn't help.)
Is there something I can do to my HTML or CSS to help satisfy the tool? The website doesn't seem to have any way to contact the people operating the website or I would have asked there first.
Should I just ignore the "errors"? Or should I use a different tool? I'm just getting started with WCAG compliance checking - I realize now that I'm rather late getting into this - so maybe there are better tools to use. If so, I would appreciate any recommendation, especially for free tools.
I certainly want my pages to be WCAG compliant but I can't spare money for tools right now.

A:
I have a photograph appearing above the background color

So your text has a transparent background color or it has a background-image?  A code snippet would help.
I'm guessing you're getting this error: https://achecker.ca/checker/suggestion.php?id=301
If you look up "achecker.ca" on https://www.whois.net/, you get:

Administrative contact:
Name: Iris Neher
Email: ineher@ocad.ca

If you're using a decent accessibility checker, then you should not try to fake out the checker.  I have not used achecker so I can't comment on how accurate it is.  But if you post your code example, I might be able to tell if it's really a problem.
You can also try

*

*http://www.brandwood.com/a11y/ - which specifically checks text on images.

*https://chrome.google.com/webstore/detail/color-contrast-analyzer/dagdlcijhfbmgkjokkjicnnfimlebcll?hl=en - chrome plugin

A: Short Answer:
Best practices is that if you are going to composite text over an image, the image is in a container with that container having a background similar to the image.
Longer Answer:
There are a variety of reasons that an image will not load. A site doing things such as placing live text over an image needs to ensure that text remains readable regardless of the load state of the image.
Also keep in mind that a user must be able to zoom up the text in size without breaking the site, meaning keeping the text over the image or BG so it is still readable, etc.
Outlines & Shadows
As for outlines and shadows: while they may assist contrast, they should be used to enhance and not for the sole basis of contrast. In part because the rendering of these properties is far from consistent among different browsers.
Resources
WAVE Automated Checker
APCA Contrast — the new contrast method for WCAG 3


text:
Q: Garbage collector tuning in Ruby 2.0 I was wondering if the GC tuning used for ruby 1.9.x is still relevant in 2.0 with the new implementation of the GC. If so, are there any new things that we can configure on the new version?
I am talking about the following setups
RUBY_HEAP_MIN_SLOTS=600000
RUBY_GC_MALLOC_LIMIT=59000000
RUBY_HEAP_FREE_MIN=100000

A: There's a fair bit of confusion about these GC tuning parameters. REE (which is a fork of Ruby 1.8.7) introduced its own parameters first, and later Ruby (starting in 1.9.2) introduced its own (similar) parameters. Ruby 1.9.3 made them customizable via environment variables, and Ruby 2.1.0 added a lot more.
This blog post goes into great detail about garbage collection in MRI and what all the tuning variables mean.
Here's a complete list of all the tuning variables for each Ruby version:
REE source

*

*RUBY_HEAP_MIN_SLOTS

*RUBY_HEAP_SLOTS_INCREMENT

*RUBY_HEAP_SLOTS_GROWTH_FACTOR

*RUBY_GC_MALLOC_LIMIT

*RUBY_HEAP_FREE_MIN

Ruby 1.9.2 source source
(Hard-coded, but customizable via environment variables with this patch)

*

*GC_MALLOC_LIMIT

*HEAP_MIN_SLOTS

*FREE_MIN

Ruby 1.9.3 source

*

*RUBY_GC_MALLOC_LIMIT

*RUBY_HEAP_MIN_SLOTS

*RUBY_FREE_MIN

Ruby 2.0.0 source
Same as Ruby 1.9.3
Ruby 2.1.0 source

*

*RUBY_GC_HEAP_INIT_SLOTS (obsoletes RUBY_HEAP_MIN_SLOTS)

*RUBY_GC_HEAP_FREE_SLOTS (obsoletes RUBY_FREE_MIN)

*RUBY_GC_HEAP_GROWTH_FACTOR (new)

*RUBY_GC_HEAP_GROWTH_MAX_SLOTS (new)

*RUBY_GC_MALLOC_LIMIT

*RUBY_GC_MALLOC_LIMIT_MAX (new)

*RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new)

*RUBY_GC_OLDMALLOC_LIMIT (new)

*RUBY_GC_OLDMALLOC_LIMIT_MAX (new)

*RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new)

Ruby 2.1.1 source

*

*RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new)

A: From Ruby 2.1.x http://tmm1.net/ruby21-rgengc/
export RUBY_GC_HEAP_INIT_SLOTS=600000
export RUBY_GC_HEAP_FREE_SLOTS=600000
export RUBY_GC_HEAP_GROWTH_FACTOR=1.25
export RUBY_GC_HEAP_GROWTH_MAX_SLOTS=300000

or this
# Boost Ruby
export RUBY_GC_HEAP_INIT_SLOTS=1000000 # 1M
export RUBY_GC_HEAP_FREE_SLOTS=500000  # 0.5M
export RUBY_GC_HEAP_GROWTH_FACTOR=1.1
export RUBY_GC_HEAP_GROWTH_MAX_SLOTS=10000000 # 10M
export RUBY_GC_MALLOC_LIMIT_MAX=1000000000    # 1G
export RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR=1.1
# export RUBY_GC_OLDMALLOC_LIMIT=500000000      # 500M
# export RUBY_GC_OLDMALLOC_LIMIT_MAX=1000000000 # 1G
# export RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR=1.1

Performance MRI Ruby Patch
$ rvm install 2.1.2 --patch railsexpress -n railsexpress
$ rvm --default use 2.1.2-railsexpress


text:
Q: Django login() without authenticate() I'm failing to understand what does authenticate() and login() are supposed to do. For example, in view like this:
class HomeView(FormView):
    template_name = 'home/index.html'
    form_class = AuthenticationForm
    success_url = '/'

    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, *args, **kwargs):
        return super(HomeView, self).dispatch(*args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        if 'next' in self.request.GET:
            context['next'] = self.request.GET['next']
        return context

    def form_valid(self, form):
        if form.data['next']:
            self.success_url = form.data['next']
        login(self.request, form.get_user())
        return super(HomeView, self).form_valid(form)

I've tested with active and inactive user, it behaves like I don't need authenticate() (ie. I can login if user is active, but not if inactive). Why is it so? Thanx!

A: You can understand it quickly digging django source code (also with django docs):
Authenticate check for user and password:
def authenticate(self, username=None, password=None, **kwargs):
    UserModel = get_user_model()
    if username is None:
        username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
        user = UserModel._default_manager.get_by_natural_key(username)
        if user.check_password(password):
            return user
    except UserModel.DoesNotExist:
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a non-existing user (#20760).
        UserModel().set_password(password)

Login:
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""

As you can see, it is not a good idea to login user without authenticate it.

A: authenticate()

This will check your password  against the given username/email/whatever if it is valid it will return the user object
  login()

will create a session id for the user and persist(save session in db/cache/etc backends) the user so that you don't have to authenticate() every time a request is sent by that user.


text:
Q: Is Node JS limited to one thread per open HTTP connection? Can Node JS have multiple threads serving HTTP clients on a single HTTP port? This is to handle situations where some threads are waiting for a database or doing some heavy processing. This is not supposed to interfere with other threads that are quick things like loading an image.

A: Node doesn't wait for the database, thats the point. Node is non-blocking, event-driven. It sets up a callback, and keeps going round, ready for the next request. It doesn't just sit there, waiting for the database to come back with the requested info.

A: Node.js uses an event-loop and everything that is blocking uses the threadpool => libeio
(See slide 63). But then again you should not worry about this. You should just provide callbacks to asynchronous operations. It gets called when operation has completed.
Take for example this snippet from node_redis:
var redis = require("redis"),
    client1 = redis.createClient(), client2 = redis.createClient(),
    msg_count = 0;

client1.on("subscribe", function (channel, count) {
    client2.publish("a nice channel", "I am sending a message.");
    client2.publish("a nice channel", "I am sending a second message.");
    client2.publish("a nice channel", "I am sending my last message.");
});

client1.on("message", function (channel, message) {
    console.log("client1 channel " + channel + ": " + message);
    msg_count += 1;
    if (msg_count === 3) {
        client1.unsubscribe();
        client1.end();
        client2.end();
    }
});

client1.incr("did a thing");
client1.subscribe("a nice channel");

function(channel, message) is for example one of these callbacks which get called when the event happens.
function (channel, message) {
    console.log("client1 channel " + channel + ": " + message);
    msg_count += 1;
    if (msg_count === 3) {
        client1.unsubscribe();
        client1.end();
        client2.end();
    }
}

A: If you want to have multiple workers listening on the same port (most useful if you have multiple cores), look into the new Cluster API.  Example from the docs:
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}


text:
Q: Qual a diferença entre variáveis de instância de classe, automáticas (locais) e de duração estática? Qual a diferença entre esses tipos variáveis? Como identificá-las? Como o C# trabalha com elas?

A: O que é uma variável?

variável de instância

Esta variável pertence ao objeto, concretamente ela só existe quando objeto é criado. Na classe ela serve apenas de planta de como criar o objeto. Em todos os métodos de instância você pode acessá-la porque internamente tem um parâmetro (this) em todos os métodos de instância já que eles recebem o objeto (geralmente por referência) sem você ver.
Elas só podem ser acessadas através de um objeto. Não pode ser acessada pela classe ou outra forma, tem que dizer de qual objeto você quer a variável.
class Exemplo {
    private int valor;
    public string nome;
}

variável de classe

São variáveis que existem por todo o tempo de vida da aplicação, elas são acessadas através da classe porque só existe uma dela, não é como os objetos que podem ter vários. Então podemos entender que há um objeto único na memória com as variáveis da classe. Estas variáveis são compartilhadas por toda a aplicação (a não ser que sejam privadas).
class Exemplo {
    public static int total;
}

variável automática (variável local)

São as variáveis dos métodos, geralmente presentes no stack (pode estar no registrador). Eles tem seu tempo de vida gerenciado automaticamente enquanto o método estiver executando. São chamadas de automáticas por isso.
class Exemplo {
    public static int total;
    private int valor;
    public string nome;
    public string Metodo(int parametro) => (total + valor + parametro).ToString() + nome;
}

Note que parâmetros são variáveis locais, a diferença é só a inicialização que é feita na chamada do método.

variável de duração estática

O mesmo que variável de classe.
Coloquei no GitHub para referência futura.


text:
Q: Using "this", when function and selector are not together With this
example 1
$("#my_div").on("click", function () {
    alert( $(this).attr("id") )
});

we obtain correct result, but if I use this:
example 2
function thisId () {
    alert( $(this).attr("id") )
}

$("#my_div").on("click", function () {
    thisId();
});

Now the result is undefined. Please tell me how I should be using this, when the selector and function using this are written as different expressions, as in example 2?

A: For jQuery to pass the element reference to the function you must provide the function as a reference. Try this:
$("#my_div").on("click", thisId);

Update for @bot
function thisId (event) {
    alert( $(this).attr("id") )
    alert(event.type);
}

$("#my_div").on("click", thisId);

A: @RoryMcCrossan's answer is the correct one, here's why: JS determines what this references ad hoc, that is: when the function is called, it looks at the call-context:
myObject.property = function(){console.log(this)}
myObject.property();
  /\          ||
  ||who called |
  |_____________

If the function wasn't called as a method of an obeject, like you did with thisId, JS -like it always does- falls back to the global object, and this will point to window.
You can determine the calling context programmatically, with functionName.call(context) and functionName.apply(context,[arguments]);, which is what jQuery does behind the scenes:
$.fn.on(evt,callback)//simplified
{//jQ sets up its own event handler that looks like this:
    //here, this point to $("#my_div") in your case, so:
    var jQhandler = function(e)
    {
        callback.apply(this,[e]);//passes the event as an argument
    };
    this.addEventListener(evt,jQhandler,false);//<-- passes its handler by reference
}

So you can do either this use apply, which -in your case- requires yet another anon. function object to be created, or pass the function directly to jQuery as being the callback. The latter being far more efficient: less verbose and less function objects required.
This is, in short, why @RoryMcCrossan is correct, and why some consider JS to be the worlds most misunderstood language: the bulk of ppl using it don't really know about how JS determines the context.

Just as a side-note: ECMA5 allows you to bind a function to a context, using the .bind method, but that would take us to far off-topic...


text:
Q: Will changes to Java Options in the Tomcat Monitor App persist at runtime? I'm using the Tomcat 7 Monitor Application to add the following java options:
-XX:+HeapDumpOnOutOfMemoryError

-XX:HeapDumpPath=path

Once I hit the "Apply" button will these variables be updated at runtime, or do I need to restart the service?
Thanks

A: As -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath are both command line options, they take effect on JVM start only and therefore you'll need to restart your Tomcat for this configuration change to take effect.
However it is still possible to change both flags at runtime using jinfo or jconsole as indicated here.


text:
Q: How to Make my databse centre for more desktop apps I have developed a desktop app for my office. My company head office is in Mumbai. And now my boss wants to install that application at other branches like Delhi, Chennai etc. And we want to access the same database at all the branches. And we don't want to host the database at a server.
My office has LAN. So is it possible to make my database common for all the branch through my ip address of pc?
I have told my boss that we should host the DB at a server. Then the DB will be common for all the office. But my boss is telling me to make it without hosting if that is possible. If any body have any idea then reply me please..
Thanks...

A: I would look at SymmetricDS, which is an open source (java) database syncing tool.
It operates over HTTP(S), and does multi-master replication.
So, you could have Java desktop at each site and have all the database sync.


text:
Q: Recursive Multiplication in Scheme (trouble with negatives) I am trying to multiply in Scheme using recursion, and I am able to do so with positive numbers but not negatives (they get stuck in an infinite loop). I assume the problem comes in the 3rd and 4th lines, which I wrote in an attempt to be able to handle negatives. Any help would be appreciated :)
(define Multiply(lambda (x y)
                      (if (eq? x 0) 0 (if (eq? y 0) 0 ;if either x or y are zero, return 0
                         (if (> 0 x) (- 0 (+ x (Multiply x (- y 1))))
                             (if (> 0 y) (- 0 (+ x (Multiply x (- y 1))))
                                 (+ x (Multiply x (- y 1)))))))))

A: Since multiplication is associative, you can have
x * (-1 * y)  =  (x * -1) * y

With this in mind, you can convert y to positive whenever it is less than zero, by multiplying both x and y with -1.
Consider the following:
(define (multiply x y)
  (cond
    ((zero? x) 0)
    ((zero? y) 0)
    ((< y 0)
     (multiply (- x) (- y)))
    (else
     (+ x (multiply x (sub1 y))))))


text:
Q: How do I convert Expression> to Expression>? I can find lots of information about how to change the body of an expression, but I can't find anything about how to change the ReturnType.
Here is the code that I have written incorporating the call to the Convert routine given below.
    private T[] CheckCreatedOnDate<T>(Expression<Func<T, object>> fieldExpression, T[] input, Data.Context context) where T : Entity
    {
        var fieldDelegate = fieldExpression.Compile();

        Expression<Func<T, bool>> predicateExpression = Convert(fieldExpression);
        Func<T, bool> predicateDelegate = predicateExpression.Compile();
        Predicate<T> predicate = predicateDelegate.Invoke;

        DbSet<T> dbSet = context.Set<T>();
        var data = dbSet.ToList();

        foreach (T inputRecord in input)
        {
            var fieldObject = fieldDelegate.Invoke(inputRecord);

            var dataRecord = data.SingleOrDefault(x => Equals(predicate, fieldObject));

            if (dataRecord != null)
            {
                inputRecord.CreatedOn = dataRecord.CreatedOn;
            }
        }

        return input;
    }

This method should behave in a very similar way to the AddOrUpdate method in EF, however this one simply replace the createdOn date if the record is already in the Db.
My code however still does not work. The predicate that is created does not seem to be correct as it never finds the relevant record in the Db.
All help much appreciated.
Cheers Mike

A: Assuming that fieldExpression is something like (T e) => e.Field I concluded that you want find in DB record with same value in Field column.
Try this:
foreach (T inputRecord in input)
{
    object fieldObject = fieldDelegate.Invoke(inputRecord);

    ParameterExpression p = fieldExpression.Parameters.First();
    // Equivalent to x => x.Field == fieldObject
    Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(
        // input.Field == fieldObject
        Expression.Equal(
            // input.Field
            fieldExpression.Body,
            // constant from fieldObject
            Expression.Constant(fieldObject)
        ),
        new []{ p }
    );

    T dataRecord = dbSet.SingleOrDefault(predicate);

    if (dataRecord != null)
    {
        inputRecord.CreatedOn = dataRecord.CreatedOn;
    }
}

I create totally new predicate in each loop run by taking fieldExpression body and pass it to SingleOrDefault invocation.


text:
Q: mysql query to find all possible like combinations start with and ends with (simplified duplicate) -- Sample data, borrowed from https://stackoverflow.com/q/7745609/808921

CREATE TABLE IF NOT EXISTS `docs` (
  `id` int(6) NOT NULL auto_increment,
  `groupname` varchar(100),
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `sm` (
  `id` int(6) NOT NULL auto_increment,
  `code` varchar(100),
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`groupname`) VALUES
  ('100:2000'),
  ('100:2001'),
  ('101:2000'),
  ('101:2001'),
  ('102:2002'),
  ('103:2003');
INSERT INTO `sm` (`code`) VALUES
  ('100'),
  ('101'),
  ('2000');

SQL Fiddle of same: http://sqlfiddle.com/#!9/54714e/39
In MySQL, I would like to filter only the group names that contains various combinations of values in the sm table. i.e. 100,101,2000.
The below query returns other combinations too like
100:2000
100:2001
101:2000
101:2001

SQL:-
select distinct d.groupname from docs d, sm s  where d.groupname like concat(s.code,'%') or d.groupname like concat('%',s.code);

Original question:-
mysql query to find all possible like combinations start with and ends with
Update:-
Expected results:-
100:2000
101:2000

A: I've just broke your or condition into make multiple join with the same table like below to achieve your expected result,
select distinct d.groupname from docs d
join sm s1 on
d.groupname like concat(s1.code,'%')
join sm s2 on
d.groupname like concat('%',s2.code);


text: Q: PageSpeed Insights Mobile vs Desktop I've come to the conclusion that PSI's mobile score is not affected by the time it takes to load every resource (onLoad event). On the other hand, PSI's desktop score is. Why is that?


text:
Q: Preventing entering new records before all the fields filled, in MsExcel I have a Worksheet in Excel:

My goal - user shouldn't be able to proceed before all the fields are filled from my drop down lists.
Otherwise - some sort of alert should appear or just doesn't let them proceed to the next record, before all the fields are entered with data.
One other important detail - my Form contains dropdown lists in all fields
That's why just a simple data validation rule won't work.
(There already other rules and formulas)
Is it still possible to do what described in vba, perhaps?
I have excel 2017
thank you!
update from Hell--1931
I probably do something wrong
I placed your code as following:
     Private Sub Worksheet_Deactivate()
     Dim sh As Worksheet, lastRow As Long, lastCol As Long,
                                  emptyCells As Range

      Set sh = Worksheets("ClientSatisfactionForm") ' very important to fully
                                             qualify it (not ActiveSheet)!
      lastRow = sh.Range("A" & Rows.Count).End(xlUp).Row
      lastCol = sh.Cells(1, Columns.Count).End(xlToLeft).Column
     On Error Resume Next
     Set emptyCells = sh.Range(sh.Cells(1, 1), sh.Cells(lastRow,
                        lastCol)).SpecialCells(xlCellTypeBlanks)
     If Err.Number = 1004 Then
     Err.Clear: On Error GoTo 0: Exit Sub
     End If
   On Error GoTo 0
   If emptyCells.Cells.Count > 0 Then
      MsgBox "There are empty cells, which must be filled: " &
                                        emptyCells.Address(0, 0)
     sh.Activate: emptyCells.Select
     Exit Sub
   End If
  End Sub

Now, it's not displays any error messages (as it did in previous version - when I executed in on close event), even if I enter empty row it now just asks about saving sheet....
PS - whenever I change event to "Before Close"  this code works as well as the previous one. But still lets exit out of Worksheet saving empty cells ..

A: Try the next code, please:
After editing: Now sh cannot be ActiveSheet, anymore! It must be clearly qualified. Meaning to use the involved worksheet name.
Sub checkEmptyCells()
  Dim sh As Worksheet, lastRow As Long, lastCol As Long, emptyCells As Range

  Set sh = Worksheets("Involved sheet name") ' very important to fully qualify it (not ActiveSheet)!
  lastRow = sh.Range("A" & Rows.count).End(xlUp).Row
  lastCol = sh.cells(1, Columns.count).End(xlToLeft).Column
  On Error Resume Next
   Set emptyCells = sh.Range(sh.cells(1, 1), sh.cells(lastRow, lastCol)).SpecialCells(xlCellTypeBlanks)
   If Err.Number = 1004 Then
        Err.Clear: On Error GoTo 0: Exit Sub
   End If
   On Error GoTo 0
  If emptyCells.cells.count > 0 Then
    MsgBox "There are empty cells, which must be filled: " & emptyCells.Address(0, 0)
    sh.Activate: emptyCells.Select
    Exit Sub
  End If
End Sub

The above code assumes that there are not cells having formulas which returns "". In such a case xlCellTypeBlanks does not consider them like being empty...
Edited:
In order to not allow leaving from the sheet in discussion, until all cells are filled, the above Sub (however it will be named) should be simple called in the Worksheet_Deactivate event, as following:
Private Sub Worksheet_Deactivate()
   checkEmptyCells
End Sub


text:
Q: R foreach %dopar% Results I am trying to run a function using foreach and %dopar% that will pass its results back into itself for each iteration.  Small example below:
require(doParallel)

test_function <- function(data)
{
  result <- rbind(data, data)
  return(result)
}

test_data <- mtcars

cl                          <-          makeCluster(4)
registerDoParallel(cl)
results                     <-          foreach(i = 1:10) %dopar%
{
  aa <- test_function(test_data)
  aa$iteration <- i
  test_data <- aa
  return(aa)
}
stopCluster(cl)

What I am hoping to see in results is a list of ten data frames, each one sequentially doubling in number of rows.
It appears that re-defining test_data within the foreach function does not do this, as it would if I just ran these commands within a standard for loop - like so:
results <- list()
for(i in 1:10)
{
  aa <- test_function(test_data)
  aa$iteration <- i
  test_data <- aa
  results[[i]] <- aa
}

Would appreciate any insight into what I'm overlooking here.

A: If I understand your question correctly, your issues are caused because you are unable to update the global variable test_data from within the parallelised for-loop.
To understand why you are being prevented from doing so, consider what is actually happening within the parallelised for-loop: multiple workers running on different threads are performing operations in parallel, each with their own separate, locally-scoped variables. If they had access to any global variable (or shared memory) without any kind of protection that controls access to it, then it would be possible to corrupt whatever is stored in the variable - and there are several different ways this corruption might happen.
Preventing this is the raison d'être of concurrency control structures like semaphores. These allow users to do what you are trying to, but require some care to use correctly.
However, they are not a available in R. Hence, it makes sense that R should protect that global variable test_data from being modified in a non-thread safe manner. It's actually trying to protect your data.
The solution is to rewrite your code to remove any attempt to update global variables (if you still want to do any kind of parallel processing) or switch to using a traditional, sequential for loop (as some commenters have already suggested).


text:
Q: Is there a way to see the RenderTreeBuilder version of the razor file in blazor? Take the index page for example:

Hello, world!

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

It is my understanding that this will be translated into some code using the RenderTreeBuilder which may look something like this:
builder.OpenElement(0, "h1")
builder.AddContent(1, "Hello, world!")
.
.
.

Is there a place where I can inspect the RenderTreeBuilder version of the razor pages?
I would like to start trying out RenderTreeBuilder and would like to know how it is done, for references purposes.
Apologies in advanced if this is a duplicate. I will delete this question if so.
Thanks!

A: You are right. The BlazorMarkup is translated into C# files that are using the RenderTreeBuilder. It is comparable to what WPF does when it comes to XAML and C# files.
After you have built your project, go to the obj/debug/net5.0/Razor/.
Keep in mind to use a debug build. Otherwise, you won't see the files.

You will see the same directory structure as in your project. Directories are listed as long as they contain razor files. Open the file, e.g., Index.razor.g.cs (.g stands for generated), and you can see the calls to RenderTreeBuilder
 [Microsoft.AspNetCore.Components.RouteAttribute("/")]
    public partial class Index : Microsoft.AspNetCore.Components.ComponentBase
    {
        #pragma warning disable 1998
        protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
        {
            __builder.AddMarkupContent(0, "
Hello, world!
\r\n\r\nWelcome to your new app.\r\n\r\n");
            __builder.OpenComponent<BlazorApp1.Shared.SurveyPrompt>(1);
            __builder.AddAttribute(2, "Title", "How is Blazor working for you?");
            __builder.CloseComponent();
        }
        #pragma warning restore 1998
    }


text:
Q: Find Accuracy of an agglomeration method? I have plotted a dendrogram using maximum agglomeration method.
hc <- hclust(distance_matrix, method = "complete")
plot(hc, hang = 0, labels=ilpd_df$Class)

Q1) How can I find the accuracy of this agglomeration method?
Q2) How should one comment on the sensitivity of test data to the agglomeration method?
Thank you =)

A: Cluster analysis is explorative, not predictive.
Accuracy makes sense when predicting, but not so much when exploring data. You won't be able to just apply this clustering method to a new data point!
The closest to accuracy is probably the Rand index if you actually have labeled data. It's the accuracy of predicting for a pair of points if they have the same label, or not.


text:
Q: AttributeError: _member_count Exception has occured: AttributeError
_member_count

in on_guild_remove
@client.event
async def on_guild_remove(guild):
    channel = client.get_channel(ID)
    embed = discord.Embed(title=guild.name, description=f'Member Count: {guild.member_count}', colour = discord.Color.red())
    embed.set_author(name='Removed', icon_url=guild.icon_url_as())
    embed.set_thumbnail(url=guild.icon_url)
    embed.add_field(name='Owner', value=guild.owner_id, inline=False)
    embed.add_field(name='Owner', value=guild.region, inline=False)
    await channel.send(embed=embed)

There seems to be no problem when i have this exact code in on_guild_join.

A: Change guild.member_count to len(guild.members)
AttributeError _member_count means that the object guild does not have an attribute called member_count


text:
Q: Extend template conditionally in Twig Take the following tree structure:
├───base
│   ├───0001
│   │   └───pages
│   │           file.twig
│   │           file_content.twig
│   └───ext
│       └───store
│       │   └───pages
│       │       └───all
│       │       │       file.twig
│       │       └───0001
│       │               file.twig
│       └───newsletter
│           └───pages
│               └───all
│               │       file.twig
│               └───0001
│                       file.twig
└───pages
    │   file.twig
    └───0001
            file.twig

As you can see, there's a load of file.twig scattered around.
I want to render the contents of the file base/0001/pages/file_content.twig.
But, I want that the following files can change the content inside blocks:

*

*ext/<...>/pages/0001/file.twig

*ext/<...>/pages/all/file.twig

*/pages/0001/file.twig

*/pages/file.twig
But, these files may or may not exist, may or may not be needed and must be able to change the content of any block.
Is there any way to make this work?
So far, I have the following:
{% embed 'base/pages/file_content.twig' %}
    {% block page_file %}
        {{ parent() }}
        {% if data.store_enabled %}
            {% include [
                    'base/ext/store/pages/0001/file.twig',
                    'base/ext/store/pages/all/file.twig'
                ] ignore missing
            %}
        {% endif %}
        {% include ['pages/0001/file.twig', 'pages/file.twig'] ignore missing %}
    {% endblock %}
{% endembed %}

This "works", in the sense that it renders the page but doesn't allow any block to be overrided.
How could I make this work?

As an example, consider this structure of files (yes, files are missing, and that's expected):
    ├───base
    │   ├───0001
    │   │   └───pages
    │   │           file.twig
    │   │           file_content.twig
    │   └───ext
    │       └───store
    │       │   └───pages
    │       │       └───0001
    │       │               file.twig
    └───pages
            file.twig

The file base/0001/pages/file_content.twig has the following:
{% block page_file %}
    {% block title %}
Nice title
{% endblock %}
    {% block price %}{% endblock %}

{% endblock %}

The file base/ext/store/pages/0001/file.twig has the following content:
{% block price %}55 €{% endblock %}

And the file pages/file.twig has:
{% block title %}{{ parent() }}
{% endblock %}
{% block price %}
{{ parent() }}
{% endblock %}

The output I expect is the following:

Nice title

55 €</span

But with that code, all the other files' changes are being ignored and the output is being only the following:

Nice title

Note:
It's important to notice that I'm using Twig 1.33.2, and using the Twig_Autoloader::register(); method.
I can't use Twig 2.x, since it requires PHP 7.0+ and I'm restricted to PHP 5.3.29.

A: After a few more attempts, I've finally figured a way to do this.
This is as ugly as it may seem...
Assuming the structure:
├───base
│   ├───0001
│   │   └───pages
│   │           file.twig
│   │           file_content.twig
│   └───ext
│       └───store
│       │   └───pages
│       │       └───0001
│       │               file.twig
└───pages
        file.twig

The main file (base/pages/file.twig) has the following code:
{% if data.store_enabled %}
    {% include [
            'base/ext/store/pages/0001/file.twig',
            'base/ext/store/pages/all/file.twig',

            'base/pages/file_content.twig'
        ] ignore missing
    %}
{% else %}
    {% include [
            'pages/0001/file.twig',
            'pages/file.twig',

            'base/pages/file_content.twig'
        ] ignore missing
    %}
{% endif %}

This will include the files inside base/ext/store/pages/ if they exist. If a file is missing there, then the file base/pages/file_content.twig is included.
All the files inside base/ext/store/pages/ must have the following code on the top:
{% extends [
        'pages/0001/file.twig',
        'pages/file.twig',

        'base/pages/file_content.twig'
    ]
%}

And the files inside pages/ must have the following:
{% extends 'base/pages/file_content.twig' %}

This allows you to have override any block inside base/pages/file_content.twig and the files are only included/extended if they exist.
Having there a garanteed file (in this case, base/pages/file_content.twig must always exist) will still display the "default" content and won't throw a nasty exception.

Outside of the scope of this answer, I've initially found a very similar aproach, which used conditional values.
Try it on: https://twigfiddle.com/u06tur


text:
Q: Test failure of a playbook with Ansible Molecule I'm creating a sudo role and want to test with Molecule that the role fails if a rule is not correct.
How can we define that we expect the playbook to fail with Molecule?
For example, if I have the following configuration:
sudo__entries:
  - name: super_alice
    content: "alice ALL NOPASSWD"

The role will fail because visudo won't validate the file.
And that's the behavior I want to test.

A: You can modify converge.yml to test a failure scenario with a rescue block, using a similar method to this unit testing paradigm:
try {
    foo();
    Assert.fail();
} catch(FooException e) {
    // Caught expected exception from foo()
}

An example failure scenario for role sudo would have a converge.yml that looks something like:
---
- name: Does not converge
  hosts: all
  tasks:
    - block:
        - name: "Include sudo"
          include_role:
            name: "sudo"
          register: expected_failure
        - name: "Check execution halted"
          fail:
            msg: "Execution should stop before this task"
          register: should_not_run
      rescue:
        - assert:
            that:
              - expected_failure is defined
              - should_not_run is not defined

You can also supplement this with a verify.yml to assert the failure scenario did not leave the host in a broken state.