text:
Q: Testing slopes in multivariate adaptive regression splines (MARS/earth) I am using the earth package in R to estimate the number of breakpoints in a curve. There is only a single predictor.
I was hoping there was a sensible way to compare a slope for some segment against 0. Normally I would use the estimate and standard error, but it's not obvious (to me) what to do for segments that are combinations of multiple slopes:
        estimate    SE
(intercept) 2.78        .015
h(age-4)    -.01        .0029
h(4-age)    -.35        .015
h(age-11)   -.076       .0055

So the slope after age 11 is -.086. How do I quantify my confidence that this slope really is negative?

A: The short answer: you can't quantify that precisely.
You can have confidence in the model AS A WHOLE (because of the GCV, see for example the FAQ in the earth package vignette "What is a GCV in simple terms?") but can't easily quantify the significance of each part of the model.
The problem is actually worse than quantifying confidence in the effect of two combined hinge functions, because we can't even quantify the effect of each hinge function in isolation.  The standard error values you quote are unlikely to be valid.  (I assume you got those SEs by doing a linear regression on the MARS basis matrix i.e.  lm(y ~ earth.model$bx - 1) ).
If we were certain of the position of a knot, we can do a standard linear regression on the slope at that knot, and get standard linear regression SEs and p-values for that slope.  But of course with a different sample, MARS might choose a somewhat different position of the knot.  Since we aren't certain of the position of the knot, those p-values overstate certainty, often dramatically.
Another way of looking at is to remember that the MARS algorithm does a lot of work to select only good terms.  Terms that would have a bad p-value are tossed out by the MARS forward pass during the knot selection process.  So lm(y ~ earth.model$bx - 1) will always give good p-values, because all terms in bx have been pre-selected to be "good".  But all the uncertainty in the selection process is ignored by lm.  To quote the earth vignette Section 3: variable selection overstates the significance of the selected variables.  This is true in general and also in the specific case of MARS.
To gain confidence in the model as a whole, one possibility is to do as Gavin Simpson says --- bootstrapping.  The earth function has built in cross-validation facilities, so cross-validation would be an easier way to go than bootstrapping.  Each bootstrap or cross-validation iteration will give slightly different hinge functions, so it doesn't help in formally quantifying confidence in the position of the hinges in the full model, although may give some informal confidence.  Earth will soon have facilities for estimating prediction intervals that may help in terms of the big picture of what you are trying to do.

A: To some extent, MARS has already "tested" the slopes in so far as predictive ability via the CV procedure used. Of course, this assumes the CV has been done in a way that matches the experimental design or dependencies in the data.
If you wanted to get better estimates of the standard errors, I would suggest a bootstrap approach, which is computationally demanding but will give you SEs or a distribution from which to compute a confidence interval
You'll need to bootstrap the whole process of course. Start with the boot package and write a wrapper to the MARS function accordingly to fit the model to a given bootstrap sample and return the slopes from the wrapper.


text: Q: Scalar triple product of three vectors at 60 degrees to each other I encountered a question involving a scalar triple product of three vectors of unit length which were mutually at 60 degrees to each other. While the answer involved taking the root of the square of the resulting determinant (since the only terms inside turn out to be 1 or $\frac{1}{2}$), I would like to know how to get the angle between $\hat{a}$ and $\hat{b} \times \hat{c}$ to calculate the cross product for the volume. I figured $\hat{a}$ should be in the same plane as the resultant and dot product of $\hat{b}$ and $\hat{c}$ in this scenario (which are perpendicular to each other) but I can't figure out the angle between them. I'm probably missing something trivial here so any hints would be appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is Haskell complaining about this plus sign? From this code intended to convert a balanced ternary representation to a Haskell Integer:
frombal3 :: String -> Integer
frombal3 "+" =  1
frombal3 "0" =  0
frombal3 "-" = -1
frombal3 current:therest = \
  (*) frombal3 current (^) 3 length therest \
  + frombal3 therest

I got the error:
main.hs:7:3: error: parse error on input '+'
  |
7 |   + frombal3 therest
  |   ^
<interactive>:3:1: error:
   • Variable not in scope: main
   • Perhaps you meant 'min' (imported from Prelude)

A: It is not clear what you are trying to achieve, but I can see some mistakes that can be already pointed out.
Problems
You don't need \ to continue a line, that's only needed inside strings. Indentation is enough in Haskell
You need to wrap your pattern matching with parenthesis: (current:therest). Furthermore, this pattern will make current a Char and not a String, so you cannot directly pass it to your function that takes a String.
You need to wrap your function arguments as well: if you want to multiply frombal3 current by 3, you need (*) (frombal3 current) 3, or the much better frombal3 current * 3. Infix functions have higher precedence and make the code more clear.
Suggestions
I am not sure what you want to achieve, but this looks like somthing that can be done with a fold or simple list comprehension

A: Don't use backslashes, and remember to properly bracket pattern matches:
frombal3 :: String -> Integer
frombal3 "+" =  1
frombal3 "0" =  0
frombal3 "-" = -1
frombal3 (current:therest) = -- ^ Note brackets
  (*) frombal3 current (^) 3 length therest
  + frombal3 therest

This still causes a problem due to how you're using operators, but I think you can solve this on your own, especially since I can't work out what you're trying to do here.

A: You appear to be trying to use backslashes to continue onto the next line; don't do that. If you just delete all the backslashes, the error will go away. (You'll get several other errors, but this particular one will go away.)
Haskell uses indentation to detect where one part ends and the next begins. You don't need to manually add backslashes to the end of each line to continue an expression.


text:
Q: WordPress creating table with dbDelta not working in plugin I've a problem with my custom WordPress plugin creating a table with dbDelta. For creation I've created a function that returns my table when I call dbDelta:
private function get_db_schema(): string {
    $collate = '';

    if ( $this->wpdb->has_cap( 'collation' ) ) {
        $collate = $this->wpdb->get_charset_collate();
    }

    return "
    CREATE TABLE {$this->wpdb->prefix}woomex_exported_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        order_id BIGINT UNSIGNED NOT NULL,
        status varchar(255) NOT NULL,
        payment_status varchar(255) NOT NULL DEFAULT 'pending',
        invoice_status varchar(255) NOT NULL DEFAULT 'pending',
        cancellation_invoice_status varchar(255) NOT NULL DEFAULT 'pending',
        delivery_status varchar(255) NOT NULL DEFAULT 'pending',
        date_exported timestamp NOT NULL default CURRENT_TIMESTAMP
    PRIMARY KEY  (id)
    ) $collate;
    ";
}

After that I'm calling:
dbDelta( $this->get_db_schema() );

I'm getting no errors but also no table. I'm sure my function get's called because I verified this by a logging in it. Does anyone know what I'm doing wrong here?


text:
Q: How to get the location of centered place pin on Map like uber android app Someone please explain me how to get the location of centered place pin on Google Map Like in this Uber App. User can move the map but pin is always centered align and We can get the location as we keep moving the map.

A: I'm not sure what language your using so here's a javascript solution. try creating latlng variable and using that variable to both place the marker and define center. You could do Something like this

var markerLatlng = new google.maps.LatLng ("your coords here");
var mapOptions = {
 zoom :5,
 center: markerLatlng,
 mapTypeId: google.maps.MapTypeId.ROADMAP
 };

var marker = new google.maps.Marker({
 position: markerLatlng,
 map: map,
 animation: google.maps.Animation.DROP,
 title: "your title here",
 });

Hope this helps.

A: You can use CurrentCenterPositionMap
First import the lib:
compile 'br.com.simplepass:mapfragmentwrapper:0.8.0'

Then, all you have to do is to put the MapFragmentWrapper xml tag as a container of your map fragment. Like this:
<br.com.simplepass.mapfragmentwrapper.MapFragmentWrapper
    android:id="@+id/map_wrapper"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/main_fragment_map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</br.com.simplepass.mapfragmentwrapper.MapFragmentWrapper>

See the result:


text:
Q: Magento 2: Run setup:di:compile a Specific Module Is it possible to di compile to specific module instead of whole magento di compile ?
Because, Whole Magento take a long time to compile. So, is it possible to di compile to specific module.
php bin/magento setup:di:compile CompanyName_ModuleName

Please help me. If it is possible.

A: If your focus is to try to contain as well as possible the downtime of your production, the below may help:
You could clone your codebase on the same server and separate folder (clone basically).
Once both environments would coexist, you can deploy static content on the clone without penalising the production environment uptime.
Finally, when the deploy is complete, you could either symlink the pub/static folder or just rsync. Of course, this may be done with a script.

A: You can do this by follow this step :
Go to :

/var/www/html/YourMagento/setup/src/Magento/Setup/Console/Command/DiCompileCommand.php

Find this line :
$modulePaths = $this->componentRegistrar->getPaths(ComponentRegistrar::MODULE);

Replace this below line and add path of the module which you want to compile like this :
$modulePaths = ['CompanyName_ModuleName' => '/var/www/html/YourMagento/app/code/CompanyName/ModuleName'];

Make sure module register with thisCompanyName_ModuleName in registration.php file.
It's temporary solution for di compile single module. Remove di generated module folder and refresh cache.
Hope, It will helpful for you.
Reference


text:
Q: Connecting to SQL Server from Azure Databricks I am trying to connect to SQL Server (on Azure VM) from Azure Databricks. I tried connecting using Python and Scala, but failed to connect.
I get the error:
The TCP/IP connection to the host HOSTNAME, port 1433 has failed.
I used the code in the following link:
https://docs.databricks.com/data/data-sources/sql-databases.html
Both the SQL Server and the Databricks are on the same VNET.
I tried connecting to the SQL Server using "username" and "pwd" and I am able to connect from Management Studio on a Windows laptop.
val jdbcUrl = s"jdbc:sqlserver://${jdbcHostname}:${jdbcPort};database=${jdbcDatabase}"

I have the following details:

*

*Server Name -  ABCD\EFGH  (this is what I use to connect from Management Studio on Windows)

*IP Address

*I am using the default port 1433

*Fully qualified name - ABCD.lalaland.lala.lala.la

*Database name

*Username / pwd

What am I missing? What should the hostname be in JDBC URL? Should the instance name be included?

A: According to the Subnets reqirement, the virtual network must include two subnets dedicated to Azure Databricks: a private subnet and public subnet. As @samuelsaumanchan said, you can try enabling service endpoints on the vnet hosting both your sql server as well as your databricks instance. Service Endpoints enables private IP addresses in the VNet to reach the endpoint of an Azure service without needing a public IP address on the VNet.


text:
Q: Box or [ around multiple lines inside align I have the following code
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\begin{alignat*}{4}
        \begin{minipage}[h!]{0\linewidth}
            \text{Let:} \end{minipage}
        && G_{\delta_r}^{\beta} &= \frac{n_1 s + n_0}{s^2 + d_1 s + d_0} = \frac{0.01956 s + 7.01}{s^2 + 0.802 s + 6.489} \\
        && step \left(G_{\delta_r}^{\beta}(s) \right) = \frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1}{s} \cdot \frac{n_1 s + n_0}{s^2 + d_1 s + d_0} \\
        \\
        % \left[
        % \makebox[0\linewidth][s] {
        %   \begin{dcases}
                \makebox[0\linewidth][s]{Expanding with partial fractions:} \\
                && \frac{x_1}{s} + \frac{x_{21}s + x_{20}}{s^2 + d_1 s + d_0} &= \frac{1}{s} \cdot \frac{n_1 s + n_0}{s^2 + d_1 s + d_0} \\
                \\
                \makebox[0\linewidth][s]{Removing denominator:} \\
                && x_1(s^2 + d_1 s + d_0) + s(x_{21} s + x_{20}) &= n_1 s + n_0 \\
                \\
                \makebox[0\linewidth][s]{Has solutions:} \\
                \makebox[0\linewidth][s]{
                \begin{minipage}[h!]{0.3\linewidth} \centering
                    $x_{21} = \frac{-n_0}{d_0} = -1.08$ \end{minipage}
                \begin{minipage}[h!]{0.3\linewidth} \centering
                    $x_1 = \frac{n_0}{d_0} = 1.08$ \end{minipage}
                \begin{minipage}[h!]{0.3\linewidth} \centering
                    $x_{20} = n_1 - \frac{n_0 d_1}{d_0} = -0.847$ \end{minipage} }
            % \end{dcases}
            % }
        \\
        \begin{minipage}[h!]{0\linewidth}
            \text{Hence:} \end{minipage}
        && \frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1.08}{s} - \frac{1.08s + 0.847}{s^2 + 0.8-2s + 6.489} \\
        \\
        \makebox[0\linewidth][s]{Completing the square:} \\
        && \frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1.08}{s} - \frac{1.08s + 0.847}{(s + 0.401)^2 + 6.328} \\
        \makebox[0\linewidth][s]{Inverse Laplace:} \\
        && \mathcal{L}^{-1}\left\{ \frac{G_{\delta_r}^{\beta}(s)}{s} \right\} &=  1.08 - e^{-.401t} \left(1.08 \cos(t\sqrt{6.328}) + \frac{0.847}{\sqrt{6.328}} \sin(t\sqrt{6.328}) \right)
    \end{alignat*}
\end{document}

Which produces:

I would like to put a box (or some kind of a bracket) like the one shown in the picture to denote "sub working out". The complications are that the box will need to span many lines of equations and many columns of the alignat environment.
I have tried many things including \makebox, \minipage, \bcases, \matrix
Any suggestions?

A: An option using a \parbox inside a \fcolorbox inside a \makebox, and the whole construct inside \intertext; some changes to the original mark-up were done (in particular, the code was greatly simplified), but the original alignment of expressions before and after the box was preserved:
\documentclass{article}
\usepackage{mathtools}
\usepackage{tikzpagenodes}
\usetikzlibrary{tikzmark}

\begin{document}

Let:
\begin{align*}
G_{\delta_r}^{\beta} &= \frac{n_1 s + n_0}{s^2 + d_1 s + d_0} = \frac{0.01956 s + 7.01}{s^2 + 0.802 s + 6.489} \\
\text{step} \left(G_{\delta_r}^{\beta}(s) \right) = \frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1}{s} \cdot \frac{n_1 s + n_0}{s^2 + d_1 s + d_0}
\intertext{%
\makebox[\linewidth][c]{\fcolorbox{blue}{white}{\parbox{\linewidth}{%
Expanding with partial fractions:
\[
\frac{x_1}{s} + \frac{x_{21}s + x_{20}}{s^2 + d_1 s + d_0} =
\frac{1}{s} \cdot \frac{n_1 s + n_0}{s^2 + d_1 s + d_0}
\]
Removing denominator:
\[
x_1(s^2 + d_1 s + d_0) + s(x_{21} s + x_{20}) = n_1 s + n_0
\]
Has solutions:
\[
x_{21} = \frac{-n_0}{d_0} = -1.08\qquad
x_1 = \frac{n_0}{d_0} = 1.08\qquad
x_{20} = n_1 - \frac{n_0 d_1}{d_0} = -0.847
\]
Hence:}}}
}
\frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1.08}{s} - \frac{1.08s + 0.847}{s^2 + 0.8-2s + 6.489} \\
\shortintertext{Completing the square:}
\frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1.08}{s} - \frac{1.08s + 0.847}{(s + 0.401)^2 + 6.328} \\
\shortintertext{Inverse Laplace:}
\mathcal{L}^{-1}\left\{ \frac{G_{\delta_r}^{\beta}(s)}{s} \right\} &=  1.08 - e^{-.401t} \left(1.08 \cos\alpha + \frac{0.847}{\sqrt{6.328}} \sin\alpha \right),
\end{align*}
where $\alpha=t\sqrt{6.328}$.

\end{document}

Another option would be to use the tikzmark library; the idea is to use \tikzmark to place marks at the appropriate locations and then to use those marks to draw the blue rectangle.
Below I show this approach and also illustrate another option for the mark-up (of course, this approach will also work with the above approach or with any other variation):
\documentclass{article}
\usepackage{mathtools}
\usepackage{tikzpagenodes}
\usetikzlibrary{tikzmark}

\begin{document}

Let:
\begin{align*}
G_{\delta_r}^{\beta} &= \frac{n_1 s + n_0}{s^2 + d_1 s + d_0} = \frac{0.01956 s + 7.01}{s^2 + 0.802 s + 6.489} \\
\text{step} \left(G_{\delta_r}^{\beta}(s) \right) = \frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1}{s} \cdot \frac{n_1 s + n_0}{s^2 + d_1 s + d_0}
\end{align*}
\tikzmark{start}Expanding with partial fractions:
\[
\frac{x_1}{s} + \frac{x_{21}s + x_{20}}{s^2 + d_1 s + d_0} =
\frac{1}{s} \cdot \frac{n_1 s + n_0}{s^2 + d_1 s + d_0}
\]
Removing denominator:
\[
x_1(s^2 + d_1 s + d_0) + s(x_{21} s + x_{20}) = n_1 s + n_0
\]
Has solutions:
\[
x_{21} = \frac{-n_0}{d_0} = -1.08\qquad
x_1 = \frac{n_0}{d_0} = 1.08\qquad
x_{20} = n_1 - \frac{n_0 d_1}{d_0} = -0.847\tikzmark{end}
\]
Hence:
\begin{align*}
\frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1.08}{s} - \frac{1.08s + 0.847}{s^2 + 0.8-2s + 6.489} \\
\shortintertext{Completing the square:}
\frac{G_{\delta_r}^{\beta}(s)}{s} &= \frac{1.08}{s} - \frac{1.08s + 0.847}{(s + 0.401)^2 + 6.328} \\
\shortintertext{Inverse Laplace:}
\mathcal{L}^{-1}\left\{ \frac{G_{\delta_r}^{\beta}(s)}{s} \right\} &=  1.08 - e^{-.401t} \left(1.08 \cos(t\sqrt{6.328}) + \frac{0.847}{\sqrt{6.328}} \sin(t\sqrt{6.328}) \right)
\end{align*}

\begin{tikzpicture}[remember picture,overlay]
\draw[line width=1.5pt,blue]
  ([xshift=-1ex,yshift=2.5ex]current page text area.west|-{pic cs:start})
  rectangle
  ([yshift=-2.5ex]current page text area.east|-{pic cs:end});
\end{tikzpicture}

\end{document}


text:
Q: How to fill the treeTableView correctly I have a record in database which being get must be in the tree table view. Here is the filling method:
 private void updateGoods(){
        goodsPane.setCenter(goodTreeTableView);
        List<Good> goodAndFoldersList;
       try {
           goodAndFoldersList = goodsService.getGoods();//database query
       }catch (SQLException e){
           goodAndFoldersList = new ArrayList<>();
           log.log(Level.ERROR, e.getMessage());
       }
           List<Good> goods = new ArrayList<Good>();//list for roots
           List<Good> roots = new ArrayList<Good>();//list for goods themselves
           for (Good good : goodAndFoldersList) {
               if (good.isIs_folder()) {
                   roots.add(good);
               } else {
                   goods.add(good);
               }
           }
           TreeItem<Good> rootItem = new TreeItem<>();//the main root
           for (Good root : roots) {
               Long folderId = root.getId();
               TreeItem<Good> rootTreeItem = new TreeItem<>(root);
               for (Good good : goods) {//looking for goods for each folder
                   if (good.getFolderId() == folderId) {
                       TreeItem<Good> goodTreeItem = new TreeItem<>(good);
                       rootTreeItem.getChildren().add(goodTreeItem);
                   }
               }
               rootItem.getChildren().add(rootTreeItem);//adding every folder to the main root
           }
           goodTreeTableView = new TreeTableView<>(rootItem);
    }

after this method user doesn't see anything in the treeTableView. Maybe there nessessary to define cell content, but this code being put before goodTreeTableView = new TreeTableView<>(rootItem); drops NullPointerException:
        goodName.setCellValueFactory((TreeTableColumn.CellDataFeatures<Good, String> param) ->
                new ReadOnlyStringWrapper(param.getValue().getValue().getName()));
        folderId.setCellValueFactory((TreeTableColumn.CellDataFeatures<Good, Number> param) ->
                new ReadOnlyLongWrapper(param.getValue().getValue().getFolderId()));
        is_folder.setCellValueFactory((TreeTableColumn.CellDataFeatures<Good, Boolean> param) ->
                new ReadOnlyBooleanWrapper(param.getValue().getValue().isIs_folder()));

I guess this is the reason of my problem but why this drops NPE I can't figure out.
UPD: if I add setting cell value factory I get the following stacktrace:
javafx.fxml.LoadException:
/D:/javaEdi/linkserver/ediagent/target/classes/com/ediagent/edi/gui/Main.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2595)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2565)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2435)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2403)
    at com.ediagent.edi.gui.Main.initRootLayout(Main.java:44)
    at com.ediagent.edi.gui.Main.start(Main.java:27)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(LauncherImpl.java:821)
    at com.sun.javafx.application.LauncherImpl$$Lambda$51/1546859350.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
    at com.sun.javafx.application.PlatformImpl$$Lambda$44/1712669532.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/157858792.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
    at com.sun.javafx.application.PlatformImpl$$Lambda$46/1225373914.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
    at com.sun.glass.ui.win.WinApplication$$Lambda$37/152005629.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2560)
    ... 18 more
Caused by: java.lang.NullPointerException
    at com.ediagent.edi.gui.MainController.updateGoods(MainController.java:309)
    at com.ediagent.edi.gui.MainController.initialize(MainController.java:328)
    ... 28 more

**UPD:**rootItem:

A: You are adding the data to an GUI element on FXML, by re-initializing it. Avoid re-initialization of FXML elements.
You can change the signature of updateGoods() to :
public TreeItem<Good> updateGoods() {
...
}

and use it in the MainController to set items
goodTreeTableView.setRoot(updateGoods());

Preferably, you can also return only data(List) from updateGoods() instead of returning a TreeItem. Create it in the Controller and set it as the root of goodTreeTableView.


text:
Q: increment counter in XSLT 1.0 This is the input XML:
<Move-Afile>
  <Afile>
    <Item>
      <PackNumber>1234</PackNumber>
    </Item>
    <Item>
      <PackNumber>567</PackNumber>
    </Item>
    <Item>
      <PackNumber>567</PackNumber>
    </Item>
    <Item>
      <PackNumber>126</PackNumber>
    </Item>
    <Item>
      <PackNumber>876</PackNumber>
    </Item>
  </Afile>
</Move-Afile>

<Item> is an unbounded element which contains <PackNumber> as a child element. For each pack number we need to increment the counter variable, but here one condition is present like if previous <PackNumber> is equal to current <PackNumber> we have to ignore the counter (there is no need to increment) like below output.
Inside the for-each, can we  get the counter like below XSLT sample?
This is my XSLT template
<xsl:template match="/">

    <target>
      <xsl:for-each select="/inp1:Move-Afile/inp1:Afile/inp1:Item/inp1:PalletNumber">

        <xsl:variable name="count">

        </xsl:variable>

        <counter>$count</counter>
        <PNumber><xsl:value-of select="."/></PNumber>

      </xsl:for-each>
    </target>

</xsl:template>

This is the XML output:

  <target>
    <Item>
      <counter>1</counter>
      <PNumber>1234</PNumber>
    </Item>
    <Item>
      <counter>2</counter>
      <PNumber>567</PNumber>
    </Item>
    <Item>no need to increment
      <PNumber>567</PNumber>
    </Item>
    <Item>
      <counter>3</counter>
      <PNumber>126</PNumber>
    </Item>
    <Item>no need to increment
      <PNumber>126</PNumber>
    </Item>
  </target>

XML output 2:
<?xml version="1.0"?>

  <target>
    <counter>1</counter>
    <PNumber>1234</PNumber>
    <counter>2</counter>
    <PNumber>567</PNumber>

    <counter>3</counter>
    <PNumber>126</PNumber>
    <counter>4</counter>
    <PNumber>876</PNumber>
  </target>

A: Try this:

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output indent="yes"/>

        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="text()" />

        <xsl:template match="PackNumber">
            <xsl:if test="not(preceding::PackNumber =.)" >

                <counter>
                    <xsl:value-of select="count(preceding::PackNumber[not(preceding::PackNumber= .)])+1"/>
                </counter>
            </xsl:if>
            <PNumber>
                <xsl:value-of select="."/>
            </PNumber>

        </xsl:template>

    <xsl:template match="/">

            <target>
                <xsl:apply-templates select="//Item"/>
            </target>

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

Update according the changed question:
get the count here (inside a for each loop as variable)
Try this:
    <?xml version="1.0" encoding="utf-8"?>

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output indent="yes"/>

        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="text()" />

        <xsl:template match="PackNumber" mode="count">
                <xsl:value-of select="count(preceding::PackNumber
                          [not(preceding::PackNumber= .)and not( . = current()/. ) ])+1"/>
        </xsl:template>

        <xsl:template match="/">

                <target>
                    <xsl:for-each select="//Item/PackNumber">
                        <xsl:variable name="count">
                            <xsl:apply-templates select="." mode="count"/>
                        </xsl:variable>
                                <counter>
                                    <xsl:value-of select="$count"/>
                                </counter>
                                <PNumber>
                                    <xsl:value-of select="."/>
                                </PNumber>
                    </xsl:for-each>
                </target>

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

Update  Output:
<?xml version="1.0"?>

  <target>
    <counter>1</counter>
    <PNumber>1234</PNumber>
    <counter>2</counter>
    <PNumber>567</PNumber>
    <counter>2</counter>
    <PNumber>567</PNumber>
    <counter>3</counter>
    <PNumber>126</PNumber>
    <counter>4</counter>
    <PNumber>876</PNumber>
  </target>

A: Here is a short and very efficient solution, using Muenchian grouping:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kPackNByVal" match="PackNumber" use="."/>

 <xsl:template match="Afile">

       <target>
         <xsl:apply-templates select=
         "*/*[generate-id() = generate-id(key('kPackNByVal',.)[1])]"/>
       </target>

 </xsl:template>

 <xsl:template match="PackNumber">
   <counter><xsl:value-of select="position()"/></counter>
   <PNumber><xsl:value-of select="."/></PNumber>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:
<Move-Afile>
  <Afile>
    <Item>
      <PackNumber>1234</PackNumber>
    </Item>
    <Item>
      <PackNumber>567</PackNumber>
    </Item>
    <Item>
      <PackNumber>567</PackNumber>
    </Item>
    <Item>
      <PackNumber>126</PackNumber>
    </Item>
    <Item>
      <PackNumber>876</PackNumber>
    </Item>
  </Afile>
</Move-Afile>

the wanted, correct result is produced:

   <target>
      <counter>1</counter>
      <PNumber>1234</PNumber>
      <counter>2</counter>
      <PNumber>567</PNumber>
      <counter>3</counter>
      <PNumber>126</PNumber>
      <counter>4</counter>
      <PNumber>876</PNumber>
   </target>

A: If the result you need is what you show in your second XML sample, then this stylesheet is all you need.
All it does is copy the PackNumber from only those Item elements that have no previous matching PackNumber.
The count is calculated as one more than the number of preceding Item elements that have no matching predecessor.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:strip-space elements="*"/>
  <xsl:output method="xml" indent="yes" encoding="UTF-8" omit-xml-declaration="yes"/>

  <xsl:template match="/">

      <target>
        <xsl:apply-templates select="*"/>
      </target>

  </xsl:template>

  <xsl:template match="Item">
    <xsl:if test="not(PackNumber = preceding-sibling::Item/PackNumber)">
      <counter>
        <xsl:value-of select="1+count(preceding-sibling::Item[not(PackNumber = preceding-sibling::Item/PackNumber)])"/>
      </counter>
      <xsl:copy-of select="PackNumber"/>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

output

   <target>
      <counter>1</counter>
      <PackNumber>1234</PackNumber>
      <counter>2</counter>
      <PackNumber>567</PackNumber>
      <counter>3</counter>
      <PackNumber>126</PackNumber>
      <counter>4</counter>
      <PackNumber>876</PackNumber>
   </target>

A: Rather than using counter variable and attempting to increment its value every time (Which anyway not going to happen as the variables in xsl are actually constants), try using position(), which can work as a unique incrementing identifier. Following is an example of the syntax using position():
<xsl:variable name="counterAlias" select="position()"/>


text:
Q: How can I integrate a D3 & Three.js object as a Vue 3 component? I am trying to create a Vue 3 component based off of a D3 & Three.js object that I found online written by Mike Bostock.
This is the object that I would like to use:
https://bl.ocks.org/mbostock/2b85250396c17a79155302f91ec21224
It's given as HTML code that works right away when copied into an html file.
I've downloaded d3, three, and other dependencies with npm and used loadScript to load the other scripts. I'm using Vite for tooling. Nothing appears when I load the component on a page. There are also no errors in the console.
Here is the Vue code that I have so far. Is this a solid approach? Is there a better way of integrating this object? I'm still very new to Vue and any help is appreciated.
Thank you.
<template>

</template>

A: I don't think you need to use loadscript to load d3 & THREEjs dependencies because the npm packages you are importing already includes those.
you also need to install topojson-client and import it as well.
npm i topojson-client

Below is the code working for me.
screenshot
Some notes of what I changed:

*

*When using composition api the

<template>

</template>

my package.json
  "dependencies": {
    "d3": "^7.4.4",
    "three": "^0.139.2",
    "topojson-client": "^3.1.0",
    "vue": "^3.2.25"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.3.1",
    "vite": "^2.9.2"
  }


text:
Q: too -- enough \ structure change
*

*It had been snowing too heavily for me to leave the house.

Use enough:

*It had been snowing heavily enough for me to stay indoors.

Why does the author change ( leave the house into stay indoors?
The Communicative Grammar of English Workbook - Page 14
I understand it ( too carries negative meaning \ enough carries positive meaning ) so I dislike the result or I hate it in ( 1) . It is so difficult for me to leave the house due to the much snow.
2-  Positive result ( The snow came down to such extent that I couldn't go out, so I would rather stay at home).
Could you please give me another interpretation ?

A: The first sentence is this:

It had been snowing too heavily for me to leave the house.

If you say:

It had been snowing too heavily for me to stay indoors.

That has the opposite meaning of what you intend to say. It means it was snowing so heavily that you could not remain indoors (you had to go outside).
So you need to substitute something for too heavily. That substitution is heavily enough in your example:

It had been snowing too heavily enough for me to stay indoors.

There are many other ways to express the same idea with very similar words, but if the only thing you can replace in the sentence is too heavily, and you can't make any other changes, then I suppose heavily enough is best.
IMHO, a better construct would be to use so heavily that and you wouldn't have to make any substitutions at all:

It had been snowing so heavily that I could not leave the house.
It had been snowing so heavily that I had to stay inside.


text:
Q: awstats indicates drop in pages after move to a new server I moved a web service to a new server. I figured out that, in the old server, the following gives approximately the same number of hits as awstats (e.g., for a given day the following gives 5537, whereas awstats indicates 5557 hits):
grep -v bot myaccess.log|     # file contains given vhost for given date range \
grep -v rss2email|\
grep -v Slurp|\
grep -v pider|                # Ignore spiders \
egrep 'HTTP/.... (200|304) '| # Catch only 200 and 304 responses \
grep -v Wget|\
grep -v Bot|\
grep -v rawler|               # Ignore crawlers \
grep -v favicon.ico|\
grep -v robots.txt|\
grep -v HTTrack|\
grep -v simplepie|\
grep -v BingPreview|\
wc -l

Adding the following to the end of the grep chain gives approximately the same number of pages (e.g. 2916 for a given day) as awstats (3042):
egrep -v '(css)|(js)|(class)|(gif)|(jpg)|(jpeg)|(png)|(bmp)|(ico)|(swf) HTTP'

Now, I moved server. Lots of things changed: apache became nginx; the log format changed; the awstats configuration has been rewritten; Debian squeeze became wheezy, and awstats 6.9.5 became 7.0.
The large pipeline above still approximates awstats's hits well (e.g. 5521 vs. 5541), but adding the egrep that excludes the NotPageList does not: I get, for a given day, 2948, whereas awstats gives 1580. (Whether the exclusion list contains rss and xml makes no significant difference.) Indeed, since the day the service was moved, the hits remain approximately the same, whereas the pages and the visits have approximately halved. I can't figure out why.

A: The main difference appears to be a new feature in awstats 7.0: downloads. It assumes that certain file extensions (pdf, zip, txt, mp3, doc, ppt, and more) are "downloads". Older awstats versions considered these to be "pages".
I also understand that each new version of awstats has a more complete filter-out list (e.g. a more complete bot list), resulting in each new version reporting fewer pages (overestimation always exists and is probably impossible to eliminate entirely); but this must have a smaller effect.


text:
Q: How to format date in a material UI textfield?                             <TextField
                              name="BalDueDate"
                              format="MM/dd/yyyy"
                              value={basicDetails.BalDueDate.slice(0,10)}
                              onChange={event => {
                                setBasicDetails({
                                  ...basicDetails,
                                  [event.target.name]: event.target.value,
                                });
                              }}
                              label="Bal. Due Date"
                              type="date"
                              variant="outlined"
                              className={classes.textField}
                              InputLabelProps={{
                                shrink: true,
                              }}
                            />

the default date format that i receive from this code of text field of material UI is : 'dd-mm-yyyy'.
But due to my requirements i want the format to be in the form of 'MM-dd-yyyy".
I have tried using material Ui date pickers but that breaks my current Ui and the whole designing outlook of the form, hence i cannot use date pickers instead.
Please provide me a solution of how to change the format of date WITHOUT USING DATE PICKER.

A: This should work :
import React from "react";
    import { makeStyles } from "@material-ui/core/styles";
    import TextField from "@material-ui/core/TextField";

    const useStyles = makeStyles(theme => ({
      root: {
        position: "relative"
      },
      display: {
        position: "absolute",
        top: 2,
        left: 0,
        bottom: 2,
        background: "white",
        pointerEvents: "none",
        right: 50,
        display: "flex",
        alignItems: "center"
      },
      input: {}
    }));

    function InputComponent({ defaultValue, inputRef, ...props }: any) {
      const classes = useStyles();
      const [value, setValue] = React.useState(() => props.value || defaultValue);

      const handleChange = event => {
        setValue(event.target.value);
        if (props.onChange) {
          props.onChange(event);
        }
      };

      return (

{value}

          <input
            className={classes.input}
            ref={inputRef}
            {...props}
            onChange={handleChange}
            value={value}
          />

      );
    }

    function DatePickers() {
      return (
        <TextField
          id="date"
          label="Birthday"
          type="date"
          InputProps={{
            inputComponent: InputComponent
          }}
          defaultValue="2017-05-24"
          InputLabelProps={{
            shrink: true
          }}
        />
      );
    }

    export default DatePickers;


text:
Q: What are the different ways to implement a button in Android java? I know these two:

*

*Button b = (Button) (findViewById(R.id.Button2));

*android:onClick=""
Are there any different ways?
I just tried Button b = new Button();
But it did not work in android!
Thank you!

A: 1.Button b = (Button) (findViewById(R.id.Button2));
This gives you object of the button defined in XML.
2.android:onClick=""
This method is for handling button click event, and not for creating button.
3.Default constructor is not available - new Button()
You need to pass context in the constructor.
Button delete = new Button(context);

A: You can add a button programmatically, try this:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

Then you can create a new Button for example and just add it:
Button btn = new Button(this);
btn.setText("MyButton");
btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(btn);

A: Try this way,hope this will help you to solve your problem.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <Button
        android:id="@+id/btnFromXml"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button From Xml"/>

    <LinearLayout
        android:id="@+id/lnrActivityButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">

        </LinearLayout>
</LinearLayout>

MyActivity.java
public class MyActivity extends Activity {

    private  Button btnFromXml;
    private LinearLayout lnrActivityButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnFromXml = (Button) findViewById(R.id.btnFromXml);
        lnrActivityButton = (LinearLayout) findViewById(R.id.lnrActivityButton);

        btnFromXml.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MyActivity.this,"XML Button Clicked",Toast.LENGTH_SHORT).show();
            }
        });

        Button btnFromActivty = new Button(this);
        btnFromActivty.setText("Button From Activity");
        btnFromActivty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MyActivity.this,"Activity Button Clicked",Toast.LENGTH_SHORT).show();
            }
        });

        lnrActivityButton.addView(btnFromActivty);
    }
}

A: You should use:
Programaticaly:
Button b=new Button(this);
yourView.addView(b);

By Xml(Using Layouts)
          <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
           />


text:
Q: How to insert username in VS2008(report edition) I'm creating a new report (*.rdl), and there I want to add username who runs the script (insert).
I've tried on VS2008 through "built-in-fields" function which is "User ID", but it didn't work:
CREATE TABLE #Some_Table
(
Plan_date date null,
Plan_customer int null,
creator_id nvarchar(55) null
)

INSERT INTO Some_Table
(

[Plan_date] ,
[Plan_customer],
[creator_id]

)
SELECT
@p_plan_monthly,
@p_plan_clients,
@creator_id ="user id" --from built-in-fields

Expected result is: Column creator_id is filling with value of username from active directory who made insert through my report.

A: Q: "and there I want to add username who runs the script (insert)"
You can use these functions.
-- database user name
SELECT USER_NAME()
-- login identification name
SELECT SUSER_NAME()

A: To reiterate my comment, as it's is incredibly important:
"You need to use a different account to access your data @whitefang. The sa account should never be used for something as mundane as a report. In truth it should never be used unless you really need sysadmin privileges, or you're doing something like recovering the server. You should have a service account that can do the respective tasks it needs to. If you can suffer injection through those reports, you're service is like an open book to whomever has access."
Now, onto your problem. I would add a further internal parameter on your report. Change the value of the parameter to have the default value of =User!UserID; this will be the ID of the user running the report (perhaps something like StackOverflow\Larnu).
Then map that report parameter to your dataset parameter @creator_id and change your INSERT statement to:
INSERT INTO Some_Table ([Plan_date],
                        [Plan_customer],
                        [creator_id])
VALUES (@p_plan_monthly, @p_plan_clients, @creator_id);


text:
Q: How to remove a little code redundancy Basically I have a code:
 $response = myFunction();

I need to repeat this call if there was an error like this:
do {
   $response = myFunction();

} while ( isset($response['error']) );

But I want to usleep(500); too if there was an error. I could do like this, but I don't find it so elegant:
do {
   $response = myFunction();

   if (isset($response['error']))
     usleep(500);

} while ( isset($response['error']) );

What Can i do? Maybe something like this (not very elegant neither)
while( isset($response['error']) && !usleep(500) );

Edit
There is another possibility... With the use of goto. But I am always reluctant to goto codes
retry:
$response = myFunction();
if (isset($response['error'])) {
  usleep(500);
  goto retry;
}

To me this seems the most clear and redundancy-free solution.   What do you think?

A: while (true) {
    $response = myFunction();

    if (isset($response['error'])) {
        usleep(500);
    } else {
        break;
    }
}

Having said that, trying to hammer a function until it returns the correct result may be a sign of a badly thought-out architecture and there may be a better solution for the whole problem to begin with.

A: Suggested solution to remove the redundancy where you check for isset twice. This is a bit cleaner.
do {
    $response = myFunction();
    if( $error = isset($response['error']) )
        usleep(500);
} while( $error );

A: You can simply define a function like this :
function isset_wait($var)
{
    if(isset($var))
    {
        usleep(500);
        return true;
    }
    return false;
}

then your code will be muche easrier to read :
do {
    $response = myFunction();
} while ( isset_wait($response['error']) );


text:
Q: tensorflow confusion matrix in Experimenter during evaluation I've got some troubles during the model evaluation using Tensorflow with the Experimenter API.
I used to work using 2-classes NN, but this time I manage to train a 4-classes one and I need to figure out how to build a confusion matrix in this case. I tried using the tf.confusion_matrix function, but it doesn't work at all.
This is the fragment of code that I used:
if mode == ModeKeys.EVAL:

    eval_metric_ops = {
        'accuracy' : metrics.streaming_accuracy(predictions=predicted_classes, labels=labels),

        # Other metrics...

        'confusion_matrix': tf.confusion_matrix(prediction=predicted_classes, label=labels, num_classes=4)
    }

    return tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=predicted_classes,
        loss=loss,
        eval_metric_ops=eval_metric_ops
    )

And this is the error that I got:
TypeError: Values of eval_metric_ops must be (metric_value, update_op) tuples, given: (<tf.Operation 'test/group_deps' type=NoOp>, <tf.Tensor 'test/accuracy/value:0' shape=() dtype=float32>, <tf.Variable 'test/confusion:0' shape=(4, 4) dtype=int32_ref>) for key: confusion_matrix

I read other answers about to create a confusion matrix in Tensorflow and I understood how to do it, but I think that my question is more related to the Estimator/Experimenter API.

A: your codes doesn't work because the framework expects eval_metric_ops to be a dictionary containing key with the name of the operation and values of type tuple (result tensor, update_operation for this tensor)
tf.confusion_matrix(prediction=predicted_classes, label=labels, num_classes=4) only returns the expected tensor.
You have to implement your own metric operation like this:

def eval_confusion_matrix(labels, predictions):
    with tf.variable_scope("eval_confusion_matrix"):
        con_matrix = tf.confusion_matrix(labels=labels, predictions=predictions, num_classes=4)

        con_matrix_sum = tf.Variable(tf.zeros(shape=(4,4), dtype=tf.int32),
                                            trainable=False,
                                            name="confusion_matrix_result",
                                            collections=[tf.GraphKeys.LOCAL_VARIABLES])

        update_op = tf.assign_add(con_matrix_sum, con_matrix)

        return tf.convert_to_tensor(con_matrix_sum), update_op

# Add evaluation metrics (for EVAL mode)
eval_metric_ops = {
    "accuracy": tf.metrics.accuracy(labels, predicted_classes),
    "conv_matrix": eval_confusion_matrix(
        labels, predicted_classes)
    }

A: Please use either tf.metrics.* or tf.contrib.metrics.* for metric calculation. There are subtle things to write a currect metric behavior.
There are some utilities in tf.contrib.metrics, such as streaming_true_positives which you may find useful.


text:
Q: Using The Extended Euclidean Algorithm : How can I compute $d$ using The Extended Euclidean Algorithm:
$$d e \equiv 1~\text{mod}~\varphi ( n ) $$
If the value of $e$ and  $\text{mod}~\varphi ( n )$ are known as
$d_7 \equiv 1~\text{mod}~8  $
I'll appreciate any help or explanation .


text:
Q: How to suppress stacktrace in Ruby exit?   trap 'TERM' do
    warn 'Exiting.'
    exit 1
  end

This prints a 10 line stacktrace.
How to suppress the stacktrace and exit silently?
Ruby 2.2.0

A: You can do it like this:
trap "TERM" do
  warn "Exiting."
  $stderr.reopen(IO::NULL)
  $stdout.reopen(IO::NULL)
  exit 1
end

A: If you hit Ctrl + C, the signal will be INT, not TERM. If you want to catch both, you can do something like this:
p = proc do
  warn 'Exiting.'
  exit 1
end
trap 'INT',p
trap 'TERM',p


text:
Q: Inserir imagens no banco de dados Bom tarde, inseri uma grande quantidade de informações em uma tabela em meu banco de dados por meio de um arquivo .csv usando a linha de comando LOAD DATA INFILE e também tenho uma tabela de relacionamento onde ficará registrado o ID do produto e  o caminho da(s) foto(s) desse produto, mas estou tentando escapar de ter que cadastrar as fotos manualmente, no caso, realizando um upload da(s) foto(s) por um form em minha área administrativa.
Sei que parece mágica mas existe alguma forma de fazer isso, relacionar o produto com imagens de uma pasta e guardar o caminho na tabela ou alguém já passou por uma situação assim?

A: Sim.
Coloque as fotos no seu computador preservando a estrutura de pastas e faça um robô (pode ser um php) que faça um full table scan (ou seja, um select all e um loop nesse resultado) procurando pela foto de cada produto. Se a foto for encontrada faça um update numa nova coluna (fotoencontrada), renomeie a foto para o id do produto e a mova para uma pasta comum.
Depois é só fazer o upload de todas as fotos através de um ftp.


text:
Q: "the ordinary sense of the word" meaning
Of course, the people in short stories are not real, in the ordinary sense of the word.

I want to know what does the phrase "ordinary sense of
the word" mean?
I find the meaning of single word in my dictionary.
But I can't suggest this phrase meaning?
I think it means "common understanding way".

A: It means the dictionary definition, the common meaning of the word, as opposed to a specialized technical meaning or a poetic or not-literal meaning.
I saw an example not long ago where a writer wanted to praise people who work hard, take care of their families, are honest, and so on. So he said, "Mr Miller is not a hero in the ordinary sense of the word. But he is a hero in his community" etc. That is, he's not a hero in the normal sense of braving fighting the enemy in war or some such. But he's a hero because people like him make society work.
In this case, I can't say for sure without reading the context. But obviously a character in a story is not literally a real person. They're not real "in the ordinary sense of the word". I'd guess the writer goes on to say that they can be "real" in the sense that they can behave like real people behave, or that they can seam real to the reader.


text:
Q: In R, how can I count specific words in a corpus? I need to count the frequency of particular words. Lots of words. I know how to do this by putting all words in one group (see below), but I would like to get the count for each specific word.
This is what I have at the moment:
library(quanteda)
#function to count
strcount <- function(x, pattern, split){unlist(lapply(strsplit(x, split),function(z) na.omit(length(grep(pattern, z)))))}
txt <- "Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents."
df<-data.frame(txt)
mydict<-dictionary(list(all_terms=c("clouds","storms")))
corp <- corpus(df, text_field = 'txt')
#count terms and save output to "overview"
overview<-dfm(corp,dictionary = mydict)
overview<-convert(overview, to ='data.frame')

As you can see, the counts for "clouds" and "storms" are in the "all_terms" category in the resulting data.frame. Is there an easy way to get the count for all terms in "mydict" in individual columns, without writing the code for each individual term?
E.g.
clouds, storms
1, 1

Rather than
all_terms
2

A: You want to use the dictionary values as a pattern in tokens_select(), rather than using them in a lookup function, which is what dfm(x, dictionary = ...) does.  Here's how:
library("quanteda")
## Package version: 2.1.2

txt <- "Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents."

mydict <- dictionary(list(all_terms = c("clouds", "storms")))

This creates the dfm where each column is the term, not the dictionary key:
dfmat <- tokens(txt) %>%
  tokens_select(mydict) %>%
  dfm()

dfmat
## Document-feature matrix of: 1 document, 2 features (0.0% sparse).
##        features
## docs    clouds storms
##   text1      1      1

You can turn this into a data.frame of counts in two ways:
convert(dfmat, to = "data.frame")
##   doc_id clouds storms
## 1  text1      1      1

textstat_frequency(dfmat)
##   feature frequency rank docfreq group
## 1  clouds         1    1       1   all
## 2  storms         1    1       1   all

And while a dictionary is a valid input for a pattern (see ?pattern), you could also have just fed the character vector of values to tokens_select():
# no need for dictionary
tokens(txt) %>%
  tokens_select(c("clouds", "storms")) %>%
  dfm()
## Document-feature matrix of: 1 document, 2 features (0.0% sparse).
##        features
## docs    clouds storms
##   text1      1      1

A: You can use the unnest_tokens() function from tidytext in combination with pivot_wider() from tidyr to get the count for each word in separate columns:
library(dplyr)
library(tidytext)
library(tidyr)

txt <- "Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents."

mydict <- c("clouds","storms")

df <- data.frame(text = txt) %>%
  unnest_tokens(word, text) %>%
  count(word) %>%
  pivot_wider(names_from = word, values_from = n)

df %>% select(mydict)

# A tibble: 1 x 2
  clouds storms
   <int>  <int>
1      1      1


text:
Q: Strange behavior for Map, parseInt
Possible Duplicate:
javascript - Array.map and parseInt

I saw this example of strange JavaScript behavior on twitter
['10','10','10','10','10'].map(parseInt)

evaluates to
[10, NaN, 2, 3, 4]

could somebody explain this behavior?  I verified it in chrome and firebug
['10','10','10','10','10'].map(function(x){return parseInt(x);})

correctly returns an array of 10s as integers.  Is this an improper use of map(), a bug with parseInt, or something else?

A: From MDN:

callback is invoked with three arguments: the value of the element,
  the index of the element, and the Array object being traversed.

parseInt() takes two arguments. The value and the radix. That means that the parseInt() function is being called with unintended parameters.

A: parseInt uses the first two arguments being passed in by map, and uses the second argument to specify the radix.
Here's what's happening in your code:
parseInt('10', 0) // 10
parseInt('10', 1) // NaN
parseInt('10', 2) // 2
parseInt('10', 3) // 3
parseInt('10', 4) // 4

Here's a link to MDN on parseInt: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt.

A: parseInt receives two arguments: string and radix:

var intValue = parseInt(string[, radix]);

while map handler's second argument is index:

... callback is invoked with three arguments: the value of the element,
  the index of the element, and the Array object being traversed.


text:
Q: How do I add a user-agent to this Python opener?
Possible Duplicate:
How do I add a header to urllib2 opener?

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

How do i add a user agent header to this?

A: Not a direct answer - as Mateusz is correct for your direct question, but I strongly suggest if you're going to be doing a lot of this you consider the requests library at http://docs.python-requests.org/en/latest/index.html
That way it's as simple as:
import requests

r = requests.get('http://whatever.com/', headers={'User-Agent': 'xxxx'})

You also get cookies handled for you, basic auth is easier, and it's easy to plug-in OAuth bits - check out the docs, you may find it useful.

A: request = urllib2.Request(your_webpage)
request.add_header('User-Agent', your_user-agent)
data = opener.open(request).read()


text:
Q: Prevent default doesn't work when dom reload I have the following snippet

$( "#diner_option" ).click(function( event ) {
  event.preventDefault();
  console.log('ok')
});

 $( "#change" ).click(function( event ) {
    var add_html = "

salade tiede de courgettes

"
    $("#diner_div").replaceWith(add_html)
    console.log('changed');
});
.recipe_option{
        position: absolute;
        padding: 15px;
        top: 0;
        right: 0;
        background: #353b43;
        border-bottom-left-radius: 10px;
    }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

<button id="change">Change</button>

salade tiede de courgettes

When I click on cog icon, I get in the console the message ok which means it worked as intended. But when I click on the change button to refresh the dom and click on the cog, the event.preventDefault(); function doesn't work. The cog works like a link then.
I would like to be able to reload the dom and the cog icon still work (which means, shows the ok message)

A: You have to rebind your click event to the new element that replaces your old cog. Call your jquery bind again.

$( "#diner_option" ).click(function( event ) {
  event.preventDefault();
  console.log('ok')
});

 $( "#change" ).click(function( event ) {
    var add_html = "

salade tiede de courgettes

"
    $("#diner_div").replaceWith(add_html);

    $( "#diner_option" ).click(function( event ) {
      event.preventDefault();
      console.log('ok')
    });
    console.log('changed');
});
.recipe_option{
        position: absolute;
        padding: 15px;
        top: 0;
        right: 0;
        background: #353b43;
        border-bottom-left-radius: 10px;
    }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

<button id="change">Change</button>

salade tiede de courgettes


text:
Q: How to change background color in Django Admin Dashboard Please tell me how to change background color in django admin dashboard. And maybe all.

A: This is a step by step blog which guides you in changing the background color of the admin panel.
DJANGO ADMIN PANEL BG Color change blog
below is the official documentation regarding the admin site and the customization options
DJANGO ADMIN DOCUMENTATION


text:
Q: Problems with ScreenManager and Screen in Python (kivy). I want to call on def in Screen from the Screenmanager class I am trying to call on def in class Screen from Screenmanager from the class Screenmanager but I can't.
I want to make a box layout and put a button in that boxlayout when the app is started as soon as ScreenManager is called so it is the default screen.
I want to do this so I can switch between multiple screens using the self.parent.current = 'Screen Name' on the press of a button
Here is the code
class Manager(ScreenManager):
    def __init__(self):
        self.add_widget(Scr1().make_button())
class Scr1(Screen):
    def __init__(self):
        self.layout = BoxLayout(orientation = 'vertical')
        self.button = Button(text='hello')
        self.layout.add_widget(self.button)
    def make_button(self, layout):
        return self.layout

class MainApp(App):
    def build(self):
        sm =Manager()
        s1 = Scr1()
        sm.add_widget=s1
        return sm

if __name__ == "__main__":
    MainApp().run()

Here is the error I get

 Traceback (most recent call last):
   File "C:/Users/user/Desktop/CarsonMusic/Learn.py", line 43, in <module>
     MainApp().run()
   File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\app.py", line 829, in run
     root = self.build()
   File "C:/Users/user/Desktop/CarsonMusic/Learn.py", line 37, in build
     sm =Manager()
   File "C:/Users/user/Desktop/CarsonMusic/Learn.py", line 24, in __init__
     self.add_widget(Scr1().make_button())
   File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\uix\screenmanager.py", line 979, in add_widget
     'ScreenManager accepts only Screen widget.')
 kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget.

I know I am probably making a dumb mistake but can someone help me?

A: I solved it! I had to delete the Manager(ScreenManager) class, added the 'super', and then I added the layout widget to self
Here is my new code:
class Scr1(Screen):
    def __init__(self, **kwargs):
        super (Scr1, self).__init__(**kwargs)

        self.layout = BoxLayout(orientation='vertical')
        self.button = Button(text='hello')
        self.button.bind(on_press=self.screen2)
        self.layout.add_widget(self.button)
        self.add_widget(self.layout)

    def screen2(self, *args):
        self.manager.current = 'screen2'

class Scr2(Screen):

    def __init__(self, **kwargs):
        super (Scr2,self).__init__(**kwargs)

        self.layout2 = BoxLayout(orientation='vertical')
        self.add_widget(self.layout2)
        self.button2 = Button(text='hello2')
        self.button2.bind(on_press=self.screen1)
        self.layout2.add_widget(self.button2)
    def screen1(self, *args):
        self.manager.current = 'screen1'

class MainApp(App):
    def build(self):
        sm= ScreenManager()
        screen1 = Scr1(name='screen1')
        screen2= Scr2(name='screen2')
        sm.add_widget(screen1)
        sm.add_widget(screen2)
        return sm

if __name__ == "__main__":
    MainApp().run()


text:
Q: How to prevent user conflict in WSL + Docker + VS Code setup I have WSL + Docker + VS Code setup. The files I'm working on are in WSL filesystem and mounted to a Docker container.
To run the files in Docker container, it requires user www-data but I can't save the files and do git operation in my VS Code because they're in my WSL filesystem and it requires my WSL local user to save the files/run git operation.
So I have to sudo chown back and forth just to make sure I can run the files in Docker container and save the files/do git operation in my WSL filesystem.
Is there a way to make files work in WSL and Docker container without having to sudo chown back and forth?

A: I've found the solution by following this answer: https://stackoverflow.com/a/56904335/2927317.
We need to set the user and group ID for docker service to match user and group ID in the host by adding the definition user: USERID:GROUPID in docker compose file.


text:
Q: Use interface or type for variable definition in java? ArrayList aList = new ArrayList();

List aList = new ArrayList();

What's the difference between these two and which is better to use and why?

A: Both are deprecated since Java 1.5.
It should be:
List<String> list = new ArrayList<String>();
// or whatever data type you are using in your list

Please read Effective Java by Joshua Bloch, especially these two items:

*

*23: Don't use raw types in new code (this is even available online)

*52: Refer to objects by their
interfaces

BTW, if you use Guava, you have a factory method for constructing an ArrayList so you don't have to repeat the type parameter:
List<String> list = Lists.newArraylist();

A: List<T> is interface, where ArrayList<T> is class, and this class implements List<T> interface.
I would prefer 2nd form, which is more general, ie if you do not use methods specific to ArrayList<T> you can declare its type as interface List<T> type. With 2nd form it will be easier to change  implementation from ArrayList<T> to other class that implements List<T> interface.
EDIT:
As many of SO users commented both forms can be arguments to any method that accept List<T> or ArrrayList<T>. But when I declare method I would prefer interface:
 void showAll(List <String> sl) ...

and use:
 void showAllAS(ArrayList <String> sl) ...

only when my method uses method specific to ArrayList<T>, like ensureCapacity().
Response with information that we should use typed List<T> instead of just List is very good (of course if we do not use ancient Java).

A: List is an Interface, whereas ArrayList is an implementation of that interface.
The second is better because it means you can change your ArrayList for another implementation of List later without needing to change the rest of your application. You may want to do this for performance reasons, or because of other aspects of the behaviour of the List implementation that you have chosen/will choose.

A: All these answers are the same recite from some dogma they read somewhere.
A variable declaration and initialization statement, Type x = new Constructor();, is definitely part of implementation detail. It's not part of a public API (unless it's public final, but List is mutable so that's inappropriate)
As an implementation detail, who you are trying to fool with your abstractions? It's better to keep the type as specific as possible. Is it an array list or a linked list? Should it be thread safe or not? The choice is important for your implementation, you carefully chose the specific list impl. Then you declare it as a mere List as if it doesn't matter and you don't care?
The only legitimate reason to declare it as List is I'm too lazy to type. That also covers the argument that if I need to move to another List impl I have one less place to modify.
This reason is legitimate only when the variable scope is small, and you can see all of its usages from one glance. Otherwise, keep the most specific type, so that its performance and semantic characteristics are manifest across all the code that use the variable.

A: I prefer the second in most cases because it signifies that you're not using anything specific in the ArrayList api, and if you need to later you can substitute any other type of List without having to change any code except the first line.

A: This is a Java quirk, due to limited type inference and doctrine OOP. For local variables it's mostly style; if you need some specific feature of the subtype, use the subtype (examples below), but otherwise fine to use either.
Java style is to use the supertype, to enforce interfaces even within the body of implementations, and for consistency with visible types (Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces). In languages with more type inference, such as C++/C#/Go/etc., you don't need to explicitly state the type, and the local variable will have the specific type.
For visible types (public or protected: fields, or parameters and return value of methods), you almost always want to use the most general type: interface or abstract class, to provide better flexibility (Effective Java: Item 40: Design method signatures carefully). However, for types that are not visible (private or package-private members, or local variables), it's ok to use either (it's just style) and sometimes necessary to use more specific types, including concrete classes.
See Effective Java for standard guidelines; personal thoughts follow.
The reason to use more general types even if not visible is to reduce noise: you're stating that you only need the more general type. Using general types on members that are not visible (like private methods) also reduces churn if you ever change types. However, this doesn't apply to local variables, where it's just changing one line anyway: ConcreteFoo foo = new ConcreteFoo(); to OtherConcreteFoo foo = new OtherConcreteFoo();.
Cases where you do need the subtype include:

*

*You need members only present on the subtype, e.g.:

*

*some feature of the implementation, like ensureCapacity for ArrayList<T>

*(common in test code)  some member of a fake class, like (hypothetically) FakeFileSystem#createFakeFile.

*You rely on the behavior of the subtype, notably in overrides of the supertype's methods, like:

*

*having a more general type of parameter,

*more specific return type, or

*throwing a more specific or fewer exception types.

As an example of the last, see Should I close a StringReader?: StringReader.html#close overrides Reader.html#close and does not throw an IOException, so using StringReader instead of Reader for the local variable means you don't need to handle an exception that can't actually occur, and significantly reduces boilerplate.

A: If you are using Java 1.4 or earlier, then I would use the second one. It's always better to declare your fields as generically as possible, in case you need to make it into something else later on, like a Vector, etc.
Since 1.5 I would go with the following
List<String> x = new ArrayList<String>();

It gives you a little bit of type safety. List 'x' can add a String Object, and that's it. When you get an item from the List 'x', you can count on the fact that a String is going to come back. This also helps by removing unnecessary casting, which can make code hard to read when you go back 6 months later and try to remember what your code does. Your compiler/IDE will help you to remember what type should be going in to List 'x' by displaying an error if you try to add any other Object type.
If you want to add multiple Object types to a List then you could add an Annotation to suppress the compile error
@SuppressWarnings("unchecked")
List y = new ArrayList();

A: I know of at least one case when declaring a variable with an interface does not work.  When you want to use reflection.
I made a bug fix on some code where I declared a variable as Map<String, MyObject> and assigned it an instance of HashMap<String, MyObject>.  This variable was used as a parameter in a method call that was accessed via reflection.  The problem is that reflection tried to find a method with HashMap signature and not the declared Map signature.  Since there was no method with a HashMap as a parameter I was unable to find a method by reflection.
Map<String, Object> map = new HashMap<String, Object>();

public void test(Map<String, Object> m) {...};

Method m = this.getClass().getMethod("test", new Class<?>[]{map.getClass()});

Will not find the method that uses the interface.  If you make another version of test that uses HashMap instead then it will work - but now you are forced to declare your variable with a concrete class and not the more flexible interface...


text:
Q: Marketing Cloud Connect: Cannot proceed when trying to 'Start Wizard' Follow step by step on this trailhead module.
I am stuck on this part where it instructs us to :
'10. Click Start Wizard to begin the setup wizard.'
The error message I got is as below :

Remote Site Setting Missing
  Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session faultcode=sf:INVALID_SESSION_ID faultactor=

As shown in this screenshot :

Any ideas how to resolve issue?

A: Session ID usually refers to the login session, so I would (1) Ensure that the integrations users are setup correctly and all the steps leading up to "Connecting the clouds" are completed from the guide.
Then, log out of everything - both MC and Core.
Then, with API user credentials, log into MC and log into Core.
Try again - this should resolve it.
In case it doesn't, you can try to manually verify the remote site:
https://help.salesforce.com/articleView?id=mc_co_advanced_faqs.htm&type=5


text:
Q: Formik handleReset is going through validation I'm trying to add a Reset button on my Formik form. Trouble is, when I click the Reset button Formik shows me the validation errors. Only after I click the Reset button a second time does the form actually reset. Why should the user go through form validation if all they want is to reset the form, right? Here's my form component:
const ContactForm = () => {

  const submit = async (values, { setSubmitting, resetForm }) => {
    ... submit logic ...
  }

  return (
        <Formik
          initialValues={{
            name: '',
            email: '',
            message: '',
          }}
          validationSchema={Yup.object({
            name: Yup.string()
              .min(3, 'Tamanho mínimo: 3 caracteres')
              .max(20, 'Tamanho máximo: 20 caracteres')
              .required('Campo obrigatório.'),
            ...more fields ...
          })}
          onSubmit={submit}
        >
          {({ isValid, isSubmitting, handleReset }) => (
            <Form>
              <div className="mb-3">
                <label htmlFor="name" className="form-label">
                  Nome
                </label>
                <Field
                  name="name"
                  type="text"
                  className="form-control"
                  aria-describedby="nameHelp"
                />
                <ErrorMessage
                  component="div"
                  id="nameHelp"
                  name="name"
                  className="form-text text-warning"
                />
              </div>
              ... more fields ...
              <button
                type="submit"
                disabled={isSubmitting || !isValid}
                className="btn btn-primary shadow me-3"
              >
                Enviar
              </button>
              <button
                disabled={isSubmitting}
                className="btn btn-outline-primary shadow"
                onClick={handleReset}
              >
                Apagar
              </button>
            </Form>
          )}
        </Formik>
  )
}

export default ContactForm

I must be doing something wrong. How can I reset the form without going through the validation process?

A: I think you should update your reset button as follows -
<button type="reset"  onClick={ e => formik.resetForm()}> Reset</button>


text:
Q: How facebook shows a share block based on a url? When I am sharing a link in FB, it somehow grabs some key information from that link and builds a sharing block containing images, name, title and the summary of that page.
How do they do that??
Do they go to the page of that link and parse every divs of that page to grad those information???

A:
How do they do that??

Facebook uses a protocol called Open Graph Protocol

Do they go to the page of that link and parse every divs of that page to grad those information???

No, Facebook scrapes your page's OG <meta /> tags from <head> tags and extract the data from them
to install them, you can follow the full documentation at OGP site
basic example
<html prefix="og: http://ogp.me/ns#">
<head>
<title>My awesome article - site</title>
<meta property="og:title" content="My awesome article - site" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://www.site.com/my-awesome-article" />
<meta property="og:image" content="http://www.site.com/images/my-awesome-article.jpg" />
...
</head>
...
</html>


text:
Q: How can I insert conditional statement inside the list? I have a list lst and I want to split its elements if they are numbers. So the  format of my lst is like:
lst=["1,2,3"," , , ","4,5,6"]

And I have an expression like below but I want to do int(i) if there is a number not a blank. How can I achieve this? Thanks in advance.
[[int(i) for i in c.split(',')] for c in lst]

What I need is:
[1, 2, 3, " ", " ", " ", 4, 5, 6]

A: The got-to-do-everything-with-list-comprehensions way:
lst=["1,2,3", " , , ", "4,5,6"]

res = [int(x) if x!=' ' else x for y in lst for x in y.split(',')]
print(res)  # [1, 2, 3, ' ', ' ', ' ', 4, 5, 6]

The old-school, for-loop way:
lst=["1,2,3", " , , ", "4,5,6"]

res = []
for item in lst:
  if item[0].isdigit():
    res.extend(map(int, item.split(',')))
  else:
    res.extend(item.split(','))
print(res)  # [1, 2, 3, ' ', ' ', ' ', 4, 5, 6]

I would go with the second one for its clarity. One can immediately tell what it does upon looking at it. That being said, and you having edited your requirements, the first one does not look so convoluted after all.

A: You can use str.replace(",", "").strip() in the if condition to check if it is a valid element. And you can also use list.extend to create your output.
Ex:
lst=["1,2,3"," , , ","4,5,6"]

res = []
for i in lst:
    if i.replace(",", "").strip():
        res.extend(map(int, i.split(",")))
    else:
        res.extend([""]*(i.count(",")+1))
print(res)

Output:
[1, 2, 3, '', '', '', 4, 5, 6]

A: lst=["1,2,3"," , , ","4,5,6"]
list2=[]

for c in lst:
    i=c.split(',')
    if c[0].isdigit():
        list2.extend(map(int,i))
    else:
        list2.extend(i)

print(list2)

This will give the output in the way you wanted.you can try it and see the result


text:
Q: React on click on button calling only once and next click it is not updating Hello I am newly started learning react.I have a text field and button. And On click on button I am displaying some results(using other functional component for results) by calling graphql. but here the issue I am facing is button is only working once after that I cannot call graphql api again on clicking on button. I suspect some issue with showResults boolean variable only(which I am setting on click on button). could some one help me to identify issue.

    const [consumption, setConsumption] = React.useState(1500);
    const [showResults, setShowResults] = useState(false);
    const displayProducts = () => {
        setShowResults(true);
    };
    const handleConsumptionChange = (event) => {
        let consumptionEntered = event.target.value;
        setConsumption(consumptionEntered);

    };
    return (

            <TextField
                label="Kwh"
                size="medium"
                value={consumption}
                onChange={handleConsumptionChange}
                variant="outlined"
            />

            <Button variant="contained" size="medium"
                    onClick={displayProducts}>Tarif finden</Button>

            {showResults && <ProductResults/>}

    );
};
export default SimpleForm;

     ' And my results display functional component code is below'

const ProductResults = (props) => {
    let bookId = props.bookId;
    const GET_BOOK = gql`
        {
            bookById(id: "book-1") {
                id
                name
                pageCount
                author{
                    id
                    firstName
                    lastName
                }
            }
        }

    `;
    console.log("props set is ::{}", props.bookId);
    const {loading, error, data} = useQuery(GET_BOOK);
    if (loading) return
Loading...
;
    if (error) return
Error :(
;
    return (

{data.bookById.id}

{data.bookById.name}

{data.bookById.pageCount}

author details

Author Id: {data.bookById.author.id}

First Name: {data.bookById.author.firstName}

Last Name: {data.bookById.author.lastName}

    );
};

export default ProductResults```

A: It probably is calling every time you click the button, but the button click just calls displayProducts which sets setShowResults(true).
You can either use setShowResults(previous => !previous) to turn it into a toggle, or you need to add a seperate "refresh" button/functionality to the ProductResults component.

A: Once the state is set to 'true', it is always setting to true. So I guess there is no state change and no update. try setShowResults(false) after setConsumption


text:
Q: ClassNotFoundException on ServletContainer when configuring Jersey in Intellij When trying to configure jax rs in intellij I get this error:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1945)

My webconfig looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>Rest</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.umbrella.server.api</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Rest</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
</web-app>

I manually downloaded the entire jersey pack from the official jersey website. Which should contain all the dependencies.
The weird thing is that whenever I create a class that derives from the ServletContainer it doesn't give any errors.

A: I found the anwser with the help of Eugen Covaci.
In the Intellij project settings there is a tab called problems. When clicking solve on the problems listed there it started working again.
Another issue was that the jar files were located in web/WEB_INF/libs/api instead of the correct folder (web/WEB_INF/lib)


text:
Q: Decode HTML string How can I decode my html string from:
Björn

to
Björn

in Swift 3 ?

A: Do you really need to preserve the  tags, while replacing the ö symbol? One technique, suggested by Leo Dabus in Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift, converts the symbols includes round-tripping it through an attributed string.
In Swift 4:
extension String {
    /// Converts HTML string to a `NSAttributedString`

    var htmlAttributedString: NSAttributedString? {
        return try? NSAttributedString(data: Data(utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
    }
}

If you want an attributed string (for example, for use in a UILabel)
let string = "Björn is great name"
label.attributedText = string.htmlAttributedString

This converts Björn to Björn and italicizes the ... portion, too.
If you just want to convert the HTML symbols and strip out the HTML tags (such as your /), just grab the string:
let string = "Björn is great name"
if let result = string.htmlAttributedString?.string {
    print(result)   // "Björn is great name"
}

For prior Swift versions, see previous revision of this answer.


text:
Q: Return multiple values from one class to another I need to return several boolean values from one class to another, here's the class that's creating the value :
public class Units {

    public static boolean unit1A;

    public static void mainPanel(final JFrame mainMenuFrame){

            unit1A = true;

        }
    }

And the class that I want to return the value to
public class UnitsTesting{

    public static void main(String[] args) {

        System.out.println(Units.unit1A);
    }

}

Unfortunately because of my poor project design i'm keeping the final JFrame in to switch out my frames when needed, so that needs to stay in, otherwise I would know how to do this.
Edit : For anyone interested looking at this i'm just going to return an array of booleans, as suggested by Ashis Kumar Sahoo.


text:
Q: Make dependant inputs in the 'State' -> 'City' -> 'Municipality' way in Laravel 5.7 I'm trying to make a form that contains 3 inputs. The first one should let the user select a state. Now, based on that selection (selection of input 1), the second input should load data from a DB table that has a relationship with the selected state, and the third input doing the same but in relation of the second input selection.
I have no idea how to do it, though I've tried this way:
My view: (it's all wrong here, I guess the magic happens on the controller).

                        {{-- Estados --}}
                        Estado
                        <select name="direccion" id="forma-estado" class="form-control dynamic" data-dependant="state">
                            @foreach ($estados as $estado)
                            <option value="{{ $estado->state }}">{{ $estado->state }}</option>
                            @endforeach
                        </select>

                        {{-- Municipio/Delegación --}}
                        Ciudad
                        <select name="direccion" id="form-ciudad" class="form-control dynamic" data-dependant="city">
                            @foreach ($estados as $estado)
                            <option value="{{ $estado->state }}">{{ $estado->state }}</option>
                            @endforeach
                        </select>

                        {{-- Colonia --}}
                        Municipio
                        <select name="direccion" id="form-municipio" class="form-control dynamic" data-dependant="municipality">
                            <option value="">Selecciona el municipio</option>
                        </select>

My controller:
public function fetch(Request $request)
{
    $state_id = DB::connection('db_postalcodes')->table('city')->get();
    $select = $request->get('select');
    $value = $request->get('value');
    $dependent = $request->get('dependent');
    $data = DB::connection('db_postalcodes')
        ->table('city')
        ->where($select, $state_id->state_id)
        ->groupBy($dependent)
        ->get();

    $output = '<option value="">Select ' . ucfirst($dependent) . '</option>';

    foreach ($data as $row) {
        $output .= '<option value="' . $row->$dependent . '">' . $row->$dependent . '</option>';
    }

    echo $output;
}

Also, I've got multiple tables with the data stored. So I guess I need to use some relationship functions in Laravel (but I don't know).


text:
Q: Fourier series of $f(x) = |x|^3$ and evaluating series I found the Fourier serie for the function $$f: [-\pi, \pi], \quad f(x) = |x|^3$$
Coefficents:
$$
a_0 = \frac{\pi^3}{2}
$$
$$
a_n = \frac{6 \pi}{n^2} \cos(n\pi) - \frac{12}{n^4\pi} \cos(n\pi) + \frac{6}{n^4}
$$
$$
b_n = 0
$$
So, the Fourier serie is given by
$$
f(x) = \frac{a_0}{2} + \sum_{n = 1}^{+\infty} a_n \cos(nx)
$$
$$
f(x) = \frac{\pi^3}{4} + \sum_{n = 1}^{+\infty}\left( \frac{6 \pi}{n^2} (-1)^n - \frac{12}{n^4\pi} (-1)^n + \frac{6}{n^4} \right) \cos(nx)
$$
Now, I should evaluate the following serie:
$$
\sum_{n = 1}^{+\infty} \frac{1}{n^4}(\pi^2 n^2 (-1)^n - 2 (-1)^n + 2)
$$
How can I find it with the help of this Fourier series?

A: I think the fourier coefficients are
$$n\neq1,\;\;a_n=\frac{6(2-n^2\pi^2)}{\pi n^4}(-1)^n-\frac{12}{\pi n^4}$$
So when we susntitute $\;x=0\;$ , we get (Dirichlet's convergence theorem)
$$0=\frac{\pi^3}4+6\sum_{n=1}^\infty\left(\frac{(2-n^2\pi^2)}{\pi n^4}(-1)^n-\frac{2}{\pi n^4}\right)\implies-\frac{\pi^3}{24}=\sum_{n=1}^\infty\left(\frac{(2-n^2\pi^2)}{\pi n^4}(-1)^n-\frac{2}{\pi n^4}\right)\implies$$
$$-\frac{\pi^4}{24}=\sum_{n=1}^\infty\left(\frac{(2-n^2\pi^2)}{ n^4}(-1)^n-\frac{2}{ n^4}\right)$$
and there you have your sum...(of course, I assume you know the sum of $\;\sum\limits_{n=1}^\infty\frac1{n^4}\;$ ...)