text:
Q: How to exit code if nothing is entered? Code example: Check if string is a palindrome or not? (in C Programming Language) QUESTION: How to exit code if nothing is entered into STDIN (console)?
For example:
*Input
"NULL - NOTHING - ZERO" :)
Expected Output
(Close program quit loop)*

Input:
Hello
Output:
Hello is not a palindrome

Input:
otto
Output:
otto is a palindrome

Code Explanation:
A palindrome is a string phrase that reads the same backwards as well as forwards. Examples of palindromes are "ABCDCBA", "otto", "i am ma i", "C". Write a program that reads in a line of text, and prints out whether or not that line of text is a palindrome.
#include <stdio.h>
#include <string.h>

#define MAXLEN 100

void reverseString(char *str, char *reversedStr)
{
    int i;

    for (i=strlen(str)-1; i>=0; i--)
    {
        *reversedStr++ = *(str+i);
    }
    *reversedStr = '\0';
}

int main(int argc, char **argv) {
    char str[MAXLEN];
    char reversedStr[MAXLEN];

    while (fgets(str, sizeof(str)-1, stdin) != NULL)
    {
        str[strlen(str)-1] = '\0'; // the last character is the newline. Replace with null
        reverseString(str, reversedStr);
        if (strcmp(str, reversedStr) == 0)
            printf("%s is a palindrome\n", str);
        else {
            printf("%s is not a palindrome\n", str);
        }
    }

    return 0;
}

Code Snippet:
https://onlinegdb.com/ByGKe8LnE

A: Your code works. Just press ctrl-d right after enter (signals end of input) to exit.
Couple of other things:

*

*fgets() doesn't need size minus 1. per the manual: "fgets() reads in at most one less than size characters..."

*there is really no need to copy/reverse the entire string and compare, half will suffice, OR you could simply compare beginning with end until center, without copying.

*strlen() "walks" the string - you can reuse the result of it instead of calling again.

.
#include <stdio.h>
#include <string.h>

#define MAXLEN 100

int isPalindrome(char *str, size_t len) {
    char *end = str + len - 1;
    while (end > str)
        if (*end-- != *str++) return 0;
    return 1;
}

int main(int argc, char **argv) {
    char str[MAXLEN];
    while (fgets(str, sizeof(str), stdin) != NULL) {
        size_t len = strlen(str) - 1;
        str[len] = 0; // the last character is the newline. Replace with null char
        printf("%s is %sa palindrome\n", str, isPalindrome(str, len) ? "" : "not ");
    }
    return 0;
}


text:
Q: Listing available queues in ActiveMQ Apache.NMS in C#.net Is there a way to list out all the active queues in ActiveMQ. I am using Apache.NMS for communicating with ActiveMQ from C#.
I am not seeing any direct methods in the library.

A: Please try this.
public void Test(ISession Session)
{
    String QUEUE_ADVISORY_DESTINATION = "ActiveMQ.Advisory.Queue";
    IDestination dest = Session.GetTopic(QUEUE_ADVISORY_DESTINATION);

    using (IMessageConsumer consumer = Session.CreateConsumer(dest))
    {
        IMessage advisory;

        while ((advisory = consumer.Receive()) != null)
        {
            ActiveMQMessage amqMsg = advisory as ActiveMQMessage;

            if (amqMsg.DataStructure != null)
            {
                DestinationInfo info = amqMsg.DataStructure as DestinationInfo;
                if (info != null)
                {
                    Console.WriteLine("   Queue: " + info.Destination.ToString());
                }
            }
        }
    }
    Console.WriteLine("Listing Complete.");
}

This is not a guaranteed way of listing queues. Please see this answer.

A: Solution above contains one defect. If you will try to get message like this:
consumer.Receive()

you will wait infinitely long time while new event won't be occurred with queues information into ActiveMQ.
I recommend to set timeout:
consumer.Receive(TimeSpan.FromMilliseconds(2000))

and see example offitial site

redpajama_set_name: RedPajamaStackExchange


text:
Q: Render child component to get its html in vue-test-utils I have one Parent Component called SuggestiveInput and it has Child Component called VueSimpleSuggest. I am getting stub of child component on the test instead of its content.
So SuggestiveInput component is like:
<template >

    <vue-simple-suggest ...>
    </vue-simple-suggest>

</template>


text:
Q: Effective Density of States for 2D Effective Mass Tensor I have derived an effective mass tensor for conduction and valence electrons in a tight binding model. Specifically, for electrons in the conduction band:
$$\begin{bmatrix}
\hbar^2\left( \frac{\partial^2 E_c}{\partial k_x^2} \right )^{-1} & 0\\
0 & \hbar^2\left( \frac{\partial^2 E_c}{\partial k_y^2} \right )^{-1}
\end{bmatrix}=\begin{bmatrix}
\frac{\hbar^2}{2a^2\cos(k_x a)} & 0\\
0 & \frac{\hbar^2}{2a^2\cos(k_y a)}
\end{bmatrix}.$$
And for valence holes
$$\begin{bmatrix}
\hbar^2\left( \frac{\partial^2 E_v}{\partial k_x^2} \right )^{-1} & 0\\
0 & \hbar^2\left( \frac{\partial^2 E_v}{\partial k_y^2} \right )^{-1}
\end{bmatrix}=\begin{bmatrix}
-\frac{\hbar^2}{a^2\cos(k_x a)} & 0\\
0 & -\frac{\hbar^2}{a^2\cos(k_y a)}
\end{bmatrix}.$$
Now I know that in one dimension, the effective DOS is given by
\begin{align*}
g_C(E)&=\frac{1}{2\pi^2}\left ( \frac{2m_e^*}{\hbar^2}\right )^{3/2}(E-E_c)^{1/2} \\
g_V(E)&=\frac{1}{2\pi^2}\left ( \frac{2m_h^*}{\hbar^2}\right )^{3/2}(E_V-E)^{1/2}
\end{align*}
for the conduction and valence bands respectively. How does this translate to two dimensions, especially considering that I now have an effective mass tensor?

A: First, the formula you give for the effective DOS in one dimension is not correct. It is the usual 3D-formula. Your effective mass tensors have the same reciprocal masses in x and y directions. Therefore you have isotropic effective masses m* in the conduction and valence bands. If your isotropic effective masses are constant you should in 2D get an energy independent 2D density of states per unit area D(E)=m*/(πℏ^2).


text:
Q: Eclipse missing action Set I have a problem while opening Eclipse. In the error log it says:
unable to find action set org.eclipse.wb.core.ui.actionset
       org.eclipse.rse.core.search.searchActionSet
       org.eclipse.rse.core.search.searchActionSet
       org.eclipse.mylyn.doc.actionSet
       org.eclipse.mylyn.context.ui.actionSet

I'm using Eclipse juno(version 4.2) and my ADT is version20 and Java 1.6
Do you have any idea what I am supposed to do?

A: In general this is a leftover from something you have uninstalled. To get rid of the error, close Eclipse, find the workbench.xml (XML) and workbench.xmi (XMI) files in either the
.metadata\.plugins\org.eclipse.ui.workbench\

or
.metadata\.plugins\org.eclipse.e4.workbench\

directories within your workspace and remove ALL corresponding lines (search for the package name you see in the message).

A: I think that this can happen when features are removed from Eclipse and a workspace is not properly updated. Create a new workspace, import all your projects, and delete the old workspace.

A: I went to the run configurations for the RCP app I had (created using EMF) and I checked the radio box under the Run--> configurations... dialog to "Clear workspace" before running.  This fixed the issue about the missing ActionSets.  I tried to find the references to the missing ActionSets per the above method and that did not fix the bug (there were no references to the missing ActionSets in the workbench.xml or workbench.xmi files.  I am using Kepler SR2 on Mac OS X 10.9.2.

A: I had this problem due to a particular view (although I'm not sure what caused it in the first place).  I simply closed the view and restarted Eclipse - problem solved!


text:
Q: How to have a 2 column text with equations that numbers in an independent way I am writing a text and I need to have two columns. On the first I will develop the exact solution of a problem with a set of equations, on the second one I will develop an approximate solution and the sequence of equations on one column.  So far I only was able to use 2 columns but if I place one quation on the left and another on the right I get a sequential numbering.
I have this on my tex document
\newenvironment{columns}[1][]
{\setkeys{columns@col}{#1}
    \noindent\begin{minipage}{\textwidth}}
    {\end{minipage}\vspace{.5cm}}

\newenvironment{column}[1]
{\begin{minipage}[t]{#1}}
    {\end{minipage}}

\begin{columns}
    \begin{column}{0.5\textwidth}
        The solution using series approximation is:
    \begin{equation}
    \frac{1}{\sqrt{1 - x}} \approx 1 + \frac{1}{2x} - O(x^2)
    \end{equation}
    \end{column}
    \begin{column}{0.5\textwidth}
        \begin{center}
The exact solution is
    \begin{equation}
\frac{1}{\sqrt{1 - x}} \approx 1 + \frac{1}{2x} - O(x^2)
\end{equation}
        \end{center}
    \end{column}
\end{columns}


text:
Q: How to unpacking effectively Monte Carlo simulations in Python leveraging from numba? SOLVED I am trying to create a Monte Carlo simulation effectivelly, because in my use case I would need to run this simulation 70*10^6 times. I was hoping that someone more experienced especially in performance could provide me some ideas of what could I try.
I have the following inputs:

*

*Demand

*

*Each column is a product, Each row is a month

*Some products in a determined month have a demand estimated by a triangular distribution tuple(min,mean,max). For those values I will make a Monte Carlo Simulation 1000 times

*Stock

My desired output is to find the:

*

*Median of the Distribution of the sum of available products (np.median(np.sum(available_products))), the median receives the 1000 simulations of the sum of available_products(available_products=stock-demand).

However I am having some issues:

*

*Speed, I have the intuition that there are clever ways to calculating leveraging vectorized functions. However I could not think of any, so I tried the usual loops. Please if you have any clue of any different approach that can be faster, let me know.

*FIXED Cannot set values to an array, in my solution I cannot set values using
demand_j[index_demand_not_0][k] = dict_demand_values_simulations[k][j]

*

*SOLUTION, I just need to access directly the demand_j location by demand_j[row,col].

Here is the code using the 3D array for demand as suggested by @Glauco:
import numpy as np
from numba import jit

@jit(nopython=True, nogil=True, fastmath=True)
def calc_triangular_dist(demand_distribution, num_monte):
    # Calculates triangular distributions
    return np.random.triangular(demand_distribution[0], demand_distribution[1], demand_distribution[2], size=num_monte)

def demand3d():
    # Goal find distribution_of_median_of_sum_available_products(np.median(np.sum(available_products)), the median from the 1000 Monte Carlo Simulations ): available_products=stock-demand (Each demand is generated by a Monte Carlo simulation 1000 times, therefore I will have 1000 demand arrays and consequently I will have a distribution of 1000 values of available products)
    # Input
    demand_triangular = np.array(
        [
            [0.0, 0.0, 0.0, 0.0],
            [0.0, 0.0, 0.0, (4.5, 5.5, 8.25)],
            [(2.1, 3.1, 4.65), 0.0, 0.0, (4.5, 5.5, 8.25)],
        ]
    )  # Each column represents a product, each row a month. Tuples are for triangular distribution (min,mean,max)
    stock = np.array(
        [[30, 30, 30, 22], [30, 30, 30, 22], [30, 30, 30, 22]]
    )  # Stock of available products, Each column represents a product, each row a month.
    num_sim_monte_carlo = 1000

    # Problem 1) How to unpack effectively each array of demand from simulation? Given that in my real case I would have 70 tuples to perform the Monte Carlo simulation?

    row, col = demand_triangular.shape
    index_demand_not_0 = np.where(
        demand_triangular != 0
    )  # Index of values that are not zeros,therefore my tuples for triangular distribution

    demand_j = np.zeros(shape=(row, col,num_sim_monte_carlo), dtype=float)

    triangular_len = len(demand_triangular[index_demand_not_0])  # Length of rows to calculate triangular
    for k in range(0, triangular_len):  # loop per values to simulate
        demand_j[index_demand_not_0[0][k], index_demand_not_0[1][k]] = calc_triangular_dist(
            demand_triangular[index_demand_not_0][k], num_sim_monte_carlo
        )

    sums_available_simulations = np.zeros(
        shape=num_sim_monte_carlo
    )  # Stores each 1000 different sums of available, generated by unpacking the dict_demand_velues_simulations

    for j in range(0, num_sim_monte_carlo):  # loop per number of monte carlo simulations
        available = stock - demand_j[:,:,j]
        available[available < 0] = 0  # Fixes with values are negative
        sums_available_simulations[j] = np.sum(available)  # Stores available for each simulation
    print("Median of distribution of available is: ", np.median(sums_available_simulations))

if __name__ == "__main__":
    demand3d()

The results of the suggestions show a much better performance using the 3D array :), now that I have only arrays I can try to to improve further using numba.
Baseline  0.4067141000000001
1) Monte Carlo per loop  0.035586100000000176
2) Demand 3D  0.017964299999999822

Thanks

A: internal loop can be removed using array programming + fancy indexing, this speed up the assignment to demand_j.
Another point is that you can generate one time the demand_j adding a dimension (the num_sim_montecarlo) it become 3d array, and in the loop you must only read the values avoiding to create values at each loop.


text:
Q: Adding line space in output of php code I have php code to print two tables continuously. But border of first table coincide with the border of second table. How can I give space between them. echo "\n" , echo ("\r\n"); echo ("\r"); are not  helping.

A: You should use css with the second table (or first)
.yourTable {margin-top: 10px;}

Or the quick, dirty and the wrong solution: just print a
 between the tables

A: echo '
'; or you can use CSS

A: With CSS margin or add a


text:
Q: Drupal 7.0 Views 7.x-3.14 Time-based cache is not functioning as expected I must admit some of this caching stuff is over my head, so this may be a misunderstanding on my part of how this is supposed to function.
But essentially I have a View with the following traits:

*

*pulling six different fields (2 text, 2 date, 1 boolean, 1 image - although that's just a text string too, right?)

*four filters with two exposed to users

*full pager showing 15 items per page (30+ items was making mysql go away)

*sorted by date and sticky

*time-based cache is turned on. Settings: query results-never,
rendered output-5 mins

Amount of data being pulled is huge: over 4,700 records
Only other caching solution on the site is stock Drupal page caching for anonymous and blocks, both enabled.
Cron is running every day although I suspect it fails sometimes.
The default filters are supposed to show all events from "time - now" until there are no more future event nodes.
Problem is, the cache sometimes shows "Now" as being yesterday or two days ago.
Shouldn't the cache refresh every five minutes? Am I misunderstanding how this setting works?
Shouldn't the View show up-to-date data even if cron doesn't run, or is cache expiration dependent on the cron running successfully? Or is the stock Drupal page cache overriding the Views cache for anonymous users?
Thanks!


text:
Q: OpenGL ES 2.0 displaying objects in opposite depth order using LibGDX I am using LibGDX and rendering a few models. This works as expected, except objects that are "further away" are displayed "in front" of "closer" objects. In other words the depth order seems to be the opposite of what I intended for it to be.
Strangely, the models are clipped in the correct order by the far clipping-plane. (Most distance objects disappear first)
I have tried enabling GL_DEPTH_TEST, and I am clearing GL_DEPTH_BUFFER_BIT.
Does anyone know what could be causing this?

A: If it's always exactly the wrong order, check that you've passed something meaningful for glDepthFunc. The default is the usually sensible GL_LESS; try GL_GREATER.
If the order appears to be the order you're issuing draw calls then check that you actually have a depth buffer. It's hard to be more specific without knowing which LibGDX backend you're using but unless a depth buffer has been allocated then it doesn't matter what you do with the depth test, there's no storage for the buffer regardless.
Correct answer, as per twiz's comment below:

I needed to set GL_LESS, but apparently LibGDX doesn't like it when
  you use glDepthFunc(). My custom shader implements the Shader class,
  so I had to use the RenderContext that is passed to the begin()
  method. Then I added this line: context.setDepthTest(GL20.GL_LESS);

My guess would be that possibly LibGDX is doing something intelligent with threading and the appropriate context isn't set prior to calling the shader inits (or, possibly, LibGDX strictly wants you to use the explicit context rather than an implicit one and therefore goes out of its way not to have one be set — there's possibly a consideration of what can be threaded where in the future and a desire to keep the coding rules uniform). Just a random guess, of course.


text:
Q: How do I change the Dock magnification on Mac OS X using a keyboard shortcut? I am new to Automator and AppleScript. I see a couple of links about customizing the dock, but they seem to be doing more than I need (or understand). Is there a quick, short way to do this ?

A: You can set the Dock magnification via AppleScript like this:
tell application "System Events"
    tell dock preferences
        set properties to {magnification:true, magnification size:1.5}
    end tell
end tell


text:
Q: how to design vertical custom JProgressBar I have written this code for custom JProgressBar in which "string painted" appears just after the progress line, but I want the same functionality in a vertical JProgressBar, please tell how can I do that???
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class R {

    public static void main(String arg[]) throws Exception {
        new R();
    }

    public R() throws Exception {

        JFrame f = new JFrame();
        CustomProgressBar b = new CustomProgressBar();
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);
        f.setUndecorated(true);
        f.setLayout(new FlowLayout());
        b.setStringPainted(true);
        f.add(b);
        f.setVisible(true);

        for(int i=0; i<101; i++) {
            b.setValue(i);
            Thread.sleep(50);
        }
    }

}

class CustomProgressBar extends JProgressBar{

    private static final long serialVersionUID = 1L;
    private boolean isStringToBePainted = false;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        if(isStringToBePainted ) {
            Dimension size = CustomProgressBar.this.getSize();
            int x = (int)( size.width * CustomProgressBar.this.getPercentComplete() );
            int height = g.getFontMetrics().getHeight();
            int d = g.getFontMetrics().getDescent();
            int y = (size.height + height)/2-d;
            String text = getString();
            g.setColor(Color.BLACK );
            g.drawString(text, x, 12);
        }
    }

    @Override
    public void setStringPainted(boolean b) {

        isStringToBePainted=b;
    }
}

A: You'd call getOrientation() and compare the results to SwingConstants.VERTICAL or SwingConstants.HORIZONTAL to determine the orientation of the JProgressBar.
For painting the text vertically, I found this page which gives two examples. The first one prints the characters "right side up". It does this by getting all the characters from the string and looping over them, painting each one and incrementing the y value. The second example prints the characters sideways, using AffineTransform to rotate the graphics context 90 degrees, then painting the string.


text:
Q: Javafx. Удаление строки из TableView и MySQL Нужно реализовать удаление строки из базы данных при вводе номера этой строки (id_depositor) в текстовое поле id_depositorField.
Добавление новых записей в таблицу работает, при удалении же ничего не происходит. Как это можно исправить?
Класс Depositors:
package sample;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

public class Depositors {

@FXML
private ResourceBundle resources;

@FXML
private URL location;

@FXML
private Button backButton;

@FXML
private TableView<depositorTable> depositor_Table;

@FXML
private TableColumn<depositorTable, Integer> id_depositor;

@FXML
private TableColumn<depositorTable, String> FIO;

@FXML
private TableColumn<depositorTable, String> address;

@FXML
private TableColumn<depositorTable, String> phone_number;

@FXML
private TableColumn<depositorTable, String> passport_data;

@FXML
private Button addButton;

@FXML
private Button changeButton;

@FXML
private Button deleteButton;

@FXML
private TextField id_depositorField;

@FXML
private TextField fioField;

@FXML
private TextField addressField;

@FXML
private TextField phone_numberField;

@FXML
private TextField passport_dataField;

ObservableList<depositorTable> oblist = FXCollections.observableArrayList();

@FXML
void initialize() {

    addButton.setOnAction(actionEvent -> {
        signUpNewDepositor();
        oblist.clear();
        addFunction();
    });

    deleteButton.setOnAction(actionEvent -> {
        deleteChosenDepositor();
        oblist.clear();
        addFunction();
    });

    addFunction();

    id_depositor.setCellValueFactory(new PropertyValueFactory<>("id_depositor"));
    FIO.setCellValueFactory(new PropertyValueFactory<>("FIO"));
    address.setCellValueFactory(new PropertyValueFactory<>("address"));
    phone_number.setCellValueFactory(new PropertyValueFactory<>("phone_number"));
    passport_data.setCellValueFactory(new PropertyValueFactory<>("passport_data"));

    depositor_Table.setItems(oblist);
}

// вывод таблицы
public void addFunction() {
    try {
        Connection con = DatabaseHandler.getConnection();
        ResultSet rs = con.createStatement().executeQuery("SELECT * FROM depositor");

        while (rs.next()) {
            oblist.add(new depositorTable(rs.getString("id_depositor"), rs.getString("FIO"),
                    rs.getString("address"), rs.getString("phone_number"),
                    rs.getString("passport_data")));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// добавление записи в таблицу
private void signUpNewDepositor() {
    DatabaseHandler dbHandler = new DatabaseHandler();

    String FIO = fioField.getText();
    String address = addressField.getText();
    String phone_number = phone_numberField.getText();
    String passport_data = passport_dataField.getText();

    depositorTable depositor = new depositorTable(FIO, address, phone_number, passport_data);

    dbHandler.signUpDepositor(depositor);
}

// удаление записи из таблицы
private void deleteChosenDepositor() {
    DatabaseHandler dbHandler = new DatabaseHandler();

    String id_depositor = id_depositorField.getText();

    depositorTable depositor = new depositorTable(id_depositor);

    dbHandler.deleteDepositor(depositor);
}
}

Класс DatabaseHandler:
public void deleteDepositor(depositorTable depositor) {
String delete = "DELETE FROM " + Const.DEPOSITOR_TABLE + " WHERE " + Const.DEPOSITOR_ID + " = ?";

try {
    PreparedStatement prSt = getDbConnection().prepareStatement(delete);
    prSt.setString(1, depositor.getId_depositor());

    prSt.executeUpdate();
} catch (SQLException | ClassNotFoundException e) {
    e.printStackTrace();
}
}


text:
Q: Configurable product - show individually i have problem with displaying configurable products. We are using Magento 1.9.3.6 (but will be migrating to Magento 2.4.3 soon.
I started creating configurable products, everything is working OK - I have product displayed, click on configurable swatches (e. g. color, size), but problem is that after clickin to this swatch, it doesn´t go to this product, only swatch is selected. The type of behavior I am looking for is, that when customer clicks on one of the swatch (let´s say blue T-shirt), he is redirected to blue T-shirt URL with that product. Reason is simple - we have multiple images for every color and this way we are not able to display multiple images, but just one. Same way for example zalando has this https://www.zalando.sk/calvin-klein-golf-3-pack-zakladne-tricko-khakinavywhite-ck442d00j-n11.html
I was thinking of doing this by having those variants (products in swatches) to be displayed in catalog (instead of do not show individually), but this then creates problem as these products have no images.
Also, I have question, how can this be done on any simple product already created before?
Do you have any idea how this can be done in Magento?

A: Configurable products work like that. The point of configurable products is that You have one page for multiple products.
I guess, the functionality You are looking for is (it should be also easier to implement):
Display Child (simple) product's Galery (instead of the Configurable), whenever customer change / choose swatch on Configurable Product Page.
But are You looking for solution for M1.9 or M2.4 ?
Anyway, at this point, You should be able to find a solution much easier (if that solution is sufficient).


text:
Q: Locally Compact Group with Haar Measure Suppose $G$ is a locally compact abelian group, with Haar Measure $\mu$, then is $\mu(E)=\mu(E^{-1})$ for all subsets $E$ of $G$?
I have seen that this is true for all Borel subsets of $G$, but I am in need of a proof and also an example showing why it doesn't hold for other subsets.

A: Not necessarily. This condition is equivalent to each left-invariant Haar measure
being right-invariant. A group having this property is called unimodular.
Since the concept has a name, then there must be groups where it fails.
See the Wikipedia article on Haar measure for an example.

A: Of course, a measure is in general only defined on some $\sigma$-algebra of sets, and for Haar measure that's the Borel sets.  As Pete mentioned you can complete the measure if you like, but that still won't yield all sets.  So for an arbitrary set $E$, $\mu(E)$ may not even be defined.
You can see this is necessary with an example you already know: let $G = S^1$ thought of as $[0,1]$ mod endpoints, and let $E$ be the usual example of a non-measurable set (the Vitali set).  There's no value for $\mu(E)$ that will let $\mu$ be translation invariant, finite, and nontrivial, which are required for a Haar measure, and so there's no "Haar measure" defined for all subsets.  To be able to have a Haar measure, we need to define it only on "reasonable", i.e. Borel, sets.


text:
Q: Faster Algorithm to Tailor Given Mathematical Expression Is there a more optimized solution to solve the stated problem?
Given an array 'arr' of 'N' elements and a number 'M', find the least index 'z' at which the equation gets satisfied. [ ] is considered as floor().

Code:
counts=0
ans=0
while(ans==0):
    s=0
    for i in range(counts,len(arr)):
        s+=int(arr[i]/(i+1-counts))
        if(s>M):
            break
    if((i+1)==len(arr) and s<=M):
        print(counts)
        ans=1
    counts+=1

Explanation:

*

*Check array from left to right. The first index that satisfies the condition is the answer. This is more optimized than considering from right to left.

*If at any time during the calculation, 's' is deemed more than M, break the loop and consider the next. This is more optimized than calculating 's' completely.
Example:
INPUT:
N=3 M=3
arr=[1 2 3]
OUTPUT:
0
This would give the answer 0 since the 0th index contains the first element to satisfy the given relation.
Thanks in advance.

A: If you're working with relatively small arrays, your algorithm is going to be fast enough.  Minor improvements could be achieved by reorganizing the code a bit but nothing dramatic.
If you're working with very large arrays, then I would suggest you look into numpy.  It is optimized for array wide operations and has impressive performance.
For example, you can divide all the elements in an array by their inverted position in one operation:
terms = arr / np.arange(len(arr),0,-1)

and then get cumulative sums and the first index in a single line
index = np.where(np.cumsum(terms) <= M)


text:
Q: Adicionar código na Pasta de Trabalho utilizando uma macro Tenho um código que registra quem imprime o documento, mas tenho uns mil documentos e tenho que inserir o código, eu já tenho o código de colocar módulos, mas preciso de um para colocar na Pasta de Trabalho pra funcionar quando imprime, mas não encontro como.
Private Sub Workbook_BeforePrint(Cancel As Boolean)

On Error Resume Next

Dim revisão As Integer
revisão = 0
Dim vUsuario As String, vMaquina As String
vUsuario = deUSUARIO()
vMaquina = deMAQUINA()

Open "\\CAMINHO\DO\ARQUIVO\" & Right(Left(ActiveWorkbook.Name, 8), 4) & ".txt" For Input As #1

Line_ = 0

Do Until EOF(1)

    Line Input #1, Text

    Line_ = Line_ + 1

    If Text = "" Then

        Exit Do

    End If

    revisão = Left(Text, 3)

Loop

Close #1

Open "\\CAMINHO\DO\ARQUIVO\" & Right(Left(ActiveWorkbook.Name, 8), 4) & ".txt" For Append As #2

If revisão <= 9 Then

    Print #2, "0" & (revisão + 1) & " - O usuário: " & vUsuario & " - " & "pela Máquina: " & vMaquina & " - " & "Imprimiu este documento dia: " & Now

Else

    If revisão >= 10 Then

        Print #2, (revisão + 1) & " - O usuário: " & vUsuario & " - " & "pela Máquina: " & vMaquina & " - " & "Imprimiu este documento dia: " & Now

    End If

End If

Close #2

End Sub

A: Encontrei a resposta.
Set WECodeMod2 = ActiveWorkbook.VBProject.VBComponents("EstaPasta_de_trabalho").CodeModule

Open "c:\CAMINHO\DO\ARQUIVO.txt" For Input As #2

  Line_1 = 0

  Do Until EOF(2)

    Line Input #2, text_1

    Line_1 = Line_1 + 1

    WECodeMod2.InsertLines Line_1, text_1

  Loop

Close #2


text:
Q: Standard fields missing in Google to Salesforce user provisioning mapping We have following setup:

*

*Google Workspace as an Identity Provider, Salesforce using Google to SSO

*Google Workspace as user management system responsible for automatic user provisioning and deprovisioning

We use Google's standard Salesforce connector which gives provisioning and deprovisioning capabilities. It's easy to setup and quite powerful. However, when mapping the Google attributes to Salesforce we can't map following Salesforce fields:

*

*RoleId

*FederationId
Because of the first field missing we started to use SAML JIT (Just In-Time Provisioning) which in our case is supposed to update the user with role that is coming with SAML Assertion (Google User provisioning creates the user earlier). This forced us into setting SAML Identity Type
as Assertion contains the Federation ID from the User object which is required when using JIT. And then comes the second issue - FederationId also can't be mapped in Google's Salesforce User provisioning - which makes later SSO not possible. For now we went with the flow copying username/email into FederationId field.
Questions:
Did you encounter such issues?

*

*Is there a way to pass RoleId as part of user provisioning in Google's  standard Salesforce app?

*Is there a way to pass FederationId as part of user provisioning in Google's  standard Salesforce app?


text: Q: Installing OWASP ZAP as Service on Windows 10 I am Trying to install OWASP ZAP (2.9.0) to run as a service on one of our servers for the testing environment.   I've been trying unsuccessfully to use YAJSW.  I creates a service but promptly stops running and gives up after a few restarts.   The QA team has selenium tests which are configured to run through the instance of ZAP running on a particular server.  If Zap in manually started.  I would like to just have it running as a background/headless service though.  We use YAJSW to run other java applications as services.  Not sure why this is failing.


text:
Q: Logger error Problem I used Logger class in my application for catching the error and logging events. But at the time of writing the log to the text pad, it returns one exception like this
 Microsoft.Practices.ObjectBuilder2.BuildFailedException was unhandled by user code
  Message="The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, null]) failed: The device is not ready.\r\n (Strategy type ConfiguredObjectStrategy, index 2)"

My code for writing the log is:
 public static void Log(string Message)
    {
        LogEntry log = new LogEntry();
        log.TimeStamp = DateTime.Now;
        log.Title = "Exception Logging";
        log.Categories.Add("Category");
        log.Message = Message.ToString();
        Logger.Write(log);
    }

Please help for resolving this issue..

A: I would guess from the error, that this logger is trying to write to a file.
The file path is probably pointing to an empty CD/DVD drive, or a removable drive that has been ejected or something like that.
Can you verify the device the logger is trying to write to?


text:
Q: React Component: Need to format an address from an API response and pass it to a component with copy to clipboard functionality I have a react component that displays an address with a copy to clipboard icon next to it.
The address is returned with 5 elements: address1, address2, city, state, and zip
When I display the elements on the front end, I'm able to conditionally render them based on if they exist. However I'm not sure how to pass that to my CopyButton.
I started to write a formatter but I'm running into issues when it comes down to passing the formatted address in.
Here's my current code for the formatter as well as the displayed string and CopyButton component for reference:
Formatter

    const formatAddress = (addressLine1: string, addressLine2: string, city: string, state: string, zip5: string ) => {
        let formattedAddress = ''
        address2 ? formattedAddress = `${addressLine1} ${addressLine2}, ${city}, ${state} ${zip5}` : formattedAddress = `${addressLine1}, ${city}, ${state} ${zip5}`
        return formattedAddress
    }

 element with address and CopyButton

 {address1
    ? (

           {address1}
           {address2 && `, ${address2}`}
           {city && `, ${city}`}
           {state && `, ${state}`}
           {zip && ` ${zip.substring(0, 5)}`}
           {formatAddress(address1, address2, city, state, zip)}
           <ButtonCopyText
              a11yText="Copy Address"
              textToCopy={formattedAddress}
           />

      ) : (

--

      )
  }

A:         let formattedAddress = ''
        address2 ? formattedAddress = `${addressLine1} ${addressLine2}, ${city}, ${state} ${zip5}` : formattedAddress = `${addressLine1}, ${city}, ${state} ${zip5}`

could be this
const formattedAddress =
  `${addressLine1}${addressLine2 ? ` ${addressLine2}` : ''}, ${city}, ${state} ${zip5}`.trim();

Also, you never define formattedAddress when you go to use it as a prop passed to your <ButtonCopyText /> component.  You could call the function right there in the prop assignment, or assign the return value of the function into that variable somewhere outside of the JSX.


text:
Q: Router won't re-offer DHCP Wondering if this "as designed" or a bug in my netgear router.
I have an AP connected to the router (via EoP)
If i connect to the router SSID, get an IP then disconnect and connect to the AP SSID I can't get an IP. I've tried numerous AP's
Running TCPDUMP on the AP I see that the router responds to the DHCP Discover with an ARP request for the IP it previously issued....
Is this normal?
10:44:45.086801 IP (tos 0x0, ttl 255, id 52143, offset 0, flags [none], proto UDP (17), length 328)
        0.0.0.0.bootpc > 255.255.255.255.bootps: [udp sum ok] BOOTP/DHCP, Request from 24:e3:14:1f:47:1d (oui Unknown), length 300, xid 0xdb47d999, secs 2, Flags [none] (0x
    0000)
              Client-Ethernet-Address 24:e3:14:1f:47:1d (oui Unknown)
              Vendor-rfc1048 Extensions
                Magic Cookie 0x63825363
                DHCP-Message Option 53, length 1: Discover
                Parameter-Request Option 55, length 7:
                  Subnet-Mask, Classless-Static-Route, Default-Gateway, Domain-Name-Server
                  Domain-Name, Option 119, Option 252
                MSZ Option 57, length 2: 1500
                Client-ID Option 61, length 7: ether 24:e3:14:1f:47:1d
                Lease-Time Option 51, length 4: 7776000
                Hostname Option 12, length 11: "Adams-Phone"
                END Option 255, length 0
                PAD Option 0, length 0, occurs 15
10:44:45.107653 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.0.3 tell 192.168.0.1, length 46


text:
Q: Cascaded Stern-Gerlach and Polarization Experiments - Differences in measurement concepts I want to understand a subtle difference between cascaded Stern Gerlach and polarization experiments.
Both affect spin 1/2 phenomena.
In Stern Gerlach the standard textbook description is like this:

*

*Atoms are split into |↑⟩ and |↓⟩. The |↑⟩-atoms are kept while the |↓⟩ are absorbed. This absorption is what turns this first to a measurement device and distinguishes it from a mere splitter, producing an entanglement between position (exit paths) and spin.

*Atoms then are split into |←⟩ and |→⟩, but only the |←⟩ atoms are kept. Thus, one would expect that the spin of the atoms points |↑⟩ and |←⟩.

*If these atoms are again brought into a B-field which separates the atoms into |↑⟩ and |↓⟩, one would expect that we obtain only |↑⟩ atoms, because we kept only those atoms in step 1. However, we find that the atoms are again split into |↑⟩ and |↓⟩. Thus, we conclude that the second measurement superposes the |↑↓⟩ spin direction.

Now: In Stern-Gerlach experiments I believe that we can replicate these thoughts by experiments.
With polarization experiments, however, I see a subtle difference. In all polarization experiments I know I cannot observe the "surviving" photons between the first and the second polarizer. All I can do is detect the photons which passed through all three polarizers at the very end of the cascade. Counting a photon destroys it in the detector (whereas counting a silver atom in a Stern Gerlach device, does not destroy it).
Thus my questions:

*

*How do we know that the experiments are similar.

*How do I know that the photon I finally detect after the third polarizer is indeed the one which passed through polarizers one and two? (In my naive phantasy in the Stern Gerlach experiments I somehow can track the silver atoms, at least "virtually" through the three SG magnets).

*How do we know that the polarizers may be viewed as wave-function collapsing measurement devices (as opposed to a beam-splitting type of device).
The reason for my question is: I want to get a better understanding for what we know from experiment and for what we know from textbook theory.

A: I will answer your second question.

How do I know that the photon I finally detect after the third polarizer is indeed the one which passed through polarizers one and two?

In a polariser, photons are not absorbed and re-emitted in the transmission direction. And photons are indivisible units from their emission to their absorption. So it is clear that the photons in front of the polarisers are the same as on the detector screen. The polarizers influence the direction of the electric (and magnetic) field only from a random distribution to a polarization.
With a polariser tuned to a certain wavelength, approx. 50 % of the photons pass through the polariser. This is the case if the radiation was not polarised before.
Since half of the photons pass through the first polariser and are aligned with their fields after passing through (that is what we mean by polarization), we can conclude that the photons with a field direction +/-90° to the slits undergo a rotation and get aligned. The other half of the photons are absorbed or reflected. Of course, the photons passing through are blocked at the next polariser, where the slits are 90° to the first polariser. All photons get absorbed or reflected.
So what a placed in between polarizer with an orientation of 45° degrees do? He rotates the incoming photons nearly without any losses to to the 45°. And the third polarizer do the same. That is why the structure of three polarizers is transparent.
Can you now try to apply this view to your first question.

A: *

*The experiments are similar because both deal with particles, both divide into two groups, and most importantly both devices rotate the particles to align with the slit or the magnetic field. In other words they don't just divide they also influence.
(2) The photons or the electrons reaching the detector are the same ones all the way through the experiment because you can  eliminate all other sources and leave only one path from source to detector through the experiment.
(3) Particles are sent through either device and they make it through or they don't. It has nothing to do with wave-functions collapsing. As a particle travels through it is also rotated to align with the slits or magnetic fields.
It's important to remember these devices are not just dividing into groups they are also rotating the spins and polarization's each time.


text:
Q: are locally unique pure quantum states also ground states of some local hamiltonian? Let $H=\sum_i H_i$ be some k-local hamiltonian with a unique ground state $|\psi>$. Then it is easily shown that $|\psi>$ is k-locally distinguishable from any other state $|\psi'>$.
Is the converse also true?
In other words assume $|\psi>$ is a pure state such that for any other pure state $|\psi'>$ there exists a subset of qubits $K$ s.t $|K| \leq k$  for a fixed $k>1$ and
$tr_{[n]\backslash K}(|\psi>) \neq tr_{[n]\backslash K}(|\psi'>)$
is it true that there exists some hamiltonian $H=\sum_i H_i$ where $H_i$ acts on at most k qubits s.t $|\psi>$ is the only ground state of $H$?

A: The question, as I understand it, asks the following:
Consider a state $|\psi\rangle$ which is uniquely determined among all other pure states by its K-party reduced density matrices. Is it guaranteed that this state is the ground state of a K-local Hamiltonian?
First, we should note that not only is it the case that any unique pure ground state of a K-local Hamiltonian is uniquely determined among all other pure states by its K-party reduced density matrices, but it is also uniquely determined among all states (including mixed states) by its K-party reduced density matrices.
More concretely:
Define the set of n-particle quantum states which have the same K-RDMs as $\rho$ to be $A_k(\rho)$. Define the unique state with maximum entropy among all states in $A_k(\rho)$ to be the K-correlated state $\tilde{\rho}_k$. A space $V$ is called K-correlated if the maximally mixed state supported on $V$ is also K-correlated. It is observed in this paper that if $V$ is the ground state space of a K-local Hamiltonian, then $V$ must be K-correlated.
Consider a quantum state $|\psi\rangle$ which is uniquely determined by its K-RDMs. If there were a K-local Hamiltonian with this quantum state as its unique ground state, then the ground state space $V$ would be one dimensional, and since $V$ must be K-correlated, the state with maximum entropy which has the same K-RDMs as $|\psi\rangle$ is just $|\psi\rangle$. This implies there are also no mixed states which share the same K-RDMs as $|\psi\rangle$.
So if there existed a pure state which was uniquely determined among all pure states by its K-RDMs, but not uniquely determined among all states (including mixed states) by its K-RDMs, then it could not be the ground state of a K-local Hamiltonian.
In this paper, posted today, I, and my collaborators, show that such states do exist. Thus the answer to your question is no, the converse is not true. Even if you show that there do not exist any other pure states with the same K-RDMs as your pure state, it is possible that it can not be the ground state of some K-local Hamiltonian.


text:
Q: In Swift, how to ignore a part of the code when running from an App Extension target? There's a similar question that works on Objective-C, but I tried the same code in Swift and it never executes, neither in the main app, nor in the action extension.
My situation is similar to the one in the question above, that is, when running from the main app I want to use UIApplication.shared.open to open a link in Safari, but I want to ignore this part of the code on the App Extension.
The problem isn't finding out whether the app is running from an App Extension or not, but ignoring the code when building for the App Extension, so that the compiler does not give me the following error on build:

A: You could introduce a new Custom Flag (similar to the DEBUG flag) for the extension target. In your Build Settings look for the Custom Flags and add a new one (e.g. "EXTENSION"). Like here in the screenshot, but also do it for release.

In your Code you could then do something like
#if EXTENSION
    // here goes code that is only compiled in the extension
#else
    // here goes code that is only compiled outside the extension
#endif

A: Update: Please read the Apple provided documentation on App Extensions:

Some APIs Are Unavailable to App Extensions
Because of its focused role in the system, an app extension is ineligible to participate in certain activities. An app extension cannot:

*

*Access a Application.shared object, and so cannot use any of the methods on that object

- Apple, App Extension Programming Guide

To programmatically find if the it the running extension via code it's really simple, just do this:
let bundleUrl: URL = Bundle.main.bundleURL
let bundlePathExtension: String = bundleUrl.pathExtension
let isAppex: Bool = bundlePathExtension == "appex"

// `true` when invoked inside the `Extension process`
// `false` when invoked inside the `Main process`


text:
Q: How to add a dynamic class as type parameter in a generic class I am developing an application with C# and angular, I want to make a generic service on the server-side which can be used by any controller
It is the service class
until now everything seems to be OK, but when I want to inject it as shown below
I inject the service
this shows this error
this is the error
please guide me on how to solve this problem


text:
Q: Exclude duplicates from django admin page My question is the following: can you exclude objects that are duplicated from being displayed on the admin page without DB modification, and if yes, how?
Thanks for all the help in advance

A: You can overwrite queryset inside your Admin model
def queryset(self, request):
    qs = super(MyModelAdmin, self).queryset(request)
    # update your query somehow
    return qs.distinct()


text:
Q: How to organize WebOS SQL code that depends on previous results? I want to do a simple WebOS Mojo app that adds dates to a database, but before that it needs to check few conditions by interrogating the database. Given the asynchronous mode of accessing the database in WebOS I'm wondering what is the most efficient and short way of writing such code.
For example I need to make sure the new date is not already in the database. Then I need to get the closest date so that I can compute the difference in days and throw an error if the difference is too small. Then I need to insert the new date and then compute an average.
This would be easy to do in a synchronous way of accessing the db, but I don't really like the idea of writing parts of the code in multiple success handlers of the different sql statements executed. Is there a more elegant solution?

A: You can use inline callbacks to the HTML 5 relational database functions:
function createProject(project, onSuccess) {
if (project.projectId)
    throw new StorageError("project already exists");
if (project.path)
    throw new StorageError("project already has a path");

project.projectId = ++Tracker.maxLocalId * 4096;
project.path = calcNextProjectPath();
project.normalize();

Tracker.db.transaction(
    function (transaction) {
        transaction.executeSql(
            "INSERT OR ROLLBACK INTO item (dbId, path, hasChildren, kind, summaryText, place, work, responsible, responsibleClass) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            [project.projectId, project.path, project.hasChildren, project.kind, project.title, project.place, project.work, project.responsible, project.responsibleClass],

            function (transaction, resultSet) {
                Mojo.Log.info("DB: inserted new project item", resultSet.insertId, project.title);

                transaction.executeSql(
                    "INSERT OR ROLLBACK INTO project (projectId, accountId, title, backendKind, backendStatus, backendLastChanged, lastSuccessfulDown) \
                            VALUES (?, ?, ?, ?, ?, ?, ?)",
                    [project.projectId, project.accountId, project.title, project.backendKind, project.backendStatus, project.backendLastChanged, project.lastSuccessfulDown],

                    function (transaction, resultSet) {
                        Warn.logInfo("created new project", "projectId=" + resultSet.insertId, project.title);
                        if (onSuccess)
                            onSuccess();
                    },

                    function (transaction, sqlError) {
                        Warn.bannerError("create", $L("Quit and reset your phone."), "project row insertion failed: ", sqlError.message, sqlError.code, project);
                        return true;   // abort whole transaction
                    }
                );
            },

            function (transaction, sqlError) {   // failure of insert project item
                if (sqlError.code === 1 && sqlError.message === "constraint failed" && Mojo.appInfo.id !== "com.outlinetracker.outlinetracker") {
                    upgradeAlert(true);
                } else {
                    Warn.bannerError("create", $L("Quit and reset your phone."), "project item insertion failed: ", sqlError.message, sqlError.code);
                }
                return true;   // abort whole transaction
            }
        );
     },   // end transaction function

    function (sqlError) {   // seems to only be called for exceptions in callbacks
        Warn.logError($L("Quit and reset your phone."), "transaction 'insert project' failed", sqlError.message, sqlError.code);
    }
);   // end transaction call

}


text:
Q: How to use regex for verifying multiple conditions in JAVA? I have a String as a input which has the below multiple conditions to pass.
It is a String  of length 8 and contains all numbers. Requirement is to
method should return false if any of the below 4 conditions is true.
First two characters -  13, 24, 28

characters three and four - 55, 99

characters five and six - 20, 21

last two characters - 42, 38, 09, 17, 66

How can I verify this using regex instead of spliting into 4 strings and checking.
Thanks in advance.

A: One way would be to use match group, so (a|b) would match either on a or b.
So your regex expression would be something like
^((13|24|28).{6}|.{2}(55|99).{4}|.{4}(20|21).{2}|.{6}(42|38|09|17|66))$

Which you could use in java with the Pattern and Matcher classes.
if (value.length() != 8) {
    return false;
} else {
    String patternString = "^((13|24|28).{6}|.{2}(55|99.).{4}|.{4}(20|21).{2}|.{6}(42|38|09|17|66))$";

    Pattern pattern = Pattern.compile(patternString);

    Matcher matcher = pattern.matcher(value);
    boolean matches = matcher.matches();

    return !matches;
}

About the length of the string, I don't see a good way to check that in a regular expression. So just check it with an if-else statement.
But make sure to only complie the pattern once if you need it multiple times.
Also for creating regular expression I would suggest using website like regex101 or regexr.

A: According to your question, string is consist of digit or not, its not clear. If string consist of all digit then try with this::
(^(13|24|28)\\d{6}$)|(^\\d{2}(55|99)\\d{4}$)|(^\\d{4}(20|21)\\d{2}$)|(^\\d{6}(42|38|09|17|66)$)
String text = "12345678";
        if (text.matches("(^(13|24|28)\\d{6}$)|(^\\d{2}(55|99)\\d{4}$)|(^\\d{4}(20|21)\\d{2}$)|(^\\d{6}(42|38|09|17|66)$)")) {
            System.out.println("Inalid");
        } else if(text.matches("^\\d{8}$")){
            System.out.println("Valid");
        } else {
            System.out.println("Invalid");
        }

Explaination:

*

*^(13|24|28)\d{6}$) -- matches first two digit && \d{6} means next 6
character is any digit..

*(^\d{2}(55|99)\d{4}$) -- \d{2} means first two any digit && matches
3rd and 4th digit with condition..\d{4} mean last 4 character be any
digit..
Demo here to check match or unmatch...


text:
Q: getting list of mp3 files from a sdcard in the order they were added in the card hi
i am developing an android app using an emulator.
i am using a filter class to filter mp3 songs and adding these to a list songs.
class Mp3Filter implements FilenameFilter
{
    public boolean accept(File dir, String name)
    {
        return (name.endsWith(".mp3"));
    }
}
public void updateList()
   {
       File home = new File(MEDIA_PATH);
       if (home.listFiles( new Mp3Filter()).length > 0)
       {
           for (File file : home.listFiles( new Mp3Filter()))
           {
            songs.add(file.getName());

           }

       }
   }

i want to know is there any order in which new songs gets added in sdcard like
alphabetically or datewise because i am seeing that new songs getting added anywhere
thus each time i am adding any songs i am finding my song list rearranged.
is there any way to get the list of all songs form the sdcard in the order of dates&time
they were added in the card ?

A: I don't think the File class exposes the creation date, but you could use the lastModified() method to find out when the files were last modified, then sort the list based on that value.


text:
Q: problem with UIWebview and link to App Store In my iPhone application I have a UIWebview that shows an html page.  Inside that page there are links that should lead the user to the iTunes application and the application they tapped on.  However, when the user taps on the link it errors out with 'too many redirects'.  Looking at it with a packet sniffer I see it just keeps redirecting to the same http://phobos.apple.com/... URL.  I even tried changing the link scheme to 'itms://' but that results in a 'Cannot show URL' error.  I could solve this problem by trapping the URLRequest and sending openURL: to the UIApplication but the app has already been deployed and I don't want to patch it.  I rather do it on the html/js/server side if possible.  Anyone have any ideas?

A: For anyone still searching for this answer, I found that it seems to be a problem on the simulator which doesn't support itms:// URLs (because there's no App Store app). I didn't see the same issue on hardware, where the App Store app opens just fine (in my case this was when testing URLs from AdMob adverts, but it's probably the same for UIWebView).


text:
Q: What ViewModelStoreOwner to use for ViewModelProvider in Fragment? I've creating a test activity that updates some text in my MyViewModel.
I'd like to observe these changes in a Fragment, but when I use
MyViewModel myViewModel = new ViewModelProvider(this).get(MyViewModel.class);

it gives me a different instance of MyViewModel than that used in the activity, which results in my onChanged() callback in the fragment not being called.
Only when I modify that same fragment code to
HomeViewModel homeViewModel = new ViewModelProvider(getActivity()).get(HomeViewModel.class);

does the fragment get the same instance of MyViewModel as the activity - so onChanged() is successfully called.
However, I'm not sure if using getActivity() as the ViewModelStoreOwner is the proper way of doing things as I haven't seen this in any examples anywhere. I'm wondering if there might be a better ViewModelStoreOwner I should be using in this instance?

A:
I'm wondering if there might be a better ViewModelStoreOwner I should
  be using in this instance?

You should use activity instance for sharing the same instance among fragments in the same activity.
Both Activity and Fragment implements their own ViewModelStoreOwner interface and implements the getViewModelStore() method. getViewModelStore() provide the ViewModelStore instance which is used to store the viewmodel objects, created by the ViewModelProvider.
Note: ComponentActivity implements the ViewModelStoreOwner interface and FragmentActivity (parent of AppCompatActivity) inherits the implementation.
So both Activity and Fragment have specific implementation for the ViewModelStoreOwner interface methods and store the viewmodel instance as per the  lifecycle of the objects(including the configuration changes).
Since fragments belong to activity get the same activity instance so using the getActivity() will result in using the ViewModelStoreOwner object of the activity. To share the objects among fragments, simply use the activity instance for creating ViewModelProvider which will use the same ViewModelStoreOwner in all fragments hence will return the persisted object of viewmodel (if created before).

A: Having an Activity which does as little as possible has become a "best practice" for some time now, so the scenario of an Activity and a Fragment which need access to the same ViewModel instance may not be covered by many guides.
But "there is no rule without an exception", and your scenario is similar to the one where an Activity has two Fragments which need to share data.
In this case, one uses the Activity scope for the ViewModel to make sure every component will have access to the same instance. See also the section "Share data between fragments" in the View Model Overview at developer.android.com


text:
Q: Change of variables in a double integral - how to find the region?? I have the following question:

Calculate the double integral $\int \int _D (x^4-y^4) e^{xy} dx dy $ on the region $D$, which is the set located in the first quadrant, bounded by the hyperbolas $xy=1, \quad x^2-xy-y^2=1, \quad x^2-y^2 =3 $.

My questions are:
It is obvious that I need to use the following change of variables: $u=x^2-y^2 , \quad v=xy$ , and once I draw the region $D$ in the xy plane, I know how to find the boundaries. But -

Is it possible to deduce the correct boundaries of the set $D^*$, which is the set $D$ in the $uv$ plane, without drawing the set $D$ in the xy plane?

If so, will you please help me understand how to do it?  When I draw the boundaries $u=3, \quad u-v=1, \quad v=1$ in $uv$ plane, I have two possible regions for $D^*$ , and have no idea how to choose between the two (without the drawing of $D$ )
Hope I made myself clear
Thanks in advance


text:
Q: jQuery Tablesorter and sortList I am using the jQuery tablesorter plugin (http://mottie.github.io/tablesorter/docs/index.html)
The tablesorter is working and I can disable sorting and filtering on a column using this code.
// Disable sorting and filtering on 1st column
$("table thead th:eq(0)").data("sorter", false).data("filter", false);

How can I use the .data method to do the equivalent of this?
$("table").tablesorter({
// sort on the 4th column, order asc
sortList: [[3,0]]
});

My problem is I can't determine how to use sortList: [[3,0]] with .data syntax. Any recommendations will be appreciated.

A: Well, you can use the data function like this to update the saved sort, but then you would need to actually trigger a sort to apply it:
$("table").data('tablesorter').sortList = [[3,0]];
$("table").trigger('update'); // apply the new sort

But really I think your best bet would be to just trigger a sorton event:
$("table").trigger("sorton", [[3,0]]);

A: "sorton event" like this
$("table").trigger("sorton", [[[3,0]]]);


text:
Q: Extracting specific data from predefined R function I am trying to figure out how I can extract a specific portion of output from a predefined R function. A simple exampled would be, if I would like to store the mean value calculated via the summary() function. I know that I could simply use the mean() function, but again, this is a simple example.
If I am running the summary() function on several datasets within a loop, I would like to store the calculated mean from each dataset (possibly in a new vector, say named 'means'), for later use. Here's a quick example of what I have tried:
>sum <- summary(data$Column1)
>sum
 Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 0.0300  0.1500  0.2200  0.3471  0.4000  2.5000
>names(sum)
[1] "Min."    "1st Qu." "Median"  "Mean"
[5] "3rd Qu." "Max."
>sum$Mean
Error in sum$Mean : $ operator is invalid for atomic vectors

A: Your variable sum is a named vector. To extract elements, use
sum["Mean"]

or
sum[4]

One point. Avoid using sum, since this is also the name of a standard function.

A: You can skip the step of storing the whole output of the function by subsetting the function directly
means<-vector()
means[1]<-summary(data$Column1)["Mean"]


text:
Q: Updating parameter of an SKAction that is repeating forever swift I have a function that animates a ball in a game that I am designing right now. However, I want the animation speed to change with the balls actual velocity, which I have achieved but only after each iteration of the animation. That makes it come out a little choppy, I am looking for a more elegant solution that could update the timePerFrame argument mid-action. I originally had it set to repeatforever but realized that timePerFrame wouldn't update once the action had started. Is there a way to make this animation speed change more smoothly?
func animBall() {
    //This is the general runAction method to make our ball change color
    var animSpeedNow = self.updateAnimSpeed()
    println(animSpeedNow)
    var animBallAction = SKAction.animateWithTextures(ballColorFrames, timePerFrame: animSpeedNow,resize: false, restore: true)

    self.runAction(animBallAction, completion: {() -> Void in
        self.animBall()

    })
}

func updateAnimSpeed() -> NSTimeInterval{
    // Update the animation speed based on the velocity to syncrhonize animation with ball velocity
    var velocX = self.physicsBody!.velocity.dx
    var velocY = self.physicsBody!.velocity.dy

    if abs(velocX) > 0 || abs(velocY) > 0 {
        var veloc = sqrt(velocX*velocX + velocY*velocY)
        var animSpeedNow: NSTimeInterval = NSTimeInterval(35/veloc)
        let minAS = NSTimeInterval(0.017)
        let maxAS = NSTimeInterval(0.190)

        if animSpeedNow < minAS {
            return maxAS
        }
        else if animSpeedNow > maxAS {
            return minAS
        }
        else {
            return animSpeedNow
        }

    }
    else {
        return NSTimeInterval(0.15)
    }
}

If it isn't possible to directly manipulate a parameter of an SKAction that is running forever, I supposed I

A: In your case, a simpler way would be to remove the old animation action and replace it with a new one.


text:
Q: What was the cost to produce one episode of Galaxy Rangers? I remember reading somewhere that the production was, at the time, USD $1,000,000 per episode. The only source I could find now is a comment on amazon, stating

the entire production cost $65 million dollars or $1 million dollars per episode ref thanks @Valorum

Is there a reputable source for this figure?

A: Best guess, approx $300k+ per episode.
The show's creator, Robert Mandell indicated in an interview with Starlog that his show wasn't dramatically more expensive than comparative shows in its market-space. Where it differed was that they were making enough shows (65 episodes) to go into immediate syndication and that the studio were planning to make their money back from overseas syndication rather than a tie-in to a major plastic toy brand.

"The syndication marketplace was just starting to explode in '84
because of the sucess of "He-Man & The Masters of the Universe".
He-Man really set the trend for producing animation with heavy toy company involvement. Toy companies have always been involved in
Saturday morning animation, but never to the extent that they were
producing 65 half hours of animation. It's an extremely expensive
endeavor. The average cost per strip has been somewhere near $15
million, which is a phenomenal amount of money  - it's like the budget
for a major motion picture. Most companies that get involved are
really looking for the big toy hit, because it's the only way a
financier can expect a return."
Starlog #121 August 1987


text:
Q: asp.net code-behind visible from browser? Can someone see the code-behind of an .aspx website from a browser?
I have been told it is possible but i cant really find a way of doing it , viewing the page source only shows the presentation page..
So is there a way of doing it ? and how?
thank you

A: No, it is not possible to see the codebehind without physical or remote access to the server itself.
You could also in theory misconfigure the IIS server to display the source files, and that would cause them to be displayed, rather than compiled, but no idea why anyone would do that. IIS by default will not display them.

A: By default, IIS shows parts of your code (aspx or code-behind) when an exception occurs - along with the call stack of the exception. Any serious ASP.NET application hides this information from users by using specific error handlers to show the error information in another (often more user-friendly) format.
As others mentioned, it's not normally possible to see the code, as it's a server-side handler, compiled and run on the server, while client only sees the HTML output.


text:
Q: Routing along existing road network using QGIS I just started learning QGIS and PyQGIS. I have one layer of a shapefile that contains a road network (image 1) and one layer of the CSV file (image 2) that contains several start and end points for certain roads within the road network.
How do I get the route from start to end points using the existing road network shapefile?
Unfortunately, those two layers come from different sources, so they don't share the same id or road name. I think the only way to connect those layers is by coordinating location.

A: But if you need to have distance from start to end, in reference to roads, you need to use a specific plugin for that: LRS
It does exactly what you need!


text:
Q: How can I move tableview section? I am developing the application with swift. I stored the objection data named Categories. I've added the tableViewImage here and there is no problem here. I want to move the section of the tableview together with the cell, but it does not. The functions I wrote are below. Please help me.Thanks.
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}
func tableView(_tableview:UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
{
let temp = categories[sourceIndexPath.section]
categories[sourceIndexPath.section] =  categories[destinationIndexPath.section];
categories[destinationIndexPath.section] = temp
}

func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .none
}

A: You can try using this method, assigning the position of the section you want to move and the place where you want it to be at the end:
table.moveSection(0, toSection: 1)

You could also try deleting the section in the IndexSet or appropriate position, subtracting in 1 the number of sections of the table and then reinserting the section and increasing the sections by 1
let index = IndexSet(integer: 0)
self.number_sections -= 1
table.deleteSections(index, with: .fade)

let newIndex = IndexSet(integer: 1)
self.number_sections += 1
table.insertSections(newIndex, with: .fade)


text:
Q: AttributeError: 'list' object has no attribute 'values' I have a mistake that I can't solve.. have you got an advice?
polygons = [r['shape_attributes'] for r in a['regions'].values()]

AttributeError: 'list' object has no attribute 'values'

A: If I understand well : a is a dictionnary but a['regions'] is a list of dictionnaries.
Indeed a 'list' object has no attribute 'values'.
If you want to loop over the values of your list you need to use this syntax :
polygons = [region['shape_attributes'] for region in a['regions']]

A: you need for each annotation-img one dictionary, that's the way Mask RCNN works.
{
    "IMG_20180413_091455.jpg1231831": {
        "base64_img_data": "",
        "file_attributes": {},
        "filename": "IMG_20180413_091455.jpg",
        "fileref": "",
        "regions": {
            "0": {
                "region_attributes": {
                    "damage": "damage"
                },
                "shape_attributes": {
                    "all_points_x": [
                        2388,
                        2586,
                        2645,
                        2655,
                        2635,
                        2497,
                        2363,
                        2328,
                        2388
                    ],
                    "all_points_y": [
                        1100,
                        1129,
                        1189,
                        1243,
                        1298,
                        1298,
                        1229,
                        1159,
                        1100
                    ],
                    "name": "polygon"
                }
            }
        },
        "size": 1231831
    },

you need to add your load_funcion and your json file, Otherwise it's hard to help you.
I really want to know the result if you print this line.
annotations = list(annotations1.values())


text:
Q: How should I transfer files between consequent Batch Tasks? I have a bunch of Azure Batch Tasks (Windows) which are dependent on each other so that they are executed one after another. There is only one Job. Each Task requires all of the files generated in the previous Task (plus whatever files the previous Task got from its previous Task).
How should I transfer these files between the Tasks? My current solution is to execute a move command at the start of each commandLine for each Task. This move command moves all files from the previous Task's folder to the current Task's folder. This kinda works but doesn't seem right and I don't have any backup about the intermediary results.
I was thinking of setting all of the files as output for each Task (to Blob Storage) and setting them as input for the next Task but this doesn't work because I would have to know all files in advance to generate ResourceFile references for them. I don't know in advance which files will get generated. So my next best idea is to generate a ResourceFile reference for a single ZIP file which contains whatever contents the previous Task zipped into it. So the ZIP file's contents would change all the time but I can add it as input because I can create a ResourceFile reference to it (even if the file's contents change). But this seems rather cumbersome.
Other ideas?
P.S. This is related to my earlier question at Azure batch task dependencies: copy files from previous which mentions this same problem but asks a different question.

A: @lauri, I think there are few things you are do, considering you are already exploring the output file approach.
2 more ideas below:
Idea 1:
Using the azurefileshare for mounting in windows VMs.
Note: Since the VMs you got are Windows I think which limits your chance of using the blobfuse driver for blobstorage mount. ALthough if the azurefileshare is something you can use as the mounting point then you can use the feature in Batch called Mounting Virtual Filesystem and AzureFileSahre in particular for windows vms.
Here as well you need to make sure that there is the task Dependency in place so that for example task1 finishes first and then the output of that file can be accessed by the task 2 form mounted drive.
Idea 2:
Like you mention use persistening output file concept along with conceptually making that task dependent on the task which will first generate the outputfile and once its persisted the task which needs to use those files can trigger the download for resrouefile.
Pros for idea1:
Once mounted the drive is available in all windows node as drive so the download and upload time is cirtailed. (only the drive sync time latency is remain which should be few milliseconds) (I think un-noticeable)
Hope this helps. Thanks, :)

A: What you likely want is to mount a virtual file system on the pool allowing shared access. See https://learn.microsoft.com/en-us/azure/batch/virtual-file-mount


text: Q: Zero Inflated Binomial Regression in SPSS I am running a zero inflated binomial regression (ZINB) in SPSS using the R essentials extension. Unfortunately, the output from ZINB in SPSS only gives me the estimate, standard error, z-score, and p-value. I am wondering if there is an easy way to get the odds ratio and 95% confidence interval for these ZINB analyses in SPSS?


text:
Q: NSXMLParsing for particular tag value
Possible Duplicate:
NSXMLParsing for particular tag value

Hi, My xml file like that...
     <routes>
         <SourceCountry> Ireland </SourceCountry>
         <SourcePort> Larne </SourcePort>
         <DestinationCountry> UK< /DestinationCountry>
         <DestinationPort> Troon  </DestinationPort>
     </routes>
     <routes>
         <SourceCountry> Ireland </SourceCountry>
         <SourcePort> Larne </SourcePort>
         <DestinationCountry> UK </DestinationCountry>
         <DestinationPort >Cairnryan  </DestinationPort>
     </routes>
     <routes>
         <SourceCountry> France </SourceCountry>
         <SourcePort> Belfast </SourcePort>
         <DestinationCountry> UK </DestinationCountry>
         <DestinationPort> Birkenhead  </DestinationPort>
     </routes>
     <routes>
         <SourceCountry> France </SourceCountry>
         <SourcePort> Belfast </SourcePort>
         <DestinationCountry> UK </DestinationCountry>
         <DestinationPort> Heysham  </DestinationPort>
     </routes>

I want to parse particular data for  <SourceCountry>  == Ireland and   <DestinationCountry> == UK
please help me
thank in advance


text:
Q: How to remove space from an empty header In the homepage of dollarcryptos.com (screenshot provided), I can't remove the empty header with two gray horizontal lines.
I've right clicked the source and if I am correct I believe this is the HTML code:

I am not sure if that is correct though.
What I want to do is delete those horizontal lines and move up the price boxes so it fits in nicely.
Info on what's used:

*

*I'm using Wordpress

*the empty header with horizontal lines along with the price display is a widget.

(source: dollarcryptos.com)
I've tried:
.sidebar.sidebar-right {
  border: none;
}
.widget {
  border: none;
}

in the additional CSS section of the customize option on Wordpress

A: do
.home .ccpwp_Widget h4.td-block-title {
    display: none;
}


text:
Q: how to close a modal dialog in showEvent? I can't believe I have to ask this, but I can't get a PyQt5 modal dialog box to close from the showEvent.
Here is a miniature example program demonstrating the problem.  The intended behavior of this test program is since somethingWentTerriblyWrong is set, as soon as btnShowDialog is pressed, the modal dialog should perhaps appear for an instant, if even that long, and then close automatically, but as you can see from the screenshot below this does not happen.
# test.py

from PyQt5.QtWidgets import QApplication, QDialog, QWidget, QLabel, QGridLayout, QPushButton
from PyQt5.Qt import Qt

def main():
    app = QApplication([])
    mainForm = MainForm()
    mainForm.show()
    app.exec()
# end main

class MainForm(QWidget):

    def __init__(self):
        super().__init__()

        self.initUi()

        self.myDialog = MyDialog(self)
        # set that something went wrong in the dialog so it should close immediately in the showEvent
        self.myDialog.somethingWentTerriblyWrong = True
    # end function

    def initUi(self):
        # set default form size and location
        self.setGeometry(400, 400, 400, 275)

        # declare a button
        self.btnShowDialog = QPushButton('show dialog')
        self.btnShowDialog.clicked.connect(self.btnShowDialogClicked)

        # increase the font size
        setFontSize(self.btnShowDialog, 16)

        # declare a layout and add the label to the layout
        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.btnShowDialog)

        # add the layout to the form
        self.setLayout(self.gridLayout)
    # end function

    def btnShowDialogClicked(self):
        retVal = self.myDialog.exec()
        print('retVal = ' + str(retVal))
    # end function

# end class

class MyDialog(QDialog):

    def __init__(self, parent):
        super().__init__(parent)

        self.initUi()

        self.somethingWentTerriblyWrong = False
    # end function

    def initUi(self):
        self.setGeometry(250, 250, 250, 175)

        self.lblDialog = QLabel('label on Dialog')

        # center the label and increase the font size
        self.lblDialog.setAlignment(Qt.AlignCenter)
        setFontSize(self.lblDialog, 15)

        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.lblDialog)

        self.setLayout(self.gridLayout)
    # end function

    def showEvent(self, event):
        super(MyDialog, self).showEvent(event)

        # if something went terribly wrong, close this dialog form
        if self.somethingWentTerriblyWrong:
            print('in if self.somethingWentTerriblyWrong:')
            # self.reject()
            self.close()
        # end if

    # end function

# end class

def setFontSize(widget, fontSize):
    font = widget.font()
    font.setPointSize(fontSize)
    widget.setFont(font)
# end function

if __name__ == '__main__':
    main()

In MyDialog, I would have expected either the self.reject() or self.close() lines to get the dialog to close, however on Ubuntu 18.04 at least the modal dialog turns dark and hangs:

I'm certain execution is getting in the if statement in MyDialog's show event because the terminal output is:
$ python3 test.py
in if self.somethingWentTerriblyWrong:

What am I doing wrong?

A: You are prematurely closing the widget, in the showEvent() method the widget is visible but the painting on the device has not yet been done so when calling the close() method you stop the painting, and it is not hidden because the internal flag was not updated generating undefined behavior.
The solution is to invoke the close()method ( or reject() method) an instant after showEvent() after an instant (leaving the time for the internal flags to update correctly) using QTimer or QMetaObject:
from PyQt5.QtCore import Qt, QTimer, QMetaObject

# ...

class MyDialog(QDialog):
    # ...
    def showEvent(self, event):
        super(MyDialog, self).showEvent(event)

        # if something went terribly wrong, close this dialog form
        if self.somethingWentTerriblyWrong:
            print("in if self.somethingWentTerriblyWrong:")
            QTimer.singleShot(0, self.close)
            # or
            # - QMetaObject.invokeMethod(self, "close", Qt.QueuedConnection)
            # - QTimer.singleShot(0, self.reject)
            # - QMetaObject.invokeMethod(self, "reject", Qt.QueuedConnection)

A: Complete working example based on eyllanesc's answer:
# CloseDialogInShowEvent.py

from PyQt5.QtWidgets import QApplication, QDialog, QWidget, QLabel, QGridLayout, QPushButton
from PyQt5.Qt import Qt
from PyQt5.QtCore import QTimer

def main():
    app = QApplication([])
    mainForm = MainForm()
    mainForm.show()
    app.exec()
# end main

class MainForm(QWidget):

    def __init__(self):
        super().__init__()

        self.initUi()

        self.myDialog = MyDialog(self)
        # set that something went wrong in the dialog so it should close immediately in the showEvent
        self.myDialog.somethingWentTerriblyWrong = True
    # end function

    def initUi(self):
        # set default form size and location
        self.setGeometry(400, 400, 400, 275)

        # declare a button
        self.btnShowDialog = QPushButton('show dialog')
        self.btnShowDialog.clicked.connect(self.btnShowDialogClicked)

        # increase the font size
        setFontSize(self.btnShowDialog, 16)

        # declare a layout and add the label to the layout
        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.btnShowDialog)

        # add the layout to the form
        self.setLayout(self.gridLayout)
    # end function

    def btnShowDialogClicked(self):
        retVal = self.myDialog.exec()
        print('retVal = ' + str(retVal))
    # end function

# end class

class MyDialog(QDialog):

    def __init__(self, parent):
        super().__init__(parent)

        self.initUi()

        self.somethingWentTerriblyWrong = False

        self.tmrClose = QTimer(self)
        self.tmrClose.setInterval(200)
        self.tmrClose.timeout.connect(self.tmrCloseTimeout)
    # end function

    def initUi(self):
        self.setGeometry(250, 250, 250, 175)

        self.lblDialog = QLabel('label on Dialog')

        # center the label and increase the font size
        self.lblDialog.setAlignment(Qt.AlignCenter)
        setFontSize(self.lblDialog, 15)

        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.lblDialog)

        self.setLayout(self.gridLayout)
    # end function

    def showEvent(self, event):
        super(MyDialog, self).showEvent(event)

        # if something went terribly wrong, close this dialog form
        if self.somethingWentTerriblyWrong:
            print('in if self.somethingWentTerriblyWrong:')
            self.tmrClose.start()
        # end if
    # end function

    def tmrCloseTimeout(self):
        self.reject()
    # end function

# end class

def setFontSize(widget, fontSize):
    font = widget.font()
    font.setPointSize(fontSize)
    widget.setFont(font)
# end function

if __name__ == '__main__':
    main()


text:
Q: Line endings in child_process.exec() stdout I'm building my custom wrapper around wmic using node.js and I have problems parsing it's output. Not a problem, but I just don't know why this happens.
I thought line endings are either \r or \r\n and decided to look on it
Here's a demo piece of code:
exec('wmic process', {maxBuffer :1000*1024}, function (err, stdout, stderr){
    let location =stdout.indexOf('\n')-6;
    let region =stdout.substr(location, 10);
    console.log(region);

    let buf = new Buffer(stdout);
    let buf2 = new Buffer(30);
    buf.copy(buf2, 0, location, location+30);
    console.log(buf2);
});

I looked at region and saw this:

For some reason there are two \rs instead of one!
Output of console.log(buf2) also shows this:
<Buffer 6f 75 6e 74 20 20 0d 0d 0a 53 79 73 ...
                          ^^ ^^ ^^

I was ready to split lines by \r\r\n when I decided to pipe its output to text file and look through a hex editor:
wmic process > wmic.txt

What? Where are two \rs?
I have two questions:

*

*Where does Node get second \r from? I tried to find some info, but Google is kind of heavy on queries such as \r\r\n, this is the closest I could get, I'm not sure if it's related

*Why hex editor shows 16bit encoding and Node doesn't? I suppose I should've specified encoding in exec() options but I don't know which one. chcp shows 437th codepage, but I kind of want it to work in other codepages as well.


text:
Q: Solve the task. using 1 array I wrote a small program.
Сondition: "Given an array of size n. Insert an element with a zero value after each negative element of the array." I solved this task using 2 ArrayList arrays. I'm wondering if it's possible to get a solution using only 1 array?
Code of the program:
public class Task_108 {
public void Task108(){

    System.out.println("Input size of array: ");
    Scanner scn = new Scanner(System.in);
    int sizeArr = scn.nextInt();
    ArrayList<Integer> ArrIntNum = new ArrayList<>(sizeArr);            // Declare array

    Random rnd = new Random();
    int val;
    // Filling array random elements from -20 to 20
    for(int i = 0; i < sizeArr; i++){
        val = -20 + rnd.nextInt(41);
        ArrIntNum.add(i, val);
    }
    // Output array on the screen
    System.out.println(ArrIntNum.toString());

    ArrayList<Integer> ArrWithZeroAftNegVal = new ArrayList<>();        // Declare once more array

    // Adding zero after every negative number in array ArrIntNum and write in array ArrWithZeroAftNegVal
    for(int i = 0; i < sizeArr; i ++){
        if(ArrIntNum.get(i) < 0) {
            ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
            ArrWithZeroAftNegVal.add(0);
        }
        else
            ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
    }
    // Output edited array on the screen
    System.out.println(ArrWithZeroAftNegVal.toString());
    }
 }

A: Like this:
import java.util.ArrayList;
public class Task_108 {
    public void Task108(){

        System.out.println("Input size of array: ");
        Scanner scn = new Scanner(System.in);
        int sizeArr = scn.nextInt();
        ArrayList<Integer> arrIntNum = new ArrayList<Integer>(sizeArr); // Declare array

        Random rnd = new Random();

        // Filling array random elements from -20 to 20
        for(int i = 0; i < arrIntNum.size(); i++)
            arrIntNum.add(-20 + rnd.nextInt(41));

        // Output array on the screen
        System.out.println(arrIntNum);

        // Adding zero after every negative number in array ArrIntNum
        for(int i = 0; i < sizeArr; i++) {
            if(arrIntNum.get(i) < 0)
                arrIntNum.add(i + 1, 0);
        }

        // Output edited array on the screen
        System.out.println(arrIntNum);
    }
}

I also simplified your code for you.

A: A ListIterator works quite naturally, allow addition of elements on the same array:
ListIterator<Integer> i = ArrIntNum.listIterator();
while (i.hasNext()) {
    Integer value = i.next();
    if (value < 0) i.add(0);
}


text:
Q: JSONObject and JSONArray - Need to get values held in array I have the following JSON data structure:
{
    "myRequest": {
    "item1": "value1",
    "itme2": "value2",
    "item3Holder": {
        "id": [
        "ID001",
        "ID002",
        "ID003",
        "ID004"
        ]
    }
    }
}

I need to be able to get the id values from the id [] array.
I can can get the values for item1-3, but can't separate out the id [] array values.
JSONObject requestObj = new JSONObject(data.trim()).getJSONObject("myRequest");

// Retrieve items from JSONObject
String item1 = requestObj.getString("item1");
String item2 = requestObj.getString("item2");
String item3 = requestObj.getString("item3");

// Retrieve all id's
JSONArray ids = requestSubObj.getJSONArray("item3Holder");

for (int i = 0; i < ids.length(); i++) {
    String id = ids.toString();
    logger.info("id : " + id);
}

A: I think you should get the objects like this:
JSONObject item3Holder = requestObj.getJSONObject("item3Holder");
JSONArray ids = item3Holder.getJSONArray("id");

Also you need to call .getString(i) for the ids object
for (int i = 0; i < ids.length(); i++) {
    String id = ids.getString(i).toString();
    logger.info("id : " + id);
}


text:
Q: Colum Group in Report Viewer I have a column group nested in row groups. I want for the column group to only show a row for each item in the row group.

Is there any way to do this?

A: I resolved this by adding a row group inside the column group. I grouped the Results column using row group and it worked!


text:
Q: Animating A-Frame fog color I'm trying to animate the fog color in A-Frame by doing this:
<a-scene  antialias="true" fog="type: exponential; color: #444; density: 0.1">
    <a-animation  attribute="fog.color" from="#444" to="#000" dur="2000"></a-animation>
</a-scene>

But it doesn't seem to work. I can animate the density works fine this way, but the color just changes in a flash.

A: Might be a bug. Maybe try the animation component. https://github.com/ngokevin/kframe/tree/master/components/animation/
<head>
  <title>My A-Frame Scene</title>
  <script src="https://aframe.io/releases/0.3.0/aframe.min.js"></script>
  <script src="https://unpkg.com/aframe-animation-component/dist/aframe-animation-component.min.js"></script>
</head>

<body>
  <a-scene fog="color: #444" animation__fog="property: fog.color; to: #000; dur: 2000">
  </a-scene>
</body>


text:
Q: How to change an icon in a JQuery Datatables TD element, according to another TD element? I want to create a Datatable with the JQuery Datatable library, but for beautification and UI reasons, I want an icon to change according to another  input field. Lets say,
If td.field 4 is null then td.field 5 icon=1 else icon=2.

A: You are not going to add an Icon you are going to add a CSS Class and in the CSS class you are going to add the image you want.
Assuming you have made you ajax call and you have the JSON and you are creating the datatable.
table = $('#table').DataTable( {
    "columns": [

            { "className":'userName col-md-2', "data": "userName" },
            { "className":'desc col-md-2', "data": "desc" },
            { "className":'timeStart col-md-2', "data": "timeStart" },
            { "className":'timeEnd col-md-2', "data": "timeEnd" },
            { "className":'dispatcher col-md-2', "data": "dispatcher" },

            {
                "className":      'edit',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },

        ],
        "order": [[2, 'desc']], !NOT FINISHED YET

Immediate after this and before the  table.row.add you have to create seperately the createdRow with the Icon you want to manipulate.
Inside the table section you add the statement you want to make for the createdRow.
 "createdRow": function ( row, data, index ) {
         if ( data.dispatcher == null ) {
            $('td', row).eq(5).addClass("edit-incident2");
          }else{
            $('td', row).eq(5).addClass("edit-incident");
          }
        }

After this your code would look like the below witch is the fully table code.
table = $('#table ').DataTable( {
    "columns": [

            { "className":'userName col-md-2', "data": "userName" },
            { "className":'desc col-md-2', "data": "desc" },
            { "className":'timeStart col-md-2', "data": "timeStart" },
            { "className":'timeEnd col-md-2', "data": "timeEnd" },
            { "className":'dispatcher col-md-2', "data": "dispatcher" },

            {
                "className":      'edit',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },

        ],
        "order": [[2, 'desc']],
        "createdRow": function ( row, data, index ) {
         if ( data.dispatcher == null ) {
          //console.log(data.dispatcher);
            $('td', row).eq(5).addClass("edit-incident2");
          }else{
            $('td', row).eq(5).addClass("edit-incident");
          }
        }
    } );

Then you draw your table and the statement makes the job.
table.row.add( {
            "userName":     responsejson.userName,
            "desc":         responsejson.desc,
            "timeStart":    responsejson.timeStart,
            "timeEnd":      responsejson.timeEnd,
            "dispatcher":   responsejson.dispatcher,
            "_id":          responsejson._id,
        } ).draw();

The two CSS classes would look like this
td.edit-incident {
    background: url('../img/incident_management.png') no-repeat center center;
    cursor: pointer;}

td.edit-incident2 {
    background: url('../img/incident_management2.png') no-repeat center center;
    cursor: pointer;}

It is not something incredible fantastic but it took me some hours, and I think the result is nice and very easy for the user to immediately understand what is he looking.

A: "columns": [
{
"className": 'details-control', "orderable": false, "data": null,"defaultContent": '', "render": function (data, type, row) {
     if(data.id==1)
          return '';
     else
     return '';
    },
}
]

just modify the column value before render.it's also possible to directly add the icon into datatable with the help of above code

A: giv ids for each row  and tds

 if you creating  dynamically using the database

     for(i=0;i<upto number of tds in a row;i++)
    {
       if($('#'+i).text()!='')//find td is null or not
       {
          $('#'+i).append('if');
       }
      else
       {
          $('#'+i).append('else');
       }
    }


text:
Q: Why does repeating a loop change the results of looped optimization? My original function embodies several optimize() functions, for which I get different results when I apply the function the first time vs. second time.
I tried this but I made sure that the returned value is one-dimensional.
fn = function(A,P){
  l_fn = function(x) {
    L <- x[1]
    -((A*L*P)-(P*L^2)) # -1 because optimize-function finds minimum
  }
  l_opt <- as.numeric(optimize(l_fn,c(0,1000))[2]) # get objective output
  return(l_opt)
}

f <- data.frame(x=c(10:20))

for (i in 1:length(f)) { # run this part 2 times!
  f$test <- sin(f$x) # this is how I expect a function to behave
  f$out[i] <- fn(f$x[i],100)
}

running the code the first time produces f$out that are all equal (weird). running the for loop again changes f$out, eventhough the input parameters remain the same! How is that possible?


text:
Q: Should I edit the whole question or just post an update, to address the comments? Admittedly, I posted this question composed in a bad way, initially at least. As some people were asking for clarifications, I was posting updates one by one, to address each comment, marking each update with [UPDATE] outline.
I usually do so, to make sure the comments made by others still remain valid, once the question has been edited. This time though, someone suggested that instead of posting updates, I should consider editing the question as a whole, so I did just that.
Is it a good practice to adhere to?
Outside the context of that specific question, is it not a concern that some comments may simply loose sense, if the question has been edited the way it looks as an original unedited post? I don't think people often care to check the history of editions.

A: Questions should avoid having a "sense of time", they are forever and should feel as if they were asked all at once in the best way possible. Make your question as good as it can be (don't invalidate existing answers however)
Comments on the other hand are transitory and will likely be deleted once you have made your edit. Never worry about invalidating them. You can even flag comments as "obsolete" after you have incorporated their suggestions and a moderator will delete them or you can @reply their author to say you've made the changes and the author will most likely delete them themselves.


text:
Q: Ruby - Time.now.to_date.next_month.begin gives error instead of first of next month When I use:
require 'date'
Time.now.to_date.next_month

it returns
 => #<Date: 2012-07-29 ((2456138j,0s,0n),+0s,2299161j)>

If I try tab completion for Time.now.to_date.next_month. I see:
1.9.3p194 :081 > Time.now.to_date.next_month.be
Time.now.to_date.next_month.begin     Time.now.to_date.next_month.between?

But if I try Time.now.to_date.next_month.begin I get
1.9.3p194 :081 > Time.now.to_date.next_month.begin
NoMethodError: undefined method `begin' for #<Date: 2012-07-29 ((...

Why is that?

A: It is because you are instantiating and asking for a suggestion in the same line.
Time.now.to_date.next_month.be<tab> #=> contains "begin"

t = Time.now.to_date.next_month
t.be<tab> #=> Does not contain "begin"

Since the Ruby interpreter has not processed the expression, it has no idea what kind of class it is dealing with and hence when you <tab>, it is just giving you everything.

A: This is because of function-overloading. When you have any concerns, first look the API reference and then ask the question.
The first date of next month is not returned because there is no such function in Date. There are total 719 functions defined on all objects, try to press tab on any  and begin and between happens to be such function.
The core assumption that "IRB auto_complete is guarantee that the function is what you want it to be" is completely misguided and wrong.


text:
Q: Finding the covariance when given joint pdf If the joint probability density of X and Y given by
$$
  f(x,y) =
\begin{cases}
1/4(2x+y),  & 0<x<1, 0<y<1\\
0, & \text{elsewhere}
\end{cases}
$$
Can I get some hints on how to find the Cov(x,y)?

A: Outline: We want to calculate $E(XY)-E(X)E(Y)$.  The three expectations can each be found by evaluating the appropriate double integral.

A: Maybe we could just consider the question through the relationship between marginal distribution and joint distribution.
The marginal probability density of y is $f_Y(y)=\int_0^1f(x,y)dx$=1/4(1+y),
so $E(Y)=\int_0^1yf_Y(y)dy=5/24$
then just calculate $E(X)$ and $E(XY)=\int_0^1\int_0^1xyf(x,y)dydx$.


text:
Q: XGBClassifier: Bad predictions after training, saving and loading a model Below is how I trained an XGBClassifier and saved it:
import pickle
from xgboost import XGBClassifier

# train
model = XGBClassifier()
model.fit(X, y)

# export
pickle.dump(model, open('model.pickle', 'wb'))

This is how I loaded the model and made predictions
loaded_model = pickle.load(open('model.pickle', 'rb'))
y_pred = loaded_model.predict(X)

The model predictions are OK if the model was loaded from within the same python process where the training was performed, but the predictions are not OK (random) if the model was loaded from a different python process than the one used for training.
Note, I've the same problem if model.save_model and model.load_model were used instead of pickle.
The simple checks I did shows the model was saved and loaded properly; the dumps of model._Booster (acquired via model._Booster.dump_model(some_file)) and loaded_model._Booster are identical.
Python version: 3.7.5
xgboost version: tried both 0.80 and 0.90
Any suggestion is appreciated.

A: In my case, i had changed column order while predicting which led to different performance. The column order for training data and prediction data Must be same