text:
Q: QListView: how to automatically scroll the view and keep current selection on correct items in view when removing items from the top I have a list view with a custom model. The model allows me to add text to the bottom of the list (using 'addText(const QString&)') and to remove items from the top of the list (using 'removeItemsFromTop(int _iCount)').
What is the best way to add text to the view and keep the model size under some maximum (lets say 'MAX_LIST_SIZE'), while always maintaining the view (i.e. current selection and items in view should not change when items are removed).
The solution should preferably be a function that I can use wherever I'm using my custom model.
I have looked at indexAt(...), scrollTo(...), currentIndex(...) and setCurrentIndex(...) methods on QListView, but I can't figure out how to put all of this together.
So far I have (for auto scrolling the view)
// add items here ...

// cleanup
QModelIndex indexViewTop = listView->indexAt(QPoint(8, 8));
if (listModel->rowCount() > MAX_SIZE)
{
    int iRemoveCount = (listModel->rowCount() - MAX_SIZE) + MAX_SIZE/10;
    listModel->clearTextFromFront(iRemoveCount);
    listView->scrollTo(indexViewTop.sibling(indexViewTop.row() - iRemoveCount, 0), QAbstractItemView::PositionAtTop);
}

This is supposed to scroll the list view as items are removed to keep the view consistent, but indexAt(...) always returns an invalid index.
For keeping the selection consistent I tried:
// add items her ...

// cleanup
if (listModel->rowCount() > MAX_SIZE)
{
  int iCurrentViewIndex = listView->currentIndex().row();
  int iRemoveCount = (listModel->rowCount() - MAX_SIZE) + MAX_SIZE/10;
  listModel->clearTextFromFront(iRemoveCount);
  listView->setCurrentIndex(listModel->index(iCurrentViewIndex - iRemoveCount, 0));
}

This seems to work, but I'm still stuck on the auto scrolling.

A: I did a queue-like table model implementation. I think it is similar for QAbstractItemModel. Best way would be to use QQueue to store data.
Now, this is a snipped for QAbstractTableModel (which is subclass of QAbstractItemModel so it should work; mEvents is QQueue):
// custom table for inserting events
void EventPreviewTableModel::insertEvent(const DeviceEvent &event) {
    beginInsertRows(QModelIndex(), 0, 0);
    mEvents.enqueue(event);
    endInsertRows();

    if (mEvents.size() > SIZE) {
      beginRemoveRows(QModelIndex(), mEvents.size(), mEvents.size());
      mEvents.dequeue();
      endRemoveRows();
    }
}

And also override data() and rowCount() to serve correct data.
For second part using ItemIsSelected flag for items you want to have selected is done through: Qt::ItemFlags QAbstractItemModel::flags(const QModelIndex & index)

A: This is my current approach and it seems to work well:
void addTitlesToList(Model *model, QListView *view, std::vector<Object*> &items)
{
    QScrollBar *pVerticalScrollBar = view->verticalScrollBar();
    bool bScrolledToBottom = pVerticalScrollBar->value() == pVerticalScrollBar->maximum();
    QModelIndex indexViewTop = view->indexAt(QPoint(8, 8));

    // add to model
    model->pushItems(items);

    // cleanup if model gets too big
    if (model->rowCount() > model->maxListSize())
    {
        int iCurrentViewIndex = view->currentIndex().row();
        int iRemoveCount = (int)(model->rowCount() - model->maxListSize()) + (int)model->maxListSize()/10;
        model->removeItemsFromFront(iRemoveCount);

        // scrolls to maintain view on items
        if (bScrolledToBottom == false)
        {
            _pView->scrollTo(indexViewTop.sibling(indexViewTop.row() - iRemoveCount, 0), QAbstractItemView::PositionAtTop);
        }

        // maintain selection
        if (iCurrentViewIndex >= iRemoveCount)
        {
            view->setCurrentIndex(_pModel->index(iCurrentViewIndex - iRemoveCount, 0));
        }
        else
        {
            view->setCurrentIndex(QModelIndex());
        }
    }

    // move scroll bar to keep new items in view (if scrolled to the bottom)
    if (bScrolledToBottom == true)
    {
        view->scrollToBottom();
    }
}

One issue I had with indexAt(QPoint(...)) is that I was calling it after adding the items to the list, which seems to cause it to always return an invalid index. Calling indexAt before anything is added to the model seems to work.
I also added automatic 'scroll to bottom' if already there (i.e. the view either stays fixed on specific items or sticks to the latest items if scrolled all the way to the bottom).


text:
Q: Log4j StringMatchFilter and denyAll filter properties configuration Can anyone please let me know filter properties for a package where
I want to separate the logs in two different logs files. Below is the configuration which I am trying use but its not working. I want deny logs
based string like 'UserMgmt-' and allow rest logs in log1 appender and allow only log2 appender allow 'UserMgmt-' and deny rest allow logs.
log4j.logger.com.abc=DEBUG, log1
log4j.logger.com.abc=DEBUG, log2

log4j.appender.log1=org.apache.log4j.RollingFileAppender
log4j.appender.log1.Append=true
log4j.appender.log1.File=C:/Oracle/Middleware/user_projects/domains/logs/G_loAFg/UM.log
log4j.appender.log1.layout=org.apache.log4j.PatternLayout
log4j.appender.log1.layout.ConversionPattern=%d %-6p [%c] %m%n
log4j.appender.log1.filter.1=org.apache.log4j.varia.StringMatchFilter
log4j.appender.log1.filter.1.StringToMatch=UserMgmt-
log4j.appender.log1.filter.1.AcceptOnMatch=false

log4j.appender.log2=org.apache.log4j.RollingFileAppender
log4j.appender.log2.Append=true
log4j.appender.log2.File=C:/Oracle/Middleware/user_projects/domains/logs/PM.log
log4j.appender.log2.layout=org.apache.log4j.PatternLayout
log4j.appender.log2.layout.ConversionPattern=%d %-6p [%c] %m%n
log4j.appender.log2.filter.1=org.apache.log4j.varia.StringMatchFilter
log4j.appender.log2.filter.1.StringToMatch=UserMgmt-
log4j.appender.log2.filter.1.AcceptOnMatch=true

A: Added deny all filter in 1st log1 after that it worked
log4j.appender.log1.filter=org.apache.log4j.varia.DenyAllFilter

log4j.logger.com.abc=DEBUG, log1
log4j.logger.com.abc=DEBUG, log2

log4j.appender.log1=org.apache.log4j.RollingFileAppender
log4j.appender.log1.Append=true
log4j.appender.log1.File=C:/Oracle/Middleware/user_projects/domains/logs/G_loAFg/UM.log
log4j.appender.log1.layout=org.apache.log4j.PatternLayout
log4j.appender.log1.layout.ConversionPattern=%d %-6p [%c] %m%n
log4j.appender.log1.filter.1=org.apache.log4j.varia.StringMatchFilter
log4j.appender.log1.filter.1.StringToMatch=UserMgmt-
log4j.appender.log1.filter.1.AcceptOnMatch=false
log4j.appender.log1.filter=org.apache.log4j.varia.DenyAllFilter
log4j.appender.log2=org.apache.log4j.RollingFileAppender
log4j.appender.log2.Append=true
log4j.appender.log2.File=C:/Oracle/Middleware/user_projects/domains/logs/PM.log
log4j.appender.log2.layout=org.apache.log4j.PatternLayout
log4j.appender.log2.layout.ConversionPattern=%d %-6p [%c] %m%n
log4j.appender.log2.filter.1=org.apache.log4j.varia.StringMatchFilter
log4j.appender.log2.filter.1.StringToMatch=UserMgmt-
log4j.appender.log2.filter.1.AcceptOnMatch=true

A: using org.apache.log4j_1.2.17.jar  I set the filter to deny what I didn't want and then allowed everything else.
log4j.appender.NormalAppender.filter.1=org.apache.log4j.varia.StringMatchFilter
log4j.appender.NormalAppender.filter.1.StringToMatch=User.Dashboard
log4j.appender.NormalAppender.filter.1.AcceptOnMatch=false
log4j.appender.NormalAppender.filter.1=org.apache.log4j.varia.AllowAllFilter

redpajama_set_name: RedPajamaStackExchange


text:
Q: correct method for an id within a class? I have a navigation system. CSS based. On a few of the li items I need to be able to customize the way it looks (background colour, font colour etc).
At the moment the top level menu is here: http://www.gardensandhomesdirect.co.uk/menutest
SALE, the bottom menu, is one I am trying to set as having a red background and have tried doing it this way:
.side_nav .li-sale { background-color:#900 !important; color:#FFF !important; }

However it is getting overuled.
What is the best way to set this up? So I can have custom li classes used.

A: That's because your red background color is for LI which is under green A, so you cannot see that LI.
Just try setting style for child A element:
.side_nav ul li.li-sale a {
    background-color:#900;
    color:#FFF;
}

A: If you li's are something like this:
<li class="side_nav" id="li-scale">
you can call this one in your css with:
.side_nav #li-scale
So basically, in your css, you call classes with a . and you call id's with a #


text:
Q: How do I remove the multiple "Attribute not allowed here error" when I start a new document? I'm new to Android development and I'm trying to make a simple Happy Birthday Card. Whenever I start the application and create a new project I receive a number of errors in the Activity_Main.xml file that prevents me from seeing the preview.
I've tried reinstalling Java, Reinstalling Android Studio, Checking the proxy's, Changing the layout from Constraint to Relative and Opening and closing the XML files.
<RelativeLayout xmlns:android="schemas.android.com/apk/res/android"
   xmlns:tools="schemas.android.com/tools"
   android:layout_height="match_parent"
   android:layout_width="match_parent"
   tools:context=".MainActivity">
     <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Happy Birthday YOURFRIENDHERE" />
</RelativeLayout>

It was Code given to simply display text on the screen of a phone however I keep receiving errors on all of the attributes, Android:layout, Tools:context, and TextView saying they're not allowed. Even when I create a new project and haven't edited anything I still get the errors on the code that's automatically populated.

A: Try this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Happy Birthday YOURFRIENDHERE" />
</RelativeLayout>

A: It was a VPN issue, certain files were not being received from google and as a result the necessary files weren't being accessed. All is working as expected now!

A: I think it was because the version of your android studio is not up-to-date , as I think google want us to use an up-to-date version when you found you are blocking from download the gradle resource from the internet through your android studio .


text:
Q: dputting an S4 object How would a person dput() an S4 object? I tried this
require(sp)
require(splancs)
plot(0, 0, xlim = c(-100, 100), ylim = c(-100, 100))
poly.d <- getpoly() #draw a pretty polygon - PRETTY!
poly.d <- rbind(poly.d, poly.d[1,]) # close the polygon because of Polygons() and its kin
poly.d <- SpatialPolygons(list(Polygons(list(Polygon(poly.d)), ID = 1)))
poly.d
dput(poly.d)

Notice that if I dput() an S4 object, I cannot reconstruct it again. Your thoughts?

A: As it currently stands, you cannot dput this object. The code of dput contains the following loop:
if (isS4(x)) {
    cat("new(\"", class(x), "\"\n", file = file, sep = "")
    for (n in slotNames(x)) {
        cat("    ,", n, "= ", file = file)
        dput(slot(x, n), file = file, control = control)
    }
    cat(")\n", file = file)
    invisible()
}

This handles S4 objects recursively, but it relies on the assumption an S3 object will not contain an S4 object, which in your example does not hold:
> isS4(slot(poly.d,'polygons'))
[1] FALSE
> isS4(slot(poly.d,'polygons')[[1]])
[1] TRUE

Edit: Here is a work-around the limitations of dput. It works for the example you provided, but I don't think that it will work in general (e.g. it does not handle attributes).
dput2 <- function (x,
                   file = "",
                   control = c("keepNA", "keepInteger", "showAttributes")){
    if (is.character(file))
        if (nzchar(file)) {
            file <- file(file, "wt")
            on.exit(close(file))
        }
        else file <- stdout()
    opts <- .deparseOpts(control)
    if (isS4(x)) {
        cat("new(\"", class(x), "\"\n", file = file, sep = "")
        for (n in slotNames(x)) {
            cat("    ,", n, "= ", file = file)
            dput2(slot(x, n), file = file, control = control)
        }
        cat(")\n", file = file)
        invisible()
    } else if(length(grep('@',capture.output(str(x)))) > 0){
      if(is.list(x)){
        cat("list(\n", file = file, sep = "")
        for (i in 1:length(x)) {
          if(!is.null(names(x))){
            n <- names(x)[i]
            if(n != ''){
              cat("    ,", n, "= ", file = file)
            }
          }
          dput2(x[[i]], file = file, control = control)
        }
        cat(")\n", file = file)
        invisible()
      } else {
        stop('S4 objects are only handled if they are contained within an S4 object or a list object')
      }
    }
    else .Internal(dput(x, file, opts))
}

And here it is in action:
> dput2(poly.d,file=(tempFile <- tempfile()))
> poly.d2 <- dget(tempFile)
> all.equal(poly.d,poly.d2)
[1] TRUE


text:
Q: Python Error with iteration, for loop I am having a problem with my iteration statement. I want to compare the letter x with the value inside to equal 12.
I wRIte in python
   list     =    9876554321
for        x = list:
 if result -> 12
output "Succes'

A: Please look at the formatting tips, it will help you display your code as you wish.
that said, I think this is what you want.
The following code will iterate through each character in your list string.
If it finds a match, it will print success
list = "9876554321"
for char in list:
    if char == "9":
        print("Success')


text:
Q: removeChild does not work in a setTimeout if there is one element Here is the code in question:
        var p = document.createElement("p");
        holder.appendChild(p);
        setTimeout(function(){
            if (holder.firstChild != null){
                holder.removeChild(holder.firstChild);
            }
        },500);

So the expected functionality is that the p goes into the holder, and in 500ms it gets removed.  Yet the p element stays forever, even though I can confirm that the element is not null.  What's going on?

A: Since firstChild Node bight well be a #text Node
Either use .firstElementChild or rather simply:
p.remove()

*

*firstChild

*firstElementChild

*.append()

*.remove()
Example:

// DOM utility functions:

const find = (sel, parent) => (parent ||document).querySelector(sel);
const create = (tag, props) => Object.assign(document.createElement(tag), props);

// Task:

const elHolder = find("#holder");
const elP = create("p", {textContent: "I will get removed soon!"});

elHolder.append(elP);
setTimeout(() => {
  elP.remove();
}, 1000);


text:
Q: What Is the probability of getting all $17$ numbers out of a set of $11$ and $12$? I have an urn with balls labeled $1$ through $17$ inside of it. I first pick $11$ balls without replacing them in between and record which numbers I picked. I then put them all back in and pick $12$ balls using the same method. My question is, what is the probability that I will pick one ball with each number on it?
I have attempted to make an excel spreadsheet to estimate what the answer would be, but I am interested in getting the precise answer. Another way of thinking about it which could help is by asking, what is the probability that there will be exactly $6$ duplicate picks?


text:
Q: Split on colons in SQL Server I have a column in SQL table which would have data like this:
"College: Queenstown College" or "University: University of Queensland"
Text before the ":" could be different. So, how can i select only the text before the ":" from the column and text after the ":(space)"?

A: You should probably consider putting your table into first normal form rather than storing 2 pieces of data in the same column...
;with yourtable as
(
select 'College: Queenstown College' as col UNION ALL
select 'University: University of Queensland'
)
select
     left(col,charindex(': ',col)-1) AS InstitutionType,
     substring(col, charindex(': ',col)+2, len(col)) AS InstitutionName
from yourtable

A: Using the charindex and substring functions:
substring(theField, 1, charindex(':', theField) - 1)


text:
Q: Ubuntu 19.10 Snap performance issues Now that it looks like more default apps are using the snap versions, a number of issues cause a decline in the experience:

*

*Startup of the apps is slower.

*Snap apps don't interact with other apps: e.g. Thunderbird attachments don't open in default apps. You have to save them first.

*Non-English language input doesn't work in snaps.

Where is the correct place to report/follow these bugs? And what is the development plan for snaps?
Thanks

A: Ubuntu 19.10 is an early release unstable build; it is almost impossible to not run into issues with it. It is highly recommended you opt for 19.04 instead, as it is more stable, and has the more available software and the same kernel version (5). Snapcraft has it's own Q&A forum available at https://forum.snapcraft.io/. Consider asking your question here instead of AskUbuntu, as you will likely get more appropriate help to resolve your issue faster.


text:
Q: What to do when Euler Lagrange Equation is highly nonlinear ode In $\mathbb{R}^3$, suppose there is a curve on X-Y plane $y(x)$ defined on $x\in [-a,a]$ satisfying:

*

*$y(x)\geqslant 0$;

*$y(-a)=y(a)=0.$
Rotate $y(x)$ along x-axis in $\mathbb{R}^3$ and get a solid revolution.
Minimize surface area $A=\int_{-a}^{a}2\pi y\sqrt{1+(y')^2}\mathrm{d}x$, given fixed volume $V=\int_{-a}^{a}\pi y^2\mathrm{d}x=C$, for some constant $C$.
By standard variational method and Lagrange multiplier, ($\lambda$ is Lagrange constant), we get the Euler Lagrange equation, which is nonlinear.
$$\frac{1}{(1+(y')^2)^{1/2}}+\lambda y = \frac{yy''}{(1+(y')^2)^{3/2}}$$
My question is how to do with this nonlinear equations. Is there any way to get the minimal $A$ without solving $y$ explicitly?


text:
Q: How is $\alpha =2 \beta$? This is a solved example in 'Differential Equations with Applications and Historical Notes' by George F.Simmons.

Find the shape of a curved mirror such that light from a
source at the origin will be reflected in a beam of rays parallel to the
$x$-axis.
Solution :
By symmetry, the mirror will have the shape of the surface of revolution
generated by revolving a curve $APB$ ( figure ) about the $x$-axis.
It follows from the law of reflection that $α = 2β$. By the geometry of the
situation, $ϕ = β $ and $θ = α + ϕ = 2β$.  .....

This is a part of the solution and I understood the following statements. But I do not understand how it is concluded that by laws of reflection $\alpha = 2\beta$. Shouldn't it be $\alpha =\beta$ since angle of reflection must be equal to angle of incidence?


text:
Q: Trying to share image with intent Android I'm trying to share an image with an intent to social media. It's asking for the path to the image, and I've retrieved the image URL from my object, in the form of files.parsetfss.com/77c6003f-0d1b-4b55-b09c-16337b3a2eb8/tfss-7267d2df-9807-4dc0-ad6f-0fd47d83d20f-3eb7b9e4-d770-420c-a0a0-9ca4fc4a6a0a_1.png, for example. The share intent displays but when I open any other app to share, I get a crash with no logcat error. What could be going wrong?
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, marketFeedItem.getDesign().getImage());
startActivity(Intent.createChooser(share, "Share your design!"));

Updated Answer. This is what I did to get it to work:
  ImageView imageView = (ImageView) feedItemView.findViewById(R.id.image);
                Drawable mDrawable = imageView.getDrawable();
                Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();

                String path = MediaStore.Images.Media.insertImage(getContentResolver(),
                        mBitmap, "Design", null);

                Uri uri = Uri.parse(path);

                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("image/*");
                share.putExtra(Intent.EXTRA_STREAM, uri);
                share.putExtra(Intent.EXTRA_TEXT, "I found something cool!");
                startActivity(Intent.createChooser(share, "Share Your Design!"));

A: If getImage() is returning the long string that you have in your question, that is not a valid URL, as it lacks a scheme.
According to the docs, you need to pass a content: Uri in the EXTRA_STREAM extra. In practice, a file: Uri frequently also works. I would expect you to run into problems with other schemes, like https: or http:.

A: maybe this helps share image with URL android share intent

A: URL of your parse server for the image file is not a valid for share intent, so save loaded bitmap temporary in your device then share image using that saved bitmap URL. After image shared you can delete saved image from your device


text:
Q: Typo3 / TS3Editor missing Code Completion I'm using Typo3 9.2.0 and it looks like the Code Completion doesn't work for me.
I'm new at typo3 and if I understood right it should be implemented.
I searched on Google and watched the Typo Extension Repository but I didn't found an Extension with the searchword "completion" that does what I'm looking for.
What Extension or what way do I have to go to get it into the backend?

A: If you are missing the editor with syntax highlighting and codecompletion in the Backend, you may need to install the system extension cms-t3editor. If you are in composer mode, use this command:
composer require typo3/cms-t3editor

If you have installed TYPO3 in classic way, just activate that extension,


text:
Q: How to introduce flat cost of flow over a node using mixed integer programming. In the set up for the program we have a graph where we are trying to minimize the cost of sending flow over the arcs. I have formulated the following linear program.
\begin{array}{ll}
\text{minimize}   & \sum_{ij} C_{ij} X_{ij} \\
\text{subject to} & \sum_j X_{ij} =\ell_i, ~ i=1,2,\dots,m \\
                  & X_{ij} \geq 0, ~ i=1,2,\dots,m,~j=1,2,\dots,n
\end{array}
Which is basically using the conservation of flow as the constraint.
What I need to be able to do is add a flat "fee" for sending any amount of flow over an arc. I am developing a mixed integer program to model this. I introduced binary variables $y_{ij}$ which give the descision to go over the arc from $i$ to $j$, but after that I am stuck as to how to formulate the problem, does anyone have any ideas on how to modify the boundary conditions so that $y_{ij} = 1$ iff $X_{ij}>0$?

A: If you're OK with using a Big M type method (although I'm told Big M is considered a bad word in mixed integer programming :)), here's a linear constraint to capture $y_{ij} = 1$ if $X_{ij} > 0$. Use $X_{ij} \leq M_{ij} y_{ij}$. Note that if $X_{ij} > 0$ then $y_{ij}$ is forced to 1. But if $X_{ij} = 0$ then $y_{ij}$ can take values 0 or 1. However, since you will add a cost $\bar{C}_{ij} y_{ij}$ to the objective function, $y_{ij}$ will naturally take the value of 0 in the case where $X_{ij} = 0$ to ensure optimality.
The parameter $M_{ij}$ should be chosen as low as possible. One candidate for the parameter is the sum of the absolute values of the demands. But you might be able to come up with better values depending on your problem data. I think if all your data is integral, then choosing the right value for $M$ is probably not critical.

A: First I would add the constraint, that the quantity, which is transported is equal to the demand:
\begin{array}{ll}
\sum_i X_{ij} =d_j, ~ j=1,2,\dots,n
\end{array}
For the condition, that $y_{i,j} =1$ if $X_{ij} >0$, there would be the following constrain helpful:
\begin{array}{ll}
y_{ij} \cdot X_{ij} = X_{ij} ~ i=1,2,\dots,m,~j=1,2,\dots,n
\end{array}
Now you can use the variable $y_{ij}$ for the objective function. And you can add sum of all fees.


text:
Q: A program in C to get previous two fibonacci numbers less than the given number #include <stdio.h>

int fibo(int);

int main() {
    int n, p[100];

    scanf("%d", &n);

    int i = 0;
    do {
        p[i] = fibo(i);
        i++;
    } while (p[i] <= n);

    printf("%d %d", p[i-1], p[i]);

    return 0;
}

int fibo(int i) {
    if (i == 0) {
        return 0;
    } else
    if (i == 1) {
        return 1;
    } else {
        return (fibo(i - 1) + fibo(i - 2));
    }
}

This is the program I have written. I got an utterly rubbish answer. Can someone help me with where I am going wrong?

A: You compare the array element after the one you just computed.  The array is uninitialized, the behavior is undefined.
You can fix your code this way:
int main() {
    int n, p[100];

    scanf("%d", &n);

    int i = 0;
    do {
        p[i] = fibo(i);
        i++;
    } while (p[i-1] <= n);

    printf("%d %d", p[i-2], p[i-1]);

    return 0;
}

However your code has several small issues:

*

*You do not check if scanf() succeeded.

*You do not check for potential buffer overflow when storing values to the p array.

*You have undefined behavior for small values of n as you will be reading entries of p at negative offsets.

Here is a corrected version that addresses these issues:
#include <stdio.h>

int fibo(int);

int main(void) {
    int n, p[100];

    if (scanf("%d", &n) == 1) {
        for (int i = 0; i < 100; i++) {
            p[i] = fibo(i);
            if (p[i] > n)
                break;
        }
        if (i >= 2) {
            printf("%d %d\n", p[i - 2], p[i - 1]);
        }
    }
    return 0;
}

int fibo(int i) {
    if (i == 0) {
        return 0;
    } else
    if (i == 1) {
        return 1;
    } else {
        return (fibo(i - 1) + fibo(i - 2));
    }
}

Note however that the Fibonacci sequence diverges quickly, and arithmetic overflow can occur, causing undefined behavior, producing an incorrect result for large values of n.
Here is simpler solution that does not use recursion and does not have this problem:
#include <stdio.h>

int main(void) {
    int n, a = 0, b = 1;

    if (scanf("%d", &n) == 1 && n > 1) {
        while (a < n - b) {
            int c = a + b;  /* no overflow possible */
            a = b;
            b = c;
        }
        printf("%d %d\n", a, b);
    }
    return 0;
}

A: Initialize i=-1, and inside the do while loop increment i first
int i=-1;

do
{
    i++;
    p[i] = fibo(i);

  } while(p[i] <=n);

  printf("%d %d", p[i-1], p[i-2]);// print i-1 and i-2

The problem was when you check p[i]<=n with the original question's code posted, you are checking for garbage value since at that time i was already incremented.


text:
Q: Concurrent update on the same record I'm facing a strange issue with some TSQL code on SQL2005.
The piece we suspect is generating the issue is:
INSERT INTO SGVdProcessInfo
    ([StartTs])
    VALUES
    (GETDATE())

SELECT @IdProcessInfo = SCOPE_IDENTITY()

UPDATE TOP(@quantity)
    [SGVdTLogDetail] WITH (ROWLOCK)
SET
    [IdSGVdProcessInfo] = @IdProcessInfo
WHERE
    [IdSGVdProcessInfo] IS NULL
    and IdTLogDetailStatus != 9

@quantity usually takes 500.
There is a non-clustered index over IdSGVdProcessInfo and IdTLogDetailStatus on SGVdTLogDetail
What's happening is that some records of SGVdTLogDetail are first updated with one id of the processinfo table and later they are updated again by another process with a new processinfo ID.
I'm wondering if the rowlock hint is raising this issue or maybe there's something else...
My guess is while the update is being applied over the first 500 selected rows, another process is selecting the next group, and taking some records of the first group which are not yet updated (because of the rowlock). Is this possible?
Any help will be much appreciated!

A: Yes, that sounds right. You can fix it (at the cost of lost concurrency) by putting the entire operation inside of a serializeable transaction. That will guarantee that all the rows are locked for the life of the transaction, instead of only during the atomic row-level reads and updates.

A: I believe this is happening because SQL Server is escalating the row-level locks to page locks. You'd think that an UPDATE in which you specify the primary key would always cause a row lock, but when SQL Server gets a batch with a bunch of these, and some of them happen to be in the same page (depending on this situation, this can be quite likely, e.g. updating all files in a folder, files which were created at pretty much the same time), you'll see page locks, and bad things will happen. And if you don't specify a primary key for an UPDATE or DELETE, there's no reason the database wouldn't assume that a lot won't be affected, so it probably goes right to page locks, and bad things happen.
By specifically requesting row-level locks, these problems are avoided as you are doing, however, in your case lots of rows are affected, and the database is taking the initiative and escalating to page locks.


text:
Q: Why does jQuery .text() not return the value inside the div? I am missing something trivial here, but I don't get it. Why doesn't it alert Test Value?

$('.comment-upvote-wrapper').on('click', function() {
    // Get the comments pk
    var comment_pk = $(this).closest('#comment-pk').text()
    alert(comment_pk)
})
.comment-upvote-wrapper {
  width: max-content;
  background-color: yellow;
  }

Test Value

Return "Text Value"

A: The problem is because #comment-pk is not an ancestor element of .comment-upvote-wrapper, it's a sibling of .comment-box. Therefore you need to use closest() to get the .common-box, then prev():

$('.comment-upvote-wrapper').on('click', function() {
  var comment_pk = $(this).closest('.comment-box').prev('#comment-pk').text();
  console.log(comment_pk)
})
.comment-upvote-wrapper {
  width: max-content;
  background-color: yellow;
}

Test Value

Return "Text Value"

However the fact that the element has an id attribute means there should only ever be one of them in the DOM. As such using DOM traversal to find it is redundant; you can just select it directly by its id:
$('.comment-upvote-wrapper').on('click', function() {
  var comment_pk = $('#comment-pk').text();
  console.log(comment_pk)
})


text:
Q: How to start drill in distributed mode in window operating system  I am using apache drill in window 10 having latest version (1.9).

I want to start my drill in distributed mode.
I have configure zookeeper zoo.cfg file:-
tickTime=2000
initLimit=10
syncLimit=5
dataDir=F:/zookeepertest/data
clientPort=2181
server.1=192.589.XX.01:2888:3888
server.1=192.565.XX.02:2888:3888

And Drill folder inside drill-override.conf
drill.exec: {
  cluster-id: "test",
  zk.connect: "192.589.XX.01:2181,192.565.XX.02:2181"
}
And my zookeeper is running..
Now When i trying to start my drill using this command:-
sqlline.bat -u "jdbc:drill:zk=192.589.XX.01:2181"
Its thoughing following error:-
Error: Failure in connecting to Drill: org.apache.drill.exec.rpc.RpcException: Failure setting up ZK for client. (state=,code=0)
java.sql.SQLException: Failure in connecting to Drill: org.apache.drill.exec.rpc.RpcException: Failure setting up ZK for client.
        at org.apache.drill.jdbc.impl.DrillConnectionImpl.<init>(DrillConnectionImpl.java:161)
        at org.apache.drill.jdbc.impl.DrillJdbc41Factory.newDrillConnection(DrillJdbc41Factory.java:70)
        at org.apache.drill.jdbc.impl.DrillFactory.newConnection(DrillFactory.java:69)
        at org.apache.calcite.avatica.UnregisteredDriver.connect(UnregisteredDriver.java:143)
        at org.apache.drill.jdbc.Driver.connect(Driver.java:72)
        at sqlline.DatabaseConnection.connect(DatabaseConnection.java:167)
        at sqlline.DatabaseConnection.getConnection(DatabaseConnection.java:213)
        at sqlline.Commands.connect(Commands.java:1083)
        at sqlline.Commands.connect(Commands.java:1015)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at sqlline.ReflectiveCommandHandler.execute(ReflectiveCommandHandler.java:36)
        at sqlline.SqlLine.dispatch(SqlLine.java:742)
        at sqlline.SqlLine.initArgs(SqlLine.java:528)
        at sqlline.SqlLine.begin(SqlLine.java:596)
        at sqlline.SqlLine.start(SqlLine.java:375)
        at sqlline.SqlLine.main(SqlLine.java:268)
Caused by: org.apache.drill.exec.rpc.RpcException: Failure setting up ZK for client.
        at org.apache.drill.exec.client.DrillClient.connect(DrillClient.java:245)
        at org.apache.drill.jdbc.impl.DrillConnectionImpl.<init>(DrillConnectionImpl.java:154)
        ... 18 more
Caused by: java.io.IOException: Failure to connect to the zookeeper cluster service within the allotted time of 10000 milliseconds.
        at org.apache.drill.exec.coord.zk.ZKClusterCoordinator.start(ZKClusterCoordinator.java:123)
        at org.apache.drill.exec.client.DrillClient.connect(DrillClient.java:243)
        ... 19 more

Can anyone tell how to start drill in distributed mode in window.??

A: From Drill documentation
To start drill in distributed mode, use drillbit.sh not sqlline i.e.
drillbit.sh start

Since drillbit.sh is a shell script (not a windows batch job) you'll need a 3rd party shell scripting tool such as Cygwin or since you're using Windows 10, you can also enable Bash on Ubuntu.


text:
Q: delete sample products in Magento 2 but maintaining sample categories and luma layout I want to delete the sample products, orders, customers and invoices but maintain the categories and also the layout. I'm using Magento 2.
Any way to do that easily or should I just delete them one by one?
Thanks

A: For delete sample product
Login to Admin, then go to
Product -> Catalog
select check box of the product, then click the action drop down then click delete.
if you want to delete all, select all and then delete
For delete Customers
Customers->All Customers
select all customer then delete
For delete order&invoice
The Default Magento only allows changing order status into cancel for any completed order or test order without deleting.
use magento 2 exetnsion, if you want delete order
for example
https://www.magecheckout.com/magento-2-delete-order-extension.html
have a good luck


text:
Q: What is needed to be done to migrate chaincode from v0.6 to v1.0? I wrote some Hyperledger Fabric chaincode for v0.6 in Golang, and I want to use v0.6 chaincode in v1.0.
How should I migrate the chaincode from v0.6 to v1.0?
What is the difference between v0.6 and v1.0 from chaincode perspective?

A: This article might help you. It's a document about the migration of the Auction chaincode from v0.6  to v1.0


text:
Q: Does ef core plus support batch update with minus? I want to update stock quantity, such as +1, because so many requests do the same thing, and I don't want to lock the row for performance, then SQL which I wanted is :
Update Stock
Set qty = qty + 1
where id = xxxx

Does Entity Framework Core Plus support it, or how to implement it?

A: I think its obvious
db.Stock
  .Where(x => x.Id == id)
  .Update(x => new Stock { qty = x.qty + 1 });


text:
Q: How to use Django URLs in React JSX I have an existing Django project. I want to use ReactJS within this as React makes handling states really really easy. The issue I am facing is how to re-use the URL templates that are already defined in Django?
Example: Home/urls.py
urlpatterns=[
    url(r'plot/api/(?P<plot_id>[0-9]+)?$', views.LivePlot.as_view(), name='livePlot'),
]

If i use just Django i can refer to the above url by {% url 'Home:livePlot' plot_id %} where plot_id is a parameter passed by the server.
i am unable to leverage the same technique when using React. Any suggestions? I have access to the plot_id within my React code.
React example:
render: function() {
   return(

);
}

Ideally in the above example i would like to have a method to place  {% url 'Home:livePlot' plot_id %} or something similar within the href attribute of anchor tag, so that the link points to example.com/plot/{plot_id}.
Right now the workaround i was using involved building the url myself. So if i place this react component in example.com/sub/sub2 i would build the url as '../../plot' + plot_id. This approach fails miserably when i place the same react component in multiple pages like example.com/sub and example.com/sub/sub2 which is exactly the use-case i have.


text:
Q: Json alternative to Docusign connect XML We are trying to determine if there is a way to obtain the timestamp of when a Carbon Copy, "Envelope Signed" or "Envelope Completed" email is sent with a json api instead of xml.
We have tested using Docusign connect by selecting the "Envelope Signed" and "Envelope Completed" events under "Send information on these envelope events" in the Docusign console.
Also, when the document is signed, we receive the expected post request to our connect endpoint which includes the following (private info removed) and are wondering if the timestamp in the "Sent" tag means that the carbon copy email was actually sent at that time and therefore we can use it for auditing purposes.
<RecipientStatus>
  <Type>CarbonCopy</Type>
  <Email>bob@example.com</Email>
  <UserName>Bob</UserName>
  <RoutingOrder>2</RoutingOrder>
  <Sent>2015-07-08T16:14:18.88</Sent>
  <DeclineReason xsi:nil="true" />
  <Status>Completed</Status>
  <RecipientIPAddress />
  <CustomFields />
  <AccountStatus>Active</AccountStatus>
  <RecipientId>dc9521c4-b11d-426c-b409-326b985e823b</RecipientId>
</RecipientStatus>

thanks
PR


text:
Q: Can't upload a PNG file with OKHttp - File Not Found I am having trouble uploading an image to a Restful service, using the Multipart upload.
I am using a Recipe from the OKHttp Examples.
For some reason, the upload doesn't find the image.
I validate the file is valid (I can output info about the file, and see that it is found), but when the upload is supposed to happen, I get an error that tells me the file is not found.
Can anybody see what am I doing wrong?
Here is my code:
    @Override
        protected Boolean doInBackground(Void... params) {
            Bitmap bmp = attachment.getBitmap(getActivity(), ATTACHMENT_IMG_SIZE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 70, bos);
            File file = new File(attachment.getFilename(getActivity()));
            try {
                Log.d("MSW", "The file Canonical Path: " + file.getCanonicalPath());
                Log.d("MSW", "The file name: " + file.getName());
                Log.d("MSW", "The file Path: " + file.getPath());
            } catch (IOException e) {
                e.printStackTrace();
            }

            OkHttpClient client = new OkHttpClient();

            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            client.networkInterceptors().add(loggingInterceptor);

            RequestBody requestBody = new MultipartBuilder()
                    .type(MultipartBuilder.FORM)
                    .addFormDataPart("method_name", "upload_attach")
                    .addFormDataPart("forum_id", getArguments().getString(ARG_FORUM_ID))
                    .addFormDataPart("attachment[]", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
                    .build();

            Request request = new Request.Builder()
                    .url(AppConfig.MOBIQUO_ATTACH_URL)
                    .post(requestBody)
                    .build();

            String respStr = "";
            Log.d("MSW", "BEFORE ---: ");
            try {
                Log.d("MSW", "BEFORE RESP: ");
                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    Log.d("MSW", "Response UNSuccessful: ");
                    throw new IOException("Unexpected code " + response);
                } else {
                    Log.d("MSW", "Response Successful: " + response.body().string());
                    respStr = response.body().string();
                    System.out.println(response.body().string());
                }

            } catch (IOException e) {
                Log.d("MSW", "Exception: " + e);
                e.printStackTrace();
            }

            Log.d("MSW", "Response is: " + respStr);
            return parseResponse(respStr);
        }

Here is the error message:
        11-23 16:03:17.525  27377-27956/com.androidcentral.app D/MSW﹕ The file Canonical Path: /4970.jpg
    11-23 16:03:17.525  27377-27956/com.androidcentral.app D/MSW﹕ The file name: 4970.jpg
    11-23 16:03:17.525  27377-27956/com.androidcentral.app D/MSW﹕ The file Path: 4970.jpg
    11-23 16:03:17.618  27377-27956/com.androidcentral.app D/MSW﹕ BEFORE ---:
    11-23 16:03:17.618  27377-27956/com.androidcentral.app D/MSW﹕ BEFORE RESP:
    11-23 16:03:17.763  27377-27956/com.androidcentral.app D/OkHttp﹕ --> POST /mobiquo/upload.php HTTP/1.1
    11-23 16:03:17.763  27377-27956/com.androidcentral.app D/OkHttp﹕ Content-Type: multipart/form-data; boundary=46df9530-8ac4-4943-a980-fc61b4879002
    11-23 16:03:17.763  27377-27956/com.androidcentral.app D/OkHttp﹕ Content-Length: 449
    11-23 16:03:17.763  27377-27956/com.androidcentral.app D/OkHttp﹕ Host: forums.androidcentral.com
    11-23 16:03:17.763  27377-27956/com.androidcentral.app D/OkHttp﹕ Connection: Keep-Alive
    11-23 16:03:17.764  27377-27956/com.androidcentral.app D/OkHttp﹕ Accept-Encoding: gzip
    11-23 16:03:17.764  27377-27956/com.androidcentral.app D/OkHttp﹕ Cookie: acsessionhash=6cddfd7c1fe76a344309c9dfac7dfac0; PassportLocalSession=6e64cce2-7e01-4a2d-803e-dc9d1636704c-54c6048c-5152-4419-884f-d1301e7baf5f; acpassword=ae7da81dda3b79580a2351049281767f; PassportSessionDate=1448323386; acuserid=2669245; SESSf659a72bed167194167ec3641e600b60=9ct3V89eQufYoRYvRpIVEWg5R69E4GqVzQD7x3B2n0o; PassportSession=6e64cce2-7e01-4a2d-803e-dc9d1636704c-54c6048c-5152-4419-884f-d1301e7baf5f
    11-23 16:03:17.764  27377-27956/com.androidcentral.app D/OkHttp﹕ User-Agent: okhttp/2.6.0
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ --> POST /mobiquo/upload.php HTTP/1.1
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ Content-Type: multipart/form-data; boundary=46df9530-8ac4-4943-a980-fc61b4879002
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ Content-Length: 449
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ Host: forums.androidcentral.com
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ Connection: Keep-Alive
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ Accept-Encoding: gzip
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ Cookie: acsessionhash=6cddfd7c1fe76a344309c9dfac7dfac0; PassportLocalSession=6e64cce2-7e01-4a2d-803e-dc9d1636704c-54c6048c-5152-4419-884f-d1301e7baf5f; acpassword=ae7da81dda3b79580a2351049281767f; PassportSessionDate=1448323386; acuserid=2669245; SESSf659a72bed167194167ec3641e600b60=9ct3V89eQufYoRYvRpIVEWg5R69E4GqVzQD7x3B2n0o; PassportSession=6e64cce2-7e01-4a2d-803e-dc9d1636704c-54c6048c-5152-4419-884f-d1301e7baf5f
    11-23 16:03:17.819  27377-27956/com.androidcentral.app D/OkHttp﹕ User-Agent: okhttp/2.6.0
    11-23 16:03:17.820  27377-27956/com.androidcentral.app D/MSW﹕ Exception: java.io.FileNotFoundException: 4970.jpg: open failed: ENOENT (No such file or directory)
    11-23 16:03:17.820  27377-27956/com.androidcentral.app W/System.err﹕ java.io.FileNotFoundException: 4970.jpg: open failed: ENOENT (No such file or directory)
    11-23 16:03:17.826  27377-27956/com.androidcentral.app W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:456)
    11-23 16:03:17.827  27377-27956/com.androidcentral.app W/System.err﹕ at java.io.FileInputStream.<init>(FileInputStream.java:76)
    11-23 16:03:17.827  27377-27956/com.androidcentral.app W/System.err﹕ at okio.Okio.source(Okio.java:163)
    11-23 16:03:17.827  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.RequestBody$3.writeTo(RequestBody.java:117)
    11-23 16:03:17.827  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.MultipartBuilder$MultipartRequestBody.writeOrCountBytes(MultipartBuilder.java:277)
    11-23 16:03:17.827  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.MultipartBuilder$MultipartRequestBody.writeTo(MultipartBuilder.java:297)
    11-23 16:03:17.827  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:163)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:867)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:748)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.Call.getResponse(Call.java:277)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:234)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:196)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.squareup.okhttp.Call.execute(Call.java:79)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.androidcentral.app.fragments.AttachmentListFragment$UploadAttachmentTask.doInBackground(AttachmentListFragment.java:269)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at com.androidcentral.app.fragments.AttachmentListFragment$UploadAttachmentTask.doInBackground(AttachmentListFragment.java:220)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:292)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ at java.lang.Thread.run(Thread.java:818)
    11-23 16:03:17.828  27377-27956/com.androidcentral.app W/System.err﹕ Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
    11-23 16:03:17.829  27377-27956/com.androidcentral.app W/System.err﹕ at libcore.io.Posix.open(Native Method)
    11-23 16:03:17.829  27377-27956/com.androidcentral.app W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
    11-23 16:03:17.829  27377-27956/com.androidcentral.app W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:442)
    11-23 16:03:17.829  27377-27956/com.androidcentral.app W/System.err﹕ ... 20 more
    11-23 16:03:17.829  27377-27956/com.androidcentral.app D/MSW﹕ Response is:
    11-23 16:03:17.832  27377-27956/com.androidcentral.app E/AttachmentListFragment﹕ org.xmlpull.v1.XmlPullParserException: unexpected type (position:END_DOCUMENT null@1:1 in java.io.StringReader@24f2e54a)
                at org.kxml2.io.KXmlParser.nextTag(KXmlParser.java:2054)
                at com.androidcentral.app.fragments.AttachmentListFragment$UploadAttachmentTask.parseResponse(AttachmentListFragment.java:296)
                at com.androidcentral.app.fragments.AttachmentListFragment$UploadAttachmentTask.doInBackground(AttachmentListFragment.java:285)
                at com.androidcentral.app.fragments.AttachmentListFragment$UploadAttachmentTask.doInBackground(AttachmentListFragment.java:220)
                at android.os.AsyncTask$2.call(AsyncTask.java:292)
                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                at java.lang.Thread.run(Thread.java:818)

A: The file doesn't exist. You can confirm this by reading its first byte with a FileInputStream.

A:
The file Canonical Path: /4970.jpg

This is an impossible file path for any normal Android device, as the root directory is not only never writable but apps, but generally speaking is a read-only filesystem.
This indicates that your function is being called with an invalid argument, an issue which you need to fix in the caller.


text:
Q: Undefined method 'set_cookie' for capybara How can I create a cookie? I am running against a public site
When I try set_cookie I get:
undefined method 'set_cookie' for #<Selenium::WebDriver::Driver:0x531e792e4b07692c browser=:chrome>

require 'rspec'
require 'capybara'
require 'capybara/rspec'
require 'capybara/dsl'
require 'pry'

Capybara.run_server = false
Capybara.app_host = 'http://www.google.com/'

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new(app, :browser => :chrome)
end

root='/'

describe 'Form flow works', :type => :feature do

  before :each do
    Capybara.current_driver = :chrome
  end

  it 'Collect the customer data', :happy do
    visit( root )
    page.driver.browser.set_cookie('test_disabled', 'true', :domain => 'www.google.com')

None of the current answers on SO address my issue or have worked.
Actual url is not google.
I tried show_me_cookies but that didn't work - details:
Added the gem:
$ gem install show_me_the_cookies
Successfully installed show_me_the_cookies-4.0.0
Parsing documentation for show_me_the_cookies-4.0.0
Done installing documentation for show_me_the_cookies after 0 seconds
1 gem installed
I added the following code to the spec (just using 1 file with all code right now)
RSpec.configure do |c|
  c.treat_symbols_as_metadata_keys_with_true_values = true
  c.include ShowMeTheCookies, :type => :feature
end

and then i added show_me_the_cookies in my spec but all I got was ...spec/foo_spec.rb:17:inblock in ': uninitialized constant ShowMeTheCookies (NameError)`

A: Capybara doesn't provide a cookie API because it's main aim is testing apps, and setting cookies when directly when testing is generally not a good idea.  That being said, it sounds like you're scraping the web rather than testing so you have 2 options.

*

*Access the driver specific cookie methods.  Since you're using the Selenium driver that would be something like
page.driver.browser.manage.add_cookie(name: cookie_name, value: cookie_value)

*Use a gem that provides a common cookie API across different drivers. That would be the show_me_the_cookies gem recommended in the comments.  That would then be
create_cookie(cookie_name, cookie_value)

You may be getting uninitialized constant because you need to require 'show_me_the_cookies' in your spec_helper/rails_heper

A: This solved it:
After visit to create the session I used:
browser = Capybara.current_session.driver.browser
browser.manage.add_cookie :name => 'ab', :value => 'true', :expires => Time.now + 3600


text:
Q: What does getExternalFilesDir() do if there's no SD card installed? I am making an project that use AudioRecord API to record voice and do some processing with produced PCM-16bit data.
Currently I am using the following code:
private void startRecording() {

final int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
final byte raw_data[] = new byte[bufferSize];

final File file = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC), "test.pcm");

if (!file.mkdirs()) {
    Log.e(TAG, "Directory not created");
}
if (file.exists()) {
    file.delete();
}

recorder.startRecording();
isRecording = true;

recordingThread = new Thread(new Runnable() {
    public void run() {

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            int read = recorder.read(raw_data, 0, bufferSize);
            if (AudioRecord.ERROR_INVALID_OPERATION != read) {

                try {
                    os.write(raw_data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        try {
            Log.i(TAG, "run: close file output stream !");
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}, "AudioRecorder Thread");

recordingThread.start();
}

From my understanding, final File file = new FilegetExternalFilesDir(Environment.DIRECTORY_MUSIC), "test.pcm");, this line of code will create a file called "test.pcm", and it is located at whatever the path refereed by getExternalFilesDir(Environment.DIRECTORY_MUSIC).
I assume it is a Music Folder but what I don't understand is that my Android device currently has no SD or any external storage installed so how come this code still work? I am still able to playback the voice using AudioTrack API.
Since I need to do some processing of the stored PCM file, I wonder where does this file actually stored on my device and how can I access it.
Thanks in Advance !

A: According to the documentation of getExternalFilesDir(type):

Returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns.

Assuming you are running your app on a phone or a tablet, even if your device does not have an SD card mounted, it does have onboard storage. From your app's perspective, the onboard storage is the primary storage device in this case.
Furthermore, I suggest reading the whole documentation of getExternalFilesDir to get a deeper insight.


text:
Q: Integrating factor mistakes when solving 1 order ODE I have an ODE:
$$\frac{dy}{dx} + 3x^{2}y = x^{2}$$ .
I got the following integrating factor:
$$e^{x^3}$$
Then I multiplied both sides, but didn't come up with the right answer. It should be:
$$y = c~e^{-x^3} + \frac{1}{3}. $$
When I come up with the following:
$$y = \left(\frac{1}{3}e^{x^3} + c\right) e^{x^3}$$
What am I doing wrong?

A: You found the right integrating factor, allowing us to write the ODE as $$(e^{x^3} y)'=e^{x^3}x^2,$$ by multiplying both sides by $e^{x^3}.$ Integrating both sides gives $$ e^{x^3} y=\frac{e^{x^3}}{3}+c.$$ Now, just multiply both sides by $e^{-x^3},$ which gives $$y(x)=\frac{1}{3}+ce^{-x^3},$$ since $e^{-x^3}e^{x^3}=1.$ It looks like you should've multiplied both sides by $e^{-x^3}$ but did $e^{x^3}$, by mistake.

A: Your LHS should read $$\frac{d}{dx}(e^{x^3}y),$$ so after integrating both sides, you have to divide by $e^{x^3}$ (i.e. multiply by $e^{-x^3}$) to obtain $y(x)$.

A: You have probably forgotten to put minus sign when dividing by $e^{x^3}$.
$$e^{x^3}dy + 3x^2e^{x^3}dx = e^{x^3}x^2dx\\
d(e^{x^3}y)=\frac13d(e^{x^3})\\
e^{x^3}y=\frac13e^{x^3}+C\\
y=Ce^{-x^3}+\frac13$$

A: You have:
$$
y'(x)+3x^2 y-x^2=0\tag{1}
$$
The associated homogeneous equation
$$
y'=-3x^2 y
$$
gives you:
$$
\frac{y'}{y}=-3x^2=\frac{\mathrm{d}}{\mathrm{d}x}\log(y)
$$
so
$$
\log (y)=-x^3,
$$
and
$$
y(x)=e^{-x^3}.
$$
The general integral for the homogeneous equation is
$$
\left\{c\,e^{-x^3},\ c\in\mathbb{R}\right\}.
$$
Now I look for a particular solution $\bar{y}$ of the original equation. If I look for a constant, like
$$
\bar{y}(x)=a,
$$
it must be $\bar{y}'(x)=0$, hence, from $(1)$:
$$
0+3ax^2-x^2=0.
$$
It follows $a=\frac{1}{3}$ and the solution:
$$
y(x)=ce^{-x^3}+\frac{1}{3},
$$
for all $c\in\mathbb{R}$.


text:
Q: Return a value, even when a sub-query in a where returns empty set I have a query that is a little like this:
SELECT ISNULL(MyColumn, "Not Applicable") As MyColumn
FROM MyTable
WHERE SomeOtherColumn =
(SELECT AValue
FROM SomeOtherTable
WHERE SomeConditionHolds
)

If the relevant value for MyColumn has a value, I get this, and if it is null, this gives me "Not Applicable" as desired.
However, occasionally the sub-query returns empty set, in which case the whole query returns empty set also.  I would still like it to return "Not applicable."
The best I have been able to do is add to the above
UNION
SELECT 'Not Applicable' AS MyColumn
WHERE NOT EXISTS
    (SELECT AValue
FROM SomeOtherTable
WHERE SomeConditionHolds
)

But this feels really hacky and inefficient.  I hope someone has a better idea.

A: SELECT ISNULL(MyColumn, DummyCol) As MyColumn
FROM MyTable
  RIGHT OUTER JOIN (SELECT 'Not Available' AS DummyCol) Q ON DummyCol IS NOT NULL
   AND SomeOtherColumn =
     (SELECT AValue
     FROM SomeOtherTable
     WHERE SomeConditionHolds
     )

A: Try this :
    SELECT Case When T.AValue Is Null Then 'Not Applicable' Else MyColumn End As MyColumn
    FROM MyTable Left Outer Join
   (SELECT AValue
    FROM SomeOtherTable
    WHERE SomeConditionHolds
   ) T on MyTable.SomeOtherColumn  = T.AValue

A: get Query result and when no Row exist set result with "Not Applicable"  otherwise you must double check and waste system time.

A: Since your subquery returns one value, you can easily convert this to an outer join, which will always give you a row and which will also make the query more efficient and elegant:
SELECT
    ISNULL(MyColumn, "Not Applicable") As MyColumn
FROM MyTable
LEFT JOIN SomeOtherTable
    ON SomeOtherColumn = AValue
    AND SomeConditionHolds

The key thing here is that SomeConditionHolds is in the join condition, not the where clause, otherwise the left join effectively becomes an inner join.

A: declare @Foo as Table ( FooId Int Identity, Something VarChar(16) );
insert into @Foo ( Something ) values
  ( 'One' ), ( 'II' ), ( '3' );

declare @FooLimit as Int = 1; -- Try 5.

with Alicia as (
  select FooId, Something, 1 as SetId
    from @Foo
    where FooId >= @FooLimit
  union all
  select 42, 'n/a', 2 )
  select FooId, Something
    from Alicia
    where SetId = ( select Min( SetId ) from Alicia )


text:
Q: Converting an input file of words to a vector - C++ I am creating a program that reads an input file of text only and creates a vector of the words in that input file.  The program I have now only prompts the user for the input file name and then stops running after that.  My text file has only 3 words in it for a test, but by the end of the program I hope to be able to read large text files such as stories.
My code:
#include<string>
#include<iostream>
#include<vector>
#include<fstream>

using namespace std;

int main(){

 string filename;  //name of text file
 string wordsFromFile;  //the words gathered from the text file

 cout << "Please enter the name of your text file" << endl;
 cin >> filename;

 ifstream fin(filename.c_str());

 fin >> wordsFromFile;

 while(fin >> wordsFromFile)
 {
   fin >> wordsFromFile;
   vector<string>word;
   for(int i=0; i<=word.size(); i++) {
      word.push_back(wordsFromFile);
      cout << word[i];}
   }

   fin.close();
   return 0;
}

A: Concerning your actual question

The program I have now only prompts the user for the input file name and then stops running after that.

Since you are not doing any checks if the file exist or not it doesn't help you to know what happen. Is it possible that the file is not located in the correct folder? You don't seem to use any path before the file name, maybe because you are giving the full path on the prompt?

i do have an introductory book. the scope of what i am trying to do in this program is not covered in the book, though

It is usually rare to find a book about what you are doing. However, if you want to learn more about C++ I would recommend C++ Primer Plus, which is a very good book.

Concerning you loop, I would recommend to fill your list on a line per line basis especially if you are planning to load Stories (e.g. couple of megs for a single story).


text:
Q: Extending a class with a trait Since I've just jumped from another language to PHP, I would like to ask you what would be a correct way of adding an extension to a class. My config right now is as follows:
class A extends B {
    use C;

    public function a(){

    }
}

I need to add some additional functions to class A, but logically divide them from it, so I though I would be using a trait C.
So my question is - can I use function a() in my trait C? I know I can define abstract function a() in trait C, however I believe that wouldn't be a good practice at all. Maybe I can somehow inject this into a trait or is it a bad practice as well?

A: It is possible, the choice is a discretion of the developer, the best solution is based on experience.
trait C {
    public function hello() {
        parent::a();
        echo 'World!';
    }
}

class B {
    function a() {
        echo "hello";
    }
}

class A extends B{
    use C;
}

(new A())->hello(); // helloWorld!

A: Let's say:
Class B {
    public function a () {
    //Does something
    }
}

Class A extends B {
//We got access to B's public function. If you want to execute B's a and add some more content, then
    public function a() {
        parent::a();
        //Some more content
    }
}

Traits were developed due to PHP's nature of not allowing to inherit from multiple classes (Single inheritance). By creating a trait and apply it to a class, you know inherit it's methods

http://php.net/manual/en/language.oop5.traits.php

It really comes down to your needs.
Q: Do you want to create an interface and make other classes implement certain methods?
A: Create an interface
Q: Do you want to create an abstract class with some implementations and allow other classes to use them? A: Create an abstract class
Q: Do you want a class to inherit from two other classes and they've got different functionalities? A: Create a trait
The best approach is to use the tools at your disposal in order to output your desired result and keeping it organized


text:
Q: Is there a way to render .jsx components inside express server I'm very confused about mixing express routes with React and .jsx files.
I'm trying to build a multipage website with a mongoose database and I've been using ejs to do it. now I'm trying to convert to React but I have absolutely no idea of how to do this despite my research for 3 days.
What I'm looking to do is roughly something like this (example is a react component "example.jsx")
app.get("/",function(req,res){ res.send(<example />)})
instead of
app.get("/",function(req,res){ res.send("another.ejs") })
If I cant do such a thing would you recommend React routs or just sticking with ejs.

A: You need to (1.) convert the JSX code to Javascript, and then (2.) render the Javascript into an HTML string, which you then can send to the client.
E.g. if you have the file example.js:
console.log('jsxData:', <example />);
// app.get("/",function(req,res){ res.send(<example />)})

1. Transpile JSX to Javascript
If a Javascript file contains JSX code, it becomes a JSX file, and Javascript can't understand it anymore. The extension .js or .jsx doesn't matter here. You may or may not rename it to example.jsx, if you like.
But you can convert (aka. "transpile") that JSX file into a Javascript file with babel. You will get a new, separate file which is a valid Javascript file.
1.a. If it's not already installed, you need to install babel and the JSX transpiler (For the installation I'm using yarn here, npm is also possible):
yarn add @babel/cli @babel/core @babel/preset-react --dev

1.b. Convert the JSX file to Javascript:
yarn babel example.js --presets=@babel/preset-react --out-dir dist

Now you should have the new file /dist/example.js, which is a valid Javascript file (but still not an HTML file). (The extension of this file will be .js, not matter if the original source file was .js or .jsx.)
2. Render HTML
In step 1. you have transpiled the JSX code <example /> inside your original file into the Javascript code React.createElement("example", null) inside the transpiled file, but this is still not HTML, this is a Javascript "React element".
You can use ReactDOMServer to render this React element into HTML:
2.a. In case it's not already installed, then install react and react-dom:
yarn add react react-dom

2.b. Import react and react-dom/server, and use the renderToString() method to render the React element into an HTML string:
const React = require('react'); // <-- React is required, because it is used in the transpiled .js file.
const ReactDOMServer = require('react-dom/server');

const jsxData = <example />;
const htmlString = ReactDOMServer.renderToString( jsxData );

console.log('htmlString:', htmlString);
// app.get("/",function(req,res){ res.send( htmlString )})

Transpile this JSX file again as before. Now inside the ./dist/example.js the htmlString should contain the HTML string which you can send to the client. In this example, if you run e.g. node ./dist/example.js you should see the console output:
htmlString: <example data-reactroot=""></example>


text:
Q: Carbon is returning a wrong date? Laravel 5.6 I'm facing a really weird issue with Carbon in laravel... i'm trying to get a specific date like this:
    $now = Carbon::now()->setTimezone('America/Costa_Rica');

    $currentYear = $now->copy()->year;

    $febmon = $now->copy()->month(2)->startOfMonth();
    dd($febmon);

It's supposed to return: 2018-02-01 00:00:00.0 America/Costa_Rica (-06:00)
But instead i'm getting this: 2018-03-01 00:00:00.0 America/Costa_Rica (-06:00)
I have already tried with all other month numbers, and works perfect but February... no idea what is wrong. Thanks in advance

A: Ok i found the issue, my mistake but if anyone is facing this simple but odd issue:
I'm basing the date depending on now() and i'm setting the month(2) before i set the startOfMonth()
And because today is 30 then it's passing to the next month in February, which is March since February doesn't have 30 days, all i had to do is set startOfMonth() first... so it will take the right date.
Here is the right way:
$now = Carbon::now()->setTimezone('America/Costa_Rica');

$febmon = $now->copy()->startOfMonth()->month(2); //Specify the month at last, and set the startOfMonth() first.
dd($febmon);


text:
Q: How does Alternating Bit Protocol work? From Wikipedia entry on ABP ( http://en.wikipedia.org/wiki/Alternating_bit_protocol ):

When A sends a message, it resends it continuously, with the same
  sequence number, until it receives an acknowledgment from B that
  contains the same sequence number. When that happens, A complements
  (flips) the sequence number and starts transmitting the next message.
When B receives a message that is not corrupted and has sequence
  number 0, it starts sending ACK0 and keeps doing so until it receives
  a valid message with number 1. Then it starts sending ACK1, etc.

I do not understand the particulars.
I understand the pretext and the whole thing with acknowledgements, but the process itself is described differently in different publications.
My question can be summed up with the following two:

*

*What does it mean "...and keeps doing so"? Does it mean that the receiver can send two consecutive acks down the ack channel without any activity from the sender at all? I.e. at that point it is not synchronized with the sender at all?

*What does it mean "resends continuously"? Same as above - is sender completely independent of the receiver during this resending?
There is an alternative coverage of the way it works here, but it gives a conflicting picture again: http://staff.science.uva.nl/~psf/specifications/abp.html

A: First this is a full duplex line as both sides send data continuously.
This protocol is very similar to Stop-and-wait ARQ.
In Stop-and-Wait:
Side A:

 1. set index=0
 2. Send DATA(index) ,set timeout and waits for ACK 0 or timeout
  - If timeout back to 1
 3. If received ACK(index) set index^=1
 4. goto 2

Side B:

 1. Set index to 0
 2. If received DATA(index) Send ACK(index) and index^=1 //(xor)<br>
    else send ACK(index^1)
 3. goto 2

In ABP is also one data packet at a time, the difference is that instead of passively waiting for ACK you keep sending the same data until the first ACK is received.
this protocol has a faster error recovery but is very poor in terms of power efficiency
For your questions:

*

*Receiver is syncronized with the sender.

When B receives a message that is not corrupted and has sequence
  number 0, it starts sending ACK0 and keeps doing so until it receives
  a valid message with number 1

keep doing so for every packet it receives with sequence 0.

*Sender is partialy independent of the receiver in the sence that it keeps sending the same data over and over again, but not entirely as it will move to the next sequence when it receives the ACK.


text:
Q: Add more data from a get request with FastAPI I begun to build an api with FastAPI in python and sqlalchemy :
Here is a part of the models :
class Game(Base):
    __tablename__ = "games"

    id = Column(Integer, primary_key=True, index=True)
    league_id = Column(Integer)
    radiant_score = Column(Integer)
    dire_score = Column(Integer)
    duration = Column(Integer)
    is_valid = Column(Boolean, default=True)

    playerstats = relationship("PlayerStat", back_populates="match")

class PlayerStat(Base):
    __tablename__ = "playerstats"

    match_id = Column(Integer, ForeignKey("games.id"), primary_key=True)
    slot = Column(Integer, primary_key=True)
    hero_id = Column(Integer, ForeignKey("heros.id"))
    num_kills = Column(Integer, default=None)
    isRadiant = Column(Boolean, default=None)

    match = relationship("Game", back_populates="playerstats")
    heros = relationship("Hero", back_populates="playerstats")

After this, I create the schemas/models for pydantic (sry for long portion):
    class PlayerStatBase(BaseModel):
    slot: int
    hero_id: int
    num_kills: int
    isRadiant: bool

class PlayerStatCreate(PlayerStatBase):
    pass

class PlayerStat(PlayerStatBase):
    slot: int
    hero_id: int
    num_kills: int
    isRadiant: bool

    class Config:
        orm_mode = True

class GameBase(BaseModel):
    id: int
    league_id: int
    radiant_score: int
    dire_score: int
    duration: int
    is_valid: bool

class GameCreate(GameBase):
    pass

class Game(GameBase):
    id: int
    league_id: int
    radiant_score: int
    dire_score: int
    duration: int
    is_valid: bool
    players: List[PlayerStat] = [{}]

    class Config:
        orm_mode = True

And the crud function I use with the api :
    def get_match(db: Session, match_id: int):
    print(db.query(models.Game).filter(models.Game.id == match_id))
    return db.query(models.Game).filter(models.Game.id == match_id).first()

The api route is :
@app.get("/matches/{match_id}", response_model=schemas.Game)
def read_game(match_id: int, db: Session = Depends(get_db)):
    db_game = crud.get_match(db, match_id=match_id)
    if db_game is None:
        raise HTTPException(status_code=404, detail="Game not found")
    return db_game

The result I've got is the next :
{
  "id": 1,
  "league_id": 10,
  "radiant_score": 41,
  "dire_score": 5,
  "duration": 3541,
  "is_valid": true,
  "players": [
    {}
  ]
}

I would like to populate "players" with the list of playerstats of the corresponding match (sorted by slot) as :
"players" : [
  {
    "slot": 0,
    "hero_id": 14,
    "num_kills": 54,
    "isRadiant": true
  },
  {
    "slot": 1,
    "hero_id": 15,
    "num_kills": 1,
    "isRadiant": false
  }
]

I think I need to chance one of the model/schema or the crud function but don't really know which one ?
Also, maybe there is some pydantic schema that are useless or poorly built
PS : I followed the guideline of the FastAPI docs (which I recommend to read).
Thx for your help!

A: I believe you problem does not lie within the scope of fastapi, but sqlalchemy. When you query for orm objects with relationships, fastapi's standard is to lazyload relationships whenever they are accessed. Since you never directly access the relationship playerstats, it does not load in. See the docs for information.
The solution to your problem should be to update the crud function to this:
return db.query(models.Game).filter(models.Game.id == match_id)
                            .options(selectinload(models.Game.playerstats)).first()

"Select In Load" is a type of eager load that will load relations as the query is submitted. If you want this behaviour to occur on every query you can update the orm to this:
playerstats = relationship("PlayerStat", back_populates="match", lazy="selectin")

I hope this helped. It is my very first answer on stackoverflow :)
EDIT: There is actually one other thing. In your orm the relationship is called "playerstats" while you name the attribute "players" in your pydantic model. That does not work. Change the pydantic attribute name from "players" to "playerstats" and now everything should work.
EDIT 2: As you can guess no everything will not work yet. I just saw that there is one other thing missing. In pydantic models you can set the orm option. This is very important when working with sqlalchemy. I recommend this for all your pydantic models. This will have to be set on every pydantic model and their attribute models
class OtherModel(BaseModel):
    value: str = None

    class Config:
        orm_mode = True

class SomePydanticModel(BaseModel):
    value: str = None
    some_other_model: OtherModel = None

    class Config:
         orm_mode = True

Now we can also modify the return statement of your crud method again:
return Game.from_orm(db.query(models.Game).options(selectinload(models.Game.playerstats)).filter(models.Game.id == match_id).first())

Now everything should finally work :)


text:
Q: Assuming no compiler optimization, how many times will this object be created? Assuming there is no compiler optimization. How many times would OutputBuffer_s type object will be created?
#include <iostream>
#include <vector>

struct OutputBuffer_s {
    int encoded[10];
};

OutputBuffer_s func() {

    OutputBuffer_s s;

    return s;
}

int main() {
    OutputBuffer_s a = func();
}

Initially, I had assumed three times.
1) When func() is called, object s will be created on stack.
2) When func() goes out of scope, it will return copy of object s to main().
3) Copying of value to object a in main(), since value returned by func() would be a temporary.
I know that I'm wrong here, since I compiled with -O0 in g++ but I could see only one creation after overriding the constructors. I want to know where and why I am wrong.

A: What you have here copy-elison.

Omits copy and move (since C++11) constructors, resulting in zero-copy pass-by-value semantics.

GCC can elide the constructors even with -O0 option. This is what is happening here. If you want to specifically prevent elision, you can use the -fno-elide-constructors option.
If you use this option, there will be one constructor call and two move constructor calls for C++11.
See demo here.
If you use C++17, there is guaranteed copy-elision in some cases, and here even with the -fno-elide-constructors option, there will be one constructor call and just one move constructor call.
See demo here.

A: C++17 has introduced Temporary materialization which I quote:

A prvalue of any complete type T can be converted to an xvalue of the same type T. This conversion initializes a temporary object of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object. If T is a class or array of class type, it must have an accessible and non-deleted destructor.

In that case the extra calls to the contructor will become a move operation. Prior to C++17, which copy elision was not mandatory, the compiler would usually copy elide. As far as I am aware, in your case, a compiler would copy elide anyway (try godbolt and check the produced assembly).
To fully answer, one call to the constructor and one move.


text:
Q: Can't run a Spring Boot test for a simple controller I've got a simple test:
package com.example.app;

import com.example.app.HomeController;

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class HomeControllerTest {

    @Autowired
    private HomeController controller;

}

and a Controller HomeController
The test lives in test/java/com/example/app
and the controller lives in java/com/example/app
Why can the import not be resolved?
It don't work without it either, which it what the tutorial suggests.
Without the import I still get the

Edit:
.
├── [  96]  .mvn
│   └── [ 160]  wrapper
├── [ 128]  src
│   ├── [ 128]  main
│   └── [  96]  test
├── [1.9K]  .classpath
├── [ 395]  .gitignore
├── [ 835]  .project
├── [1.6K]  HELP.md
├── [9.8K]  mvnw
├── [6.5K]  mvnw.cmd
└── [1.6K]  pom.xml

I created the package from Visual Studio Code, but its just a simple maven init template.

A: Your test class contains no test methods. That's why nothing happens when you try to execute it.
What can you do? Implement at least one test method and annotate it with @Test.
Update:
The reason was a look up of a wrong name. No magical reasons. Everyone makes mistakes.

A: This is my example, I tried running and it worked -
@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
public class MainApplicationTest {

  @Autowired
  HomeController homeController;
  @Autowired
  OtherController otherController;

  @Test
  public void testContextLoading() throws Exception{
    assertThat(homeController).isNotNull();
    assertThat(otherController).isNotNull();
  }

}


text:
Q: React setTransition() function causes two re-renders even though there is no state update in it Consider the following code:
import React, {useState, useRef, useEffect, useTransition} from 'react';

function Item({name, _key})
{
   const [isPending, setTransition] = useTransition();
   const [updatingName, setUpdatingName] = useState(false);
   const nameInputElement = useRef();

   useEffect(() => {
      if (updatingName) {
         nameInputElement.current.focus();
      }
   }, [updatingName]);

   function onUpdateClick() {
      setUpdatingName(true);
   }

   function onCancelClick() {
      setUpdatingName(false);
   }

   console.log('rendering');

   return (

         <input ref={nameInputElement} type="text" defaultValue={name} name="name"
         disabled={!updatingName} />

         {!updatingName
         ? <>
            <button key={1} type="button" onClick={onUpdateClick}>Update</button>
            <button key={2} type="submit" name="delete" value={_key}>Remove</button>
         </>
         : <>
            <button key={3} type="button" name="update" onClick={(e) => {
               setTransition(() => {})
            }}>Save</button>
            <button key={4} type="button" onClick={onCancelClick}>Cancel</button>
         </>}

   )
}

function ItemList({title})
{
   return <>

{title}

      <form method="post" onSubmit={(e) => {e.preventDefault()}}>
         <Item name={'small'} _key={0}></Item>
      </form>
   </>
}

export default ItemList;

CodeSandbox demo: https://codesandbox.io/embed/elegant-artem-6zx74r?fontsize=14&hidenavigation=1&theme=dark
When the Save button is clicked, setTransition() is called but there is absolutely no state updates in there — it's completely empty. Hence, I expect there to be no re-renders on the click of Save.
Surprisingly, however, when I click Save, I get to see not just one, but two rendering logs in the console.
Why is this happening? I consulted the React docs, but there is no mention of re-renders performed on setTransition().

A: enter the button into new component and it should not render twice(the button will render).
codesandbox
import { useTransition } from "react";

const Button = () => {
  const [isPending, setTransition] = useTransition();
  return (
    <button
      key={3}
      type="button"
      name="update"
      onClick={(e) => {
        setTransition(() => {
        });
      }}
    >
      Save
    </button>
  );
};
export default Button;


text:
Q: AngularJS select tag validation I am missing something very simple here, i got an array in my controller as follows
    $scope.roles = [
        {id: 0, label: 'Choose a Role'},
        {id: 1, label: 'Administrator'},
        {id: 2, label: 'Super User'}
    ];

And following is my select tag in the view
<select ng-options="role.id as role.label for role in roles" ng-model="myForm.role" ng-required="true">
</select>

How can i validate that the user chose Administrator or Super User and not Choose a Role?

A: From the HTML you can use:
<div ng-if="myForm.role == 'Chose a role">
Your code when 'Chose a role;
</div>

JS:
if ($scope.myForm.role == 'Chose a role) {
   Your code here
}

A: Edit2 : https://jsfiddle.net/3kL9rmp8/
Edit : I made you a fiddle : https://jsfiddle.net/fgpg9zvn/
You can add an option this way :
<select ng-options="role.id as role.label for role in roles"
        ng-model="myForm.role"
        ng-required="true">
       <option value="" disabled selected style="display: none;"> Chose a role </option>
</select>

A: Try this neat and simple solution.
Use this HTML to have select element.
HTML:
<select ng-model="myForm.role"
        ng-options="role.id as role.label for role in roles"
        ng-change="fillTheDDL(role.id, role.label)">

  <option value="">Chose a role</option>

</select>

Use this JS to get the desired functionality.
JS:
$scope.fillTheDDL= function (ID, Label) {
    if (Label != "Choose a Role") {
     // Your favorite code here
    }
    else {
        // You don't wanna use it
    }
};


text:
Q: updating to addEventListerner may cause return value of function not to propagate? I recently upgraded from classical registration using
element.property = function

to advanced registration using
element.addEventListener( "property", function,  bool );

In the function I had returned a false to to disable form submission when the user presses the enter key like this:
tweet_input.addEventListener( "keypress", function( event )
{
    if( event.keyCode === 13 )
    {
       new ModelTweet().invoke();
       return false;
    }
}, false );

However, this no longer works, and every time the user hit the enter key, the form is submitted.
The HTML looks like this:
  <form id="tweet" method="post" name="tweet">

      <input id="tweet_input" name="tweet" type="text" maxlength="40">

Comment

      </input>

Share

  </form>

I use this method on 3 other forms and it works fine.
Updating to advanced registration was the last major change I made but since the other 3 forms work well...I don't understand what the issue is.
I don't see a difference when I compare the code to the other 3 forms which work.
I also recently updated the Model for Tweet, but is is obvious the form is submitted twice, once when I do it by grabbing the Enter Key, and once when it is sumbitted internally by an "enter key post".
Odd.
/**
 *ModelTweet
 */

var ModelTweet = ( function()
{
    var ModelTweetI = function ( )
    {
        this.form_elements = document.getElementById( 'tweet' ).elements,
        this.response_element = document.getElementById( 'tweet_response' );
        this.fill_element = document.getElementById( 'tweet_fill' );

        this.text_object = new TextValidator( this.form_elements );
        this.message_object = new Message( this.response_element );
        this.effects_object= new Effects( this.response_element );

        this.ajax_object = new AjaxRequest();
        this.shared_object = new Shared();

        this.TIME = this.shared_object.get( 'TIME' );
        this.load_on = this.shared_object.get( 'load_on' );
    };
    ModelTweetI.prototype.invoke = function( )
    {
        if( this.load_on === 1 )
        {
            if( !this.text_object.checkEmpty() )
            {
                this.message_object.display( 'empty' );
                this.effects_object.fade( 'down', this.TIME );
                return false;
            }
            if( !this.text_object.checkPattern( 'tweet' ) )
            {
                this.message_object.display( 'tweet' );
                this.effects_object.fade( 'down', this.TIME );
                return false;
            }
        }
        var response_element = this.response_element;
        var fill_element = this.fill_element;
        this.ajax_object.invoke( this.ajax_object.serializeArray( this.form_elements ) + '&ajax_type=tweet_control', function( server_response_text ) { new AjaxResponse( server_response_text, 'tweet', response_element, fill_element ); } );
        var tweet_input = document.getElementById( 'tweet_input' );
            tweet_input.value='';
            tweet_input.blur();
        }
    };
    return ModelTweetI;
} ) ();

A: The return value of the event handler does not do anything when used with addEventListener() so returning false is not designed to do what you are trying to do.
If you want to prevent the default behavior, then you need to call event.preventDefault() (and possibly event.stopPropagation() too) like this:
tweet_input.addEventListener( "keypress", function( event )
{
    if( event.keyCode === 13 )
    {
       new ModelTweet().invoke();
       event.preventDefault();
    }
}, false );

Note: this syntax doesn't work in older versions of IE that don't support addEventListener or event.preventDefault().  They have their own way of doing things with attachEvent and window.event.returnValue = false;.


text:
Q: How can I toggle an element's attributes using pure JavaScript? Most of the similar questions that arose as I wrote this one were like this (where the user wishes to toggle an element's class using pure JS) or this (where the user wishes wishes to toggle other attributes using jQuery)
My question is a mixture of the two. I am aware that the el.classList.toggle() method exists for toggling an element's class using pure JS, but I wish to toggle different attributes using pure JS, specifically the checked attribute of some radio buttons, since this (annoyingly) does not change when different options are selected.
Is it possible to toggle the checked attribute on my two radio buttons with pure JS (by toggling I mean remove the attribute from the element altogether if it is present, and add it if it is not)?

radios = document.getElementsByName("Floor");
for (i = 0; i < radios.length; i++) {
    radios[i].addEventListener('change', function () {
        this.(/*checked attribute*/).toggle()
    }, false);
}
<input checked id="Floor" name="Floor" type="radio" value="0">Ground Floor
<input id="Floor" name="Floor" type="radio" value="1">First Floor

Edit: The possible duplicate question mentioned in the comments does not quite solve my problem. I don't need to change which radio button appears checked, I just want to toggle the checked attribute, to make it easier for me to reference the button that is checked later on in the code. Of course, if there is another, easier way of doing this, I'm all ears.

A: There actually is an Element.toggleAttribute method for boolean attributes. MDN Docs.
However, since it is not supported in IE, you might want to add the MDN Polyfill

A: there is no toggle method for attribute.
You can use:
elm[elm.hasAttribute('hidden')?'removeAttribute':'setAttribute']('hidden', '')

or
elm.hasAttribute('hidden') ? removeAttribute('hidden') : setAttribute('hidden')

EDIT: there is now toggle method for attribute.
elm.toggleAttribute('hidden')

https://developer.mozilla.org/docs/Web/API/Element/hasAttribute

A: This will work definitely well
const attrToggle = (el, attr) => el.getAttribute(attr) == 'false' ? el.setAttribute(attr, "true") : el.setAttribute(
      attr, "false")

It's similar to native toggleAttribute.

A: I didn't test this, but this should do the trick.
radios = document.getElementsByName("Floor");
  for (i = 0; i < radios.length; i++) {
    radios[i].addEventListener('change', function () {
       if ( this.checked ) {
          this.setAttribute("checked", "false");
       } else {
          this.setAttribute("checked", "true");
       }
  }, false);
}

A: Element.toggleAttribute(name) used to toggle boolean attribute https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute
this.toggleAttribute("checked");

A: To anyone stumbling on this question, no one in comments or answers since 2017 seems to have pick up on the OP's incorrect assumptions on the true nature of the checked element attribute they are trying to 'toggle'. As this post has so far been viewed 19k times, here is the information you might actually be looking for:
<input type="radio" checked>

In this context the element's checked attribute is a flag developers can use to tell the browser to render a "checked" state on a radio or checkbox input on page load. After page load, the browser does not update or toggle this attribute when a user later selects or un-selects the input.
From MDN:

Checked: A Boolean attribute which, if present, indicates that this radio button is the default selected one in the group.

Therefore the approach of using Element.toggleAttribute('checked') suggested by some here, won't work as expected as the .toggleAttribute() method adds or removes the pre-render flag from the input, but doesn't update the element's 'checked' state as the OP is trying to do. Applying a boolean value to the attribute also has no effect on the state of the element: (this wont work) checked="false"
In JavaScript you can access the current state of an input through HTMLInputElement's IDL boolean property .checked, not to be confused with the Element attribute by the same name referenced by the OP. Here HTMLInputElement.checked is both a getter and setter, meaning you can access (and toggle the value of) .checked as follows:
<input type="radio" id="spam-machine" class="blackhat" name="spam-me" value="sure!">

<script>
    const spamMe = document.querySelector('#spam-machine');
    spamMe.checked = !spamMe.checked;
</script>

You can additionally selectively style checked inputs using the :checked CSS pseudo class:
input[type="radio"].blackhat:checked { visibility: hidden; }

Now go forth into the world .... rendering to no one evil for evil.


text:
Q: An inequality for absolute total curvature in Riemannian surfaces Let be $M\subseteq \mathbb{R}^3$ a compact (Riemannian) surface and let be $K$ the gaussian curvature of $M$.
I want to prove that
$$ \int_{M} |K| \geq 4\pi(1+g(M))$$
where $g(M)$ is the genus of $M$. I tried using the following inequalities:
$$  \int _M |K|=\int_{K>0} K - \int_{K<0} K \geq 4\pi -\int_{K<0} K\geq 4\pi -\int_M K$$
but I had no luck even using Gauss Bonnet. Any hint?

A: You are almost there, you just throw away too much:
$$\begin{split}
\int_M |K| &= \int_{K>0} K - \int_{K<0} K = \int_{K>0} K - \left(\int_{K<0} K + \int_{K>0} K - \int_{K>0} K\right)\\
&= \int_{K>0} K - \left(\int_M K - \int_{K>0}K \right)\\
&= 2\int_{K>0} K - \int_M K\ .
\end{split}$$


text:
Q: arcpy.da.SearchCursor keeps running, without any response or error I am using 'arcpy.da.SearchCursor' in Python script for ArcGIS 10.5, while the script is always keeping running, without any result and error. I use print to see where the problem is; it seems that 'arcpy.da.SearchCursor' cannot be finished, as it does not print 2. However, this works well if I use these syntaxes in the Python window of ArcMap.
Here is the code:
import arcpy

fc = r'C:\\Users\hsdfyan1\Desktop\add_point_attributes\Feb_8_1_e_pth_split_join.shp'
fileds = ['time_first', 'time_last', 'SHAPE@']
print(1)
cursor = arcpy.da.SearchCursor(fc, fileds)
print(2)
for row in cursor:
    print(row[0],row[1])

The only result is 1

A: I think you should either use r or all double backslashes in your path.
So change fc = r'C:\\Users\h... to fc = r'C:\Users\h...
When not using with you should delete the cursor, as last line in your code:
del(cursor)

Try this:
import arcpy

fc = r'C:\Users\hsdfyan1\Desktop\add_point_attributes\Feb_8_1_e_pth_split_join.shp'
fields = ['time_first', 'time_last']

with arcpy.da.SearchCursor(fc, fields) as cursor:
    for row in cursor:
        print row


text:
Q: apache axis 2 CLOSE_WAIT issue I have generated web service client using apache axis 2 1.6.2.
On every request new connection is created and upon successful completion of request/ on error connection is not closed. That cause connection timeout problem to future requests.
I have checked through netstat command and there are all connection present with CLOSE_WAIT status and does not release the connection.
All connection are not release by apache axis 2 client automatically.
I have found two ways but don't know that will work or not or it can create any ripple effect.
one is to set AUTO_RELEASE_CONNECTION_PROPERTY and second is REUSE_HTTP_CLIENT
I have generated client through myeclipse by using apache axis 2

A: I was facing similar issue in my previous project & I get it resolved by using Spring's WS managed bean. This issue arises, because you are making port object each time, which create http connection each time and not properly closed.
See the following code,
    <bean id="viewBillInfo"
    class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean"
    p:serviceInterface="com.javaplex.CustomerInfoInterface"
    p:wsdlDocumentUrl="http://10.0.5.50:8080/portal/CustomerInfoPort?wsdl"
    p:namespaceUri="http://ws.customergen.com/" p:serviceName="CustomerInfo"
    p:portName="CustomerInfoPort">

here is the complete article how to setup spring based beans which give your optimum performance.
http://www.javaplex.com/spring-jax-ws-client-for-best-performance/


text:
Q: Swift headless webView I am trying to create an app that uploads data to a third party website via a form on their site. I don't have access to the backend of the website, so my process so far to test has been loading the site in a WKWebView and using evaluateJavascript to place my data into the input fields, then 'clicking' submit.
This works, but I'd like it to happen in the background (i.e. no visible webView on the screen).
I've seen third party packages like Erik and WKZombie offer headless browsing but I'm wondering if there is a way to do it without these?
This page talks about setting the frame to .zero but crashes the app.
Are there any suggestions for running a headless webview in Swift? If I do need to use a third party package, does anyone have experience to suggest if the app may be rejected?
Many thanks


text:
Q: ngAfterViewChecked is not late enough I'm using materialize as a substitute to bootstrap.
I have a problem in which a select's options are not yet loaded, in which case calling materialize's initialization will not display correctly:
given my data:
    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.sass']
    })
    export class FormComponent implements OnInit {
      inputTest= {
        value: 1,
        choiceValues: [1,2,3,4]
      };
    }

the following html:
      <select [(ngModel)]='inputTest.value' [ngModelOptions]="{standalone: true}">
        <ng-container *ngFor="let choiceValue of inputTest.choiceValues">
          <option [ngValue]="choiceValue">{{choiceValue}}</option>
        </ng-container>
      </select>

with the following :
  ngAfterViewChecked() {
    if (this.needsInitialization) {//just a guard to have the initialization once
      this.needsInitialization = false;

        let elems: NodeListOf<Element> = this.elementRef.nativeElement.querySelectorAll('select');
        M.FormSelect.init(elems, {});
  }

will display (weirdly, all options are visible!):

and on click:

Using a setTimeout will work:
      ngAfterViewChecked() {
        if (this.needsInitialization) {
          this.needsInitialization = false;
            setTimeout(() => {
              let elems: NodeListOf<Element> = this.elementRef.nativeElement.querySelectorAll('select');
              M.FormSelect.init(elems, {});
            }, 1000);
    }

As per: https://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence
ngAfterViewChecked is the last sequence before ngDestroy. but it does not do what it promises: having loaded the view completely.
How do I use something better than a timeout, when angular's lifecycle is not working properly?


text:
Q: Aligning numbers in a list I am trying to align the numbers in a list as in the picture below. Currently when I do it the (i) and (ii) are aligned on the left just by starting a new line of code, but how do I get them to be aligned on the right?

A: I suggest you load the enumitem package and define a dedicated enumerate-like list environment that uses lowercase-roman letters.

\documentclass{article}

\usepackage{enumitem}
\newlist{romanenum}{enumerate}{1}
\setlist[romanenum]{label=(\roman*)} % roman numerals, encased in parentheses

\begin{document}
\begin{romanenum}
\item For any natural number \dots
\item If $a,b,c,d\in M$, \dots
\end{romanenum}
\end{document}