text:
Q: Azure Service Bus Queue: Messages are not being sent I'm sending messages to a Service Bus Queue from a Worker Role. I noticed that randomly some messages are lost.
When I debug, I set a breakpoint after the Send method and log into my Azure Panel to check if the message queue increased. What I found out is that strangely, messages are not added to the queue some times. But it is not randomly. The pattern is: One message is added correctly and the next is lost, then again next is ok, and the next is lost.
I've implemented a retry pattern like the following but apparently not all the messages are sent correctly.
My code is:
var baseAddress = RoleEnvironment.GetConfigurationSettingValue("namespaceAddress");
var issuerName = RoleEnvironment.GetConfigurationSettingValue("issuerName");
var issuerKey = RoleEnvironment.GetConfigurationSettingValue("issuerKey");
var retryStrategy = new FixedInterval(5, TimeSpan.FromSeconds(2));
var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
Uri namespaceAddress = ServiceBusEnvironment.CreateServiceUri("sb", baseAddress, string.Empty);

this.namespaceManager = new NamespaceManager(namespaceAddress, TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey));
this.messagingFactory = MessagingFactory.Create(namespaceAddress, TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey));
//namespaceManager.GetQueue("chatmessage");
QueueClient client = messagingFactory.CreateQueueClient("chatmessage");
APPService.Model.MessageReceived messageReceived = new Model.MessageReceived();
messageReceived.From= e.From;
messageReceived.Op = e.Operator;
messageReceived.Message = e.Body;
BrokeredMessage msg = null;

// Use a retry policy to execute the Send action in an asynchronous and reliable fashion.
retryPolicy.ExecuteAction
(
    (cb) =>
    {
        // A new BrokeredMessage instance must be created each time we send it. Reusing the original BrokeredMessage instance may not
        // work as the state of its BodyStream cannot be guaranteed to be readable from the beginning.
        msg = new BrokeredMessage(messageReceived);

        // Send the event asynchronously.
        client.BeginSend(msg, cb, null);
    },
    (ar) =>
    {
        try
        {
            // Complete the asynchronous operation. This may throw an exception that will be handled internally by the retry policy.
            client.EndSend(ar);
        }
        finally
        {
            // Ensure that any resources allocated by a BrokeredMessage instance are released.
            if (msg != null)
            {
                msg.Dispose();
                msg = null;
            }
        }
    },
    ()=>{},
    (ex) =>
    {
        // Always dispose the BrokeredMessage instance even if the send operation has completed unsuccessfully.
        if (msg != null)
        {
            msg.Dispose();
            msg = null;
        }

        // Always log exceptions.
        Trace.TraceError(ex.Message);
    }
);

What could be wrong?

A: Just looking at your code I am unable to notice anything that cloud lead up to the issue.
I suppose the counter on the portal is not updated in real time so I would not consider it as a test result.
I know I am not helping right now, but If I had the doubt you are expressing, I would build a end-to-end test to send and receive the messages, comparing the messageId.
Do you already use Service Bus Explorer by Paolo Salvatori on MSDN? You can use it to test the entities. It is a reliable tool to explore and test Service Bus.


text:
Q: Error in dplyr Mutate - looping through columns to produce graphs I'm working on RStudio trying to loop through a few lines of dplyr-ggplot script which identifies outliers, then makes a plot and labels the outliers. A subset of the data looks like:
    miR_373 miR_30 miR_182        type
C1     6.78  -2.88    3.75     control
C2    11.88   0.28    7.26     control
C3     8.55  -4.08    3.37     control
C4     7.60  -2.76    7.60     control
C5    13.18   2.33   13.18     control
P18   12.62   0.37    7.99     treated
P19    4.60  -7.62   -0.52     treated
P23    9.72   0.07    9.72     treated
P24   10.40  -0.68   10.40     treated
P25   11.08   0.81   11.08     treated
N20    7.35  -4.29    2.48 non_treated
N21    3.06  -2.21    4.59 non_treated
N22    6.05  -4.99    2.15 non_treated
N28   10.44  -0.15   10.44 non_treated
N29   10.59   0.36   10.59 non_treated

The below script works fine to produce one plot:
cts <- as.data.frame(read.csv("c:/Users/dat.csv", header = TRUE, row.names = 1))
is_outlier <- function(x) {
  return(x< quantile(x,0.25) - 1.5 * IQR(x) | x>quantile(x,0.75) +1.5 * IQR(x))
}

dat <- cts %>% tibble::rownames_to_column(var="outlier") %>% group_by(type) %>% mutate(is_outlier=ifelse(is_outlier(miR_373), miR_373, as.numeric(NA)))
dat$outlier[which(is.na(dat$is_outlier))] <- as.numeric(NA)

ggplot(dat, aes(y=miR_373, x=factor(type))) + geom_boxplot() + geom_text(aes(label=outlier),na.rm=TRUE,hjust=0.05) + geom_dotplot(binaxis='y', stackdir='center', dotsize=1, binwidth = .5)

producing

But the below code doesn't work to loop through variables (columns):
miRs <- names(cts)[c(1,2,3)]
for(i in miRs){
  dat2 <- cts %>% tibble::rownames_to_column(var="outlier") %>% group_by(type) %>% mutate(is_outlier=ifelse(is_outlier(i), i, as.numeric(NA)))
  dat2$outlier[which(is.na(dat2$is_outlier))] <- as.numeric(NA)

  ggplot(dat2, aes(y=i, x=factor(type))) + geom_boxplot() + geom_text(aes(label=outlier),na.rm=TRUE,hjust=0.05) + geom_dotplot(binaxis='y', stackdir='center', dotsize=1, binwidth = .5)
}

Error in mutate_impl(.data, dots) : Evaluation error: non-numeric argument to binary operator.

I can tell that my substitution of i in the loop isn't accepted but I don't know why and haven't found another way to do it. Any suggestions or further reading would be appreciated.

A: Programming with tidyverse packages takes some getting used to. In this case, you are treating i as though it were an expression, when in fact it is a string. You can convert it to quosure and then unquote it when you need it, like this:
for(i in miRs){
    i <- rlang::parse_expr(i)
    dat2 <- cts %>%
        tibble::rownames_to_column(var="outlier") %>%
        group_by(type) %>%
        mutate(is_outlier=ifelse(is_outlier(!!i),
                                 !!i,
                                 as.numeric(NA)))
    dat2$outlier[which(is.na(dat2$is_outlier))] <- as.numeric(NA)
    dev.new()
    p <- ggplot(dat2, aes(y=!!i, x=factor(type))) +
        geom_boxplot() +
        geom_text(aes(label=outlier),
                  na.rm=TRUE,
                  hjust=0.05) +
        geom_dotplot(binaxis='y',
                     stackdir='center',
                     dotsize=1,
                     binwidth = .5)
    print(p)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the velocity of the escape of the bullet
A gun has a muzzle 0.8 meters long and with a diameter of 0.006 m. A bullet with mass 0.002 kg is initially 0.01 m away from the end of the muzzle. As a result of a gunshot, the pressure of the gas reaches 1800 atm and the temperature reaches 6273 K. Find the velocity the escape of the bullet.

I just can think that the velocity is $\frac{x}{t}$. I don't know how to find the time. I thought to use the formula $p=F/S$ and I managed to find $S$, but how can I find $F$?

A: Using the diameter of the muzzle $d$ and the initial distance between the bullet and the end of the muzzle $l$ we can calculate the volume of the gas to be given by:
\begin{equation}
V\left(l\right)=\frac{\pi d^2\left(L-l\right)}{4}
\end{equation}
where $L$ is the total length of the muzzle. We therefore find from the ideal gas law that:
\begin{equation}
\begin{aligned}
P\left(l\right)&=\frac{nRT}{V\left(l\right)}\\
&=\frac{4nRT}{\pi d^2\left(L-l\right)}
\end{aligned}
\end{equation}
We equivalently have in terms of the initial pressure $P\left(l_0\right)=\frac{4nRT}{\pi d^2\left(L-l_0\right)}$ that:
\begin{equation}
P\left(l\right)=\frac{P\left(l_0\right)\left(L-l_0\right)}{L-l}
\end{equation}
Assuming the bullet fills the cross-sectional area of the muzzle we therefore find that the force the gas exerts on the bullet is given by:
\begin{equation}
\begin{aligned}
F\left(l\right)&=P\left(l\right)A\\
&=\frac{\pi d^2P\left(l_0\right)\left(L-l_0\right)}{4\left(L-l\right)}
\end{aligned}
\end{equation}
Assuming the bullet initially begins at rest we find that:
\begin{equation}
\begin{aligned}
W&=-\int_{l_0}^0F\left(l\right)\, \textrm{d}l\\
\implies\frac{1}{2}mv^2&=\frac{\pi d^2P\left(l_0\right)\left(L-l_0\right)}{4}\int_0^{l_0}\frac{\textrm{d}l}{L-l}\\
\implies v&=d\sqrt{\frac{\pi P\left(l_0\right)\left(L-l_0\right)\ln\frac{L}{L-l_0}}{2m}}\\
\end{aligned}
\end{equation}
Substituting our given values (as $1800\textrm{ atm}\approx 1.824\times 10^8\textrm{ Pa}$) we therefore find that:
\begin{equation}
\begin{aligned}
v&\approx 0.006\sqrt{\frac{\pi\left(1.824\times 10^8\right)\left(0.8-0.01\right)\ln\frac{0.8}{0.8-0.01}}{2\left(0.002\right)}}\\
&\approx 226.4\textrm{ m s}^{-1}
\end{aligned}
\end{equation}


text:
Q: Excel converts hyphened text into a date When I copy the data from query results of Sql Server db and pasted it on Excel the hyphenated text get converted to the date.
Like 2-12 gets converted to 12-Feb. How can I avoid that?

A: One way is to in your SQL server query convert the SQL server column to text and then append an apostrophe in front of it.  When you paste that into Excel it should be pasted as text, not as a date.  E.g.
SELECT '''' + CONVERT(nvarchar,Field_Name) FROM Table_Name

You likely will then need to select the column in Excel, right click it, select Format Cells and then change the format to text.  You can then replace the apostrophe and the column will be preserved as text and not automatically converted to a date format.


text:
Q: Key generation of an application in WSO2 API Maneger In API manager inside store we can create consumer key and consumer secret using generate keys button for an application.I am just digging the java code where its getting generated so that i can try to generate keys using a different identity server not API Manager's default identity server.
I am trying the same in wso2am-2.2.0-update7 version.
Main motive is using the third party identity server for keys and token generation.

A: Please refer https://docs.wso2.com/display/AM220/Configuring+a+Third-Party+Key+Manager. This contains what you need to do to configure third party IDP as a Key Manager in APIM


text:
Q: How can i create a model in Keras and train it using Tensorflow? Is it possible to create a model with Keras and without using compile and fit functions in Keras, use Tensorflow to train the model?

A: Sure. From Keras documentation:

Useful attributes of Model

*

*model.layers is a flattened list of the layers comprising the model graph.

*model.inputs is the list of input tensors.

*model.outputs is the list of output tensors.

If you use Tensorflow backend, inputs and outputs are Tensorflow tensors, so you can use them without using Keras.

A: You can use keras to define a complicated graph:
import tensorflow as tf
sess = tf.Session()
from keras import backend as K
K.set_session(sess)
from keras.layers import Dense
from keras.objectives import categorical_crossentropy

img = Input(shape=(784,))
labels = Input(shape=(10,)) #one-hot vector
x = Dense(128, activation='relu')(img)
x = Dense(128, activation='relu')(x)
preds = Dense(10, activation='softmax')(x)

Then use tensorflow to config complicated optimization and training procedure:
loss = tf.reduce_mean(categorical_crossentropy(labels, preds))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
init_op = tf.global_variables_initializer()
sess.run(init_op)
# Run training loop
with sess.as_default():
    for i in range(100):
        batch = mnist_data.train.next_batch(50)
        train_step.run(feed_dict={img: batch[0],
                                  labels: batch[1]})

Ref: https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html


text:
Q: JPanel drawn with extra width I have a Stratego board being drawn on a JPanel, being used to set up the player's pieces. After two different instances of these panels are correctly arranged by the players, the main board (that has the same format and layout, just will have different piece appearance and logical behavior) will show.
My issue is that the second input panel and the main board (which currently has no functionality or pieces on it) are SOMETIMES set up with extra width on the bottom and the right, causing the 10x10 grid to not take up the entire board space like it should.
The initial input panel for player 1 seems to be working fine, never having this problem. The second panel and the main panel only SOMETIMES have this issue, so I'm not entirely sure where this is stemming from.
Here is the main method which sets up the panels and stuff.
public class Core {

    public static void main(String[] args) {

        LogicInterpreter logic = new LogicInterpreter();

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        InputFrame inputPlayer1 = new InputFrame(logic, 1, "red", 600, 600);
        inputPlayer1.setLocation(dim.width / 2 - inputPlayer1.getSize().width/2,
            dim.height / 2 - inputPlayer1.getSize().height / 2);

        while(!logic.isSetUp1()){
            //Just to make it work
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //Now bring up board 2

        InputFrame inputPlayer2 = new InputFrame(logic, 2, "blue", 600, 600);
        inputPlayer2.setLocation(dim.width / 2 - inputPlayer2.getSize().width/2,
                dim.height / 2 - inputPlayer2.getSize().height / 2);

        while(!logic.isSetUp2()){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        openBoards(logic);
    }

    public static void openBoards(LogicInterpreter logic) {
        try {
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            MainBoard board = new MainBoard(logic);
            board.setLocation(dim.width / 2 - board.getSize().width / 2, dim.height / 2 - board.getSize().height / 2);
        } catch (Exception e) {
            System.exit(1);
        }
    }
}

Also, here is the code inside the input panels. I'm not sure what is relevant, so I can't take stuff out. Sorry. I will withhold the main board setup code because it is really the same.
public class InputFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private LogicInterpreter holder;
    private Panel2 jp;
    private int height, width;
    private Map<Integer, ArrayList<Integer>> lakeCoords = new HashMap<>();
    private List<Piece> pieces = new ArrayList<>();
    private int playernumber;
    private String playerColor;
    Piece selectedPiece;
    Piece secondSelectedPiece;
    boolean hidePieces = false;

    JButton submit = new JButton("SUBMIT");

    public void addCoords() {
        lakeCoords.put(3, new ArrayList<Integer>(Arrays.asList(6, 5)));
        lakeCoords.put(4, new ArrayList<Integer>(Arrays.asList(6, 5)));
        lakeCoords.put(7, new ArrayList<Integer>(Arrays.asList(6, 5)));
        lakeCoords.put(8, new ArrayList<Integer>(Arrays.asList(6, 5)));
    }

    public void createPieces() {
        int y = 1;

        if (playernumber == 2) {
            y = 7;
        }

        List<Integer> openValues = new ArrayList<>();

        openValues.add(1);
        openValues.add(2);
        openValues.add(11);
        openValues.add(12);
        for (int x = 0; x < 2; x++) {
            openValues.add(3);
        }
        for (int x = 0; x < 3; x++) {
            openValues.add(4);
        }
        for (int x = 0; x < 4; x++) {
            openValues.add(5);
            openValues.add(6);
            openValues.add(7);
        }
        for (int x = 0; x < 5; x++) {
            openValues.add(8);
        }
        for (int x = 0; x < 8; x++) {
            openValues.add(9);
        }
        for (int x = 0; x < 6; x++) {
            openValues.add(10);
        }

        Collections.sort(openValues);

        System.out.println(openValues.size());
        System.out.println(pieces.size());

        for (int x = 1; x <= 10; x++) {
            for (int z = y; z <= y + 3; z++) {

                // 1x1 Marshal
                // 2x1 General
                // 3x2 Colonel
                // 4x3 Major
                // 5x4 Captain
                // 6x4 Lieutenant
                // 7x4 Sergeant
                // 8x5 Miner
                // 9x8 Scout
                // 10x6 Bomb
                // 11x1 Flag
                // 12x1 Spy

                Piece piece = new Piece(new Coords(x, z), openValues.get(0), playerColor);

                openValues.remove(0);
                pieces.add(piece);
            }
        }
    }

    public InputFrame(LogicInterpreter holder, int playerNumber, String playerColor, int height, int width) {
        this.height = height;
        this.width = width;
        playernumber = playerNumber;
        this.playerColor = playerColor;
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        addCoords();
        this.holder = holder;
        createPieces();
        jp = new Panel2(height, width);
        setResizable(false);
        jp.setBackground(new Color(235, 202, 158));
        setTitle("Player " + playerNumber + " Arrangement GUI     ||     Click Submit When Ready");
        jp.setPreferredSize(new Dimension(600, 600));
        jp.setLayout(null);
        jp.addMouseListener(new HandleMouse());
        if(playernumber == 1)
            submit.setBounds(width / 10 * 4, height / 10 * 7, width / 10 * 2, height / 10 * 2);
        else
            submit.setBounds(width / 10 * 4, height / 10, width / 10 * 2, height / 10 * 2);
        submit.setFont(new Font("Arial", Font.BOLD, width * 20 / 600));
        submit.setBackground(Color.LIGHT_GRAY);
        submit.addActionListener(new CloseListener(this));
        jp.add(submit);
        getContentPane().add(jp);
        pack();
        setVisible(true);
    }

    class CloseListener implements ActionListener {
        private InputFrame frame;

        public CloseListener(InputFrame frame) {
            this.frame = frame;
        }

        public void actionPerformed(ActionEvent event) {
            // Do the stuff here before closing
            hidePieces = true;
            repaint();
            if (playernumber == 1) {
                holder.setP1Pieces(pieces);
                JOptionPane.showMessageDialog(null, "Press When Ready for Next Player");
                holder.setSetUp1(true);
            } else {
                holder.setP2Pieces(pieces);
                JOptionPane.showMessageDialog(null, "Press When Player 1 is Ready");
                holder.setSetUp2(true);
            }
            frame.dispose();
        }
    }

    public class Panel2 extends JPanel {

        private static final long serialVersionUID = 1L;
        int height = 0;
        int width = 0;

        public Panel2(int height, int width) {
            this.height = height;
            this.width = width;
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int x = 0; x < width; x += width / 10) {
                for (int y = 0; y < height; y += height / 10) {
                    boolean fill = false;
                    for (Entry<Integer, ArrayList<Integer>> coords : lakeCoords.entrySet()) {
                        if ((coords.getKey() - 1 == x / 60 && coords.getValue().get(0) - 1 == y / 60)
                                || (coords.getKey() - 1 == x / 60 && coords.getValue().get(1) - 1 == y / 60)) {
                            fill = true;
                            break;
                        }
                    }
                    if (fill) {
                        g.setColor(Color.BLUE);
                        g.fillRect(x, y, width / 10, height / 10);
                        g.setColor(Color.BLACK);
                        g.drawRect(x, y, width / 10, height / 10);
                    } else {
                        g.setColor(Color.BLACK);
                        g.drawRect(x, y, width / 10, height / 10);
                    }
                }
            }

            if(hidePieces){
                for (Piece piece : pieces) {
                    try {
                        g.drawImage(ImageIO.read(new File(playerColor + "_pieces/" + (playerColor.equals("blue") ? "Blue" : "Red") + "_Strat_Piece"
                                + ".png")), piece.getX() * width / 10 - width / 10,
                                piece.getY() * height / 10 - height / 10, width / 10, height / 10, null);
                    } catch(Exception e){}
                }
            } else {
                for (Piece piece : pieces) {
                    g.drawImage(piece.getImage(), piece.getX() * width / 10 - width / 10,
                            piece.getY() * height / 10 - height / 10, width / 10, height / 10, null);
                }

                if (selectedPiece != null) {
                    g.setColor(Color.BLUE);
                    g.drawImage(selectedPiece.getImage(), selectedPiece.getX() * width / 10 - width / 10,
                            selectedPiece.getY() * height / 10 - height / 10, width / 10, height / 10, null);
                    g.drawRect(selectedPiece.getX() * width / 10 - width / 10,
                            selectedPiece.getY() * height / 10 - height / 10, width / 10, height / 10);
                }
            }
        }
    }

    private class HandleMouse extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            Coords coordinates = holder.getClickedBox(x, y, width, height);
            boolean found = false;
            boolean move = false;

            for (Piece piece : pieces) {
                if (piece.getX() == coordinates.getX() && piece.getY() == coordinates.getY()) {
                    found = true;
                    if (selectedPiece == null) {
                        selectedPiece = piece;
                    } else {
                        move = true;
                        secondSelectedPiece = piece;
                    }
                }
            }
            if (move) {
                pieces.remove(selectedPiece);
                pieces.remove(secondSelectedPiece);
                Coords storage = selectedPiece.getCoords();
                selectedPiece.setCoords(secondSelectedPiece.getCoords());
                secondSelectedPiece.setCoords(storage);
                pieces.add(selectedPiece);
                pieces.add(secondSelectedPiece);
                selectedPiece = null;
                secondSelectedPiece = null;
            } else if (!found) {
                if (selectedPiece != null) {
                    selectedPiece = null;
                }
            }
            repaint();
        }
    }
}

A: Did you check how many pixels are "sometimes" added?
When i call setResizable(true) on my jframe, i notice that "sometimes" there are 10 pixels more, both in width and height, than i expect.
If this is your case, i answered a similar question here.
I was able to solve the problem using a 'trick', calling pack more than one time.
In the answer i also linked another similar question (this one), where i wasn't able to find another solution, but there some users described the bug.


text:
Q: What are the rules for blanket implementations regarding modules? I've been trying to find documentation on how Rust resolves trait blanket implementations in case module boundaries are involved, but didn't find much directly related to it.
Let's consider an example with two similar, but slightly different code snippets:
The first one is code that does compile just fine, but suffers an infinite runtime recursion. This happens because the blanket implementation of the ClonableIterator for  T: Iterator+Clone matches against the Box<dyn ClonableIterator<'a>> which is, thanks to our manual implementation of Clone and Box's blanket implementation of Iterator now Iterator+Clone.
//the trait itself, with the indirection to call box_clone on the base type
trait ClonableIterator<'a>: Iterator<Item = &'a u32> + 'a {
    fn box_clone(&self) -> Box<dyn ClonableIterator<'a>>;
}

//The blanket implementation of the trait for all clonable iterators
impl<'a, T: Iterator<Item = &'a u32> + Clone + 'a> ClonableIterator<'a> for T {
    fn box_clone(&self) -> Box<dyn ClonableIterator<'a>> {
        Box::new(self.clone())
    }
}

//Clone for the box. Does not work
impl<'a> Clone for Box<dyn ClonableIterator<'a>> {
    fn clone(&self) -> Self {
      (*self).box_clone()
    }
}

fn main() {
    let input = vec![1,2,3,4,5];
    let iter1 : Box<dyn ClonableIterator> = Box::new(input.iter());
    let iter2 : Box<dyn ClonableIterator> = Box::new(iter1.clone().filter(|&&x| x%2 == 0));
    println!("{} {}", iter1.sum::<u32>(), iter2.sum::<u32>())
}

(Playground)
The second snippet is just a slight modification of the above, namely the implementation of the Clone trait has been moved to a submodule. However, it is working and doing what one expects. Trait objects created of ClonableIterator are both, Clone and Iterator, and calling the clone() method on them creates an actual copy of the boxed iterator.
Both, Iterator methods and clone() can be directly called on the Box<dyn ClonableIterator>, and iterators created from it are again Clone+Iterator, so a ClonableIterator trait object can be created from them.
//the trait itself, with the indirection to call box_clone on the base type
trait ClonableIterator<'a>: Iterator<Item = &'a u32> + 'a {
    fn box_clone(&self) -> Box<dyn ClonableIterator<'a>>;
}

//The blanket implementation of the trait for all clonable iterators
impl<'a, T: Iterator<Item = &'a u32> + Clone + 'a> ClonableIterator<'a> for T {
    fn box_clone(&self) -> Box<dyn ClonableIterator<'a>> {
        Box::new(self.clone())
    }
}

//a helper module, to prevent the above blanket implementation from matching
//the Box<dyn super::ClonableIterator<'a>>.
//I can't find the documentation how this works, but it does work.
mod helper {
    impl<'a> Clone for Box<dyn super::ClonableIterator<'a>> {
        fn clone(&self) -> Self {
          (*self).box_clone()
        }
    }
}

fn main() {
    let input = vec![1,2,3,4,5];
    let iter1 : Box<dyn ClonableIterator> = Box::new(input.iter());
    let iter2 : Box<dyn ClonableIterator> = Box::new(iter1.clone().filter(|&&x| x%2 == 0));
    println!("{} {}", iter1.sum::<u32>(), iter2.sum::<u32>())
}

(Playground)
Could someone please explain or maybe link relevant documentation on how the rules for applying a trait blanket implementation differ from the rules for having the trait itself available?

A: I don't have a complete citation of the reference manual for all the parts here, but the difference I see between these two cases is ClonableIterator is not visible in mod helper (there is no use super::ClonableIterator). Thus, the trait is not consulted for arbitrary types when looking up methods, but (evidently) it is for dyn super::ClonableIterator, presumably because it would be gratuitously unhelpful to not do that.
So the method lookup procedure will be doing approximately this:

*

*We start with *self, an explicit dereference of &Box<dyn CloneableIterator<'a>> of type Box<dyn CloneableIterator<'a>>.

*

*Does this have an inherent method named box_clone()? No.

*Does any visible trait have a method named box_clone()?

*

*In the first program, yes (ClonableIterator was declared in the same scope), so that one is called.

*In the second program, no, so continue.

*Dereference Box<dyn CloneableIterator<'a>> to obtain dyn CloneableIterator<'a>.

*

*Does this have an inherent method named box_clone()? No.

*Does any visible trait have a method named box_clone()? Yes, apparently CloneableIterator is visible for the dyn type unconditionally.


text:
Q: Assign a public IP address to new Amazon Instance My Amazon Instance got terminated accidentaly. This Instance was having an IP address associated with itself so that it can be accessed from internet.
Now I have created another Instance from the snapshot of the previous one and now I want to assign the same IP address to the current Instance so that I can mask the server failure at the front end.
Any help?

A: Goto the AWS Console and goto Elastic IP. There you will see the IP Address that was previously attached to your ec2. Select the IP Address and Associate to new EC2 instance that you have launched.
If you have released the Elastic IP previously, then I believe you can't retrieve that Elastic IP.


text:
Q: Не срабатывает аутентификация/авторизация (JWT) для RequestDelegate Проект .Net Core. Пытаюсь сделать аутентификацию с использованием JSON Web Token (JWT). Обработчик, ответственный за генерацию токена отрабатывает и возвращает мне токен.
Но вот авторизация, судя по всему, не срабатывает - захожу в обработчики запроса (В коде Test1Handle и Test2Handle, которые с атрибутом Authorize) безо всяких преград, даже не получив предварительно токен. При этом свойство Context.User.Identity.Name = null.
Пробовал определять явно политику по умолчанию и указывать ее в AuthenticationSchemes атрибута Authorize, увы, не помогло.
Код моего StartUp.cs:
using KPAA.Services.AlarmsLibraryService.Authentication;
using KPAA.Services.AlarmsLibraryService.Database;
using KPAA.Services.Base.BaseREST;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace KPAA.Services.AlarmsLibraryService.REST
{
internal class TestStartup : BaseStartup
{
    private readonly MyContextFactory m_contextFactory;

    public TestStartup(MyContextFactory ContextFactory) : base()
    {
        m_contextFactory = ContextFactory;
    }
    public override void AddRoutes(RouteBuilder routeBuilder)
    {
        routeBuilder.MapRoute("test1", Test1Handle);
        routeBuilder.MapRoute("test2", Test2Handle);
        routeBuilder.MapPost("gettoken", TokenHandler);
        base.AddRoutes(routeBuilder);
    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRouting();
        services.AddAuthentication(SetAuthenticationOptions).AddJwtBearer(SetJWTAuthoptions);
        services.AddAuthorization(opts =>
        {
            opts.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser()
            .Build();
        });
    }

    private void SetAuthenticationOptions(AuthenticationOptions opt)
    {
        opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }

    private void SetJWTAuthoptions(JwtBearerOptions opt)
    {
        opt.RequireHttpsMetadata = false;

        opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = AuthOptions.ISSUER,
            ValidateAudience = true,
            ValidAudience = AuthOptions.AUDIENCE,
            ValidateLifetime = true,
            IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
            ValidateIssuerSigningKey = true,
            //ClockSkew = TimeSpan.Zero
        };
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        RouteBuilder routeBuilder = new RouteBuilder(app);
        AddRoutes(routeBuilder);
        app.UseRouter(routeBuilder.Build());

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.Run(async (context) =>
        {
            JSONResponse res = new JSONResponse(JSONResponseResult.Error);
            res.Message = string.Format("Route is unknown", context.Request.Path);
            await context.Response.WriteAsync(res.ToJson());
        });
    }

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public async Task Test1Handle(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync($"Test1. Identity is {context.User.Identity.Name}");
    }

    [Authorize]
    private async Task Test2Handle(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync($"Test2. Identity is {context.User.Identity.Name}");
    }

    private async Task TokenHandler(HttpContext context)
    {
        Routes.Token.Response response = new Routes.Token.Response(context);
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(response.ToJson());
    }
}
}

В чем может быть проблема? Как мне правильно сконфигурировать сервисы, чтобы авторизация стала работать и не пропускать запросы?


text:
Q: download image and add post meta value after post publish I have basicly generate my web pages qr code via google apis. Here is my basic qr Code generator function.
function istanbulThhemesQrCodeAction( $width = '130', $height = '130', $url = null, $choe = 'UTF-8', $type = 'qr') {
    if(empty($url)){
        $url = get_permalink();
    }
    $title = get_the_title();
    echo '

Sayfanın Qr Kodu

';
}

when i call this function on my single php; the qr code generated succesfully. But it is an external image. I want to download it(qr code image) in to my server called like post-name.jpg than, i want to write this image path into the custom meta field. Like http://example.com/images/qrcodes/postname.jpg
Who can help me about this ?
Thank you so much.


text:
Q: Ansible: Transforming list to dictionary with items2dict Given the following list:
fruits:
  - fruit: apple
    color: red
    texture: crunchy
    shape: round
  - fruit: grapefruit
    color: yellow
    taste: sour
  - fruit: pear
    color: yellow

How would I use the items2dict filter to change to a dictionary (below)?
Problem is there is multiple, and a variable amount of values.
"{{ fruits | items2dict(key_name='fruit', value_name='??????') }}

Desired result:
fruits:
  - apple:
      color: red
      texture: crunchy
      shape: round
  - grapefruit:
      color: yellow
      taste: sour
  - pear:
      color: yellow

I can't seem to find how here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#transforming-lists-into-dictionaries

A: I think you can do something like:
- name: bla
  set_fact:
    res: "{{ res | default({}) | combine({ item['fruit']: item }) }}"
  loop: "{{ fruits }}"

A: The task below does the job
    - set_fact:
        fruits2: "{{ fruits2|default([]) + [{ item['fruit']: value }]}}"
      loop: "{{ fruits }}"
      vars:
        keys: "{{ item.keys()|difference(['fruit']) }}"
        vals: "{{ keys|map('extract', item)|list }}"
        value: "{{ dict(keys|zip(vals)) }}"

gives
  fruits2:
  - apple:
      color: red
      shape: round
      texture: crunchy
  - grapefruit:
      color: yellow
      taste: sour
  - pear:
      color: yellow

A dictionary, instead of a list, can be created by simply changing the concatenation of the lists to the combination of the dictionaries e.g.
    - set_fact:
        fruits3: "{{ fruits3|default({})|combine({ item['fruit']: value }) }}"
      loop: "{{ fruits }}"
      vars:
        keys: "{{ item.keys()|difference(['fruit']) }}"
        vals: "{{ keys|map('extract', item)|list }}"
        value: "{{ dict(keys|zip(vals)) }}"

gives
  fruits3:
    apple:
      color: red
      shape: round
      texture: crunchy
    grapefruit:
      color: yellow
      taste: sour
    pear:
      color: yellow

items2dict can be used to select 2 attributes only (key_name and value_name) e.g.
    - set_fact:
        fruits4: "{{ fruits|items2dict(key_name='fruit', value_name='color') }}"

gives
  fruits4:
    apple: red
    grapefruit: yellow
    pear: yellow

A list (desired result) can't be created by items2dict. items2dict returns a dictionary.

items2dict will fail if the attribute is missing e.g.
    - set_fact:
        fruits5: "{{ fruits|items2dict(key_name='fruit', value_name='taste') }}"

fails
The error was: KeyError: 'taste'

A: The items2dict() function is not appropriate for your case, but you may use this simple approach instead:
rows = """\
fruits:
  - fruit: apple
    color: red
    texture: crunchy
    shape: round
  - fruit: grapefruit
    color: yellow
    taste: sour
  - fruit: pear
    color: yellow"""

rows_changed = "\n".join([2*" " + row if row.startswith(4*" ") else row
                             for row in rows.split("\n")])
print(rows_changed)

The explanation:

*

*rows.split("\n") creates a list of rows from the rows multi-line string,

*the expression 2*" " + row if row.startswith(4*" ") else row within [] (the list comprehension) then indents rows starting with 4-space indent by another 2-space indent,

*"\n".join() convert that (modified) list of rows back to the multi-line string.

The output:

fruits:
  - fruit: apple
      color: red
      texture: crunchy
      shape: round
  - fruit: grapefruit
      color: yellow
      taste: sour
  - fruit: pear
      color: yellow


text: Q: usb 3 recognized as 2.1 im trying to connect my quest and ive tried flipping swapping rotating the ends of the cable and reinstalled different drivers for my mobo. ive disabled the power option and the other selective thing as well.


text: Q: How to highlight ranges of lines in different colors in vscode extension development? I'm trying to develop a vscode extension which would read some data from a file and based on that data, highlight ranges of lines in different colors. eg: lines 1 to 10 in red color, lines 20 to 40 in green, lines 50 to 100 in yellow. If that isn't possible I could also do the highlighting in the gutter. However, I've not been able to find anything in the vscode extension development docs that would allow me to do this. I was expecting there to be an API like vscode.editor.background(1, 10, 'red')


text:
Q: Print from c++ file running on postgresql I am running some C++ code in postgresql. I am trying to print some output to keep track of the execution, but no result. Is there anything I need to add somewhere to enable printf command to work? I am adding the below mentioned files in my code:
#include "postgres.h"

#include <math.h>
#include <limits.h>
#include <inttypes.h>

What I am trying to print:
printf("abc");

Any help would be greatly appreciated, as I have been trying to get some output for the past 2 days. Thanks!
Edit : I am running the postgresql server using SSH. Let me know via comments if any more information is needed.

A: You need to use PostgreSQL's build-in logging system: http://www.postgresql.org/docs/current/static/error-message-reporting.html
From the reference:
elog(INFO, "count=%d", count);

The log level has to match the level you've configured PostgreSQL to write to its log file.

A: printf("abc"); will try to write to stdout, but normally Postgresql server runs as a daemon, which means it will close stdout, that is why you cannot see that string at the standard output.
You should use the error report facilities offered by Postgresql to output those message to Postgresql log file, as pointed out by @rygvis.

A: you can use fprintf(stderr, "abc\n"); instead of printf("abc");


text:
Q: Adding a hyperlink VBA I am desperately searching for a solution for my following problem in VBA for Excel:
I want to request user input asking for entering a website link. The code should transfrom this into a hyperlink (like excel does with the HYPERLINK formula). The output should add the word website to the ActiveCell with a hyperlink to the input website.
this is my latest approach:

Sub add_hyperlink()
    link = Chr(34) & InputBox("Enter link") & Chr(34)
    ActiveSheet.Hyperlinks.Add anchor:=ActiveCell, Address:=link,
    ScreenTip:="Follow this link", TextToDisplay:="website"
End Sub

Thanks for your help!

A: Not quite sure what is the problem, but this works:
Sub add_hyperlink()
    Dim link As String
    link = InputBox("Enter link")
    ActiveSheet.Hyperlinks.Add ActiveCell, link, ScreenTip:="Follow this link", TextToDisplay:="Website"
End Sub


text:
Q: Ubuntu 18, proxy not working on terminal but work on browser (related and perhaps more simple  problem to solve: proxy authentication by MSCHAPv2)
Summary: I am using a Ubuntu 18,  the proxy is working with web-browser but not with terminal applications (wget, curl  or apt update). Any clues? Seems the problem is to interpretate a proxy's "PAC file"... Is it? How to translate to Linux's proxy variables? ... Or the problem is simple: my  proxy-config  (see step-by-step procedure below) was wrong?

Details:
By terminal env | grep -i proxy we obtain
https_proxy=http://user:pass@pac._ProxyDomain_/proxy.pac:8080
http_proxy=http://user:pass@pac._ProxyDomain_/proxy.pac:8080
no_proxy=localhost,127.0.0.0/8,::1
NO_PROXY=localhost,127.0.0.0/8,::1
ftp_proxy=http://user:pass@pac._ProxyDomain_/proxy.pac:8080

and browser (Firefox) is working fine for any URL, but:

*

*wget http://google.com say  Resolving pac._ProxyDomain_ (pac._ProxyDomain_)... etc.etc.0.26 connecting to pac._ProxyDomain_ (pac._ProxyDomain_)|etc.etc.0.26|:80... conected.
Proxy request has been sent, waiting for response ... 403 Forbidden
2019-07-25 12:52:19 ERROR 403: Forbidden.

*curl http://google.com say "curl: (5) Could not resolve proxy: pac._ProxyDomain_/proxy.pac"

Notes
(recent news here: purge exported proxy changes something and not tested all again...)
The proxy configuration procedures that I used (there are some plug-and-play PAC file generator? I need a PAC file?)
Config procedures used

*

*All machine was running, with a direct non-proxy internet connection... Them the machine goes to the LAN with the proxy.

*Add lines of "export *_proxy" (http, https and ftp) in my ~/.profile. The URL definitions are in the form http_proxy="http://user:pwd@etc" (supposing that is correct, because testesd before  with user:pwd@http://pac.domain/proxy.pac syntax and Firefox promped proxy-login)(if the current proxy-password is using # character, need to change?)

*Add lines of "export *_proxy"  in my ~root/.profile.(need it?)

*(can reboot and test with echo $http_proxy)

*visudo procedure described here

*reboot and navigate by Firefox without need of login, direct (good is working!). Testing env | grep -i proxy, it shows all correct values as expected.

*Testing wget and curl as the begin of this report, proxy bug.

*Testing sudo apt update, bug.

*... after it  more one step, supponing that for apt not exist a file, created by sudo nano /etc/apt/apt.conf.d/80proxy  and add 3 lines for Acquire::*::proxy "value";  with value http://user:pass@pac._ProxyDomain_/proxy.pac:8080. where pass is etc%23etc, url-encoded.

Summary of tests performed
CONTEXT-1.1
(this was a problem but now ignoring it to focus on more relevant one)
After (the proxied) cable connection and  proxy configurations in the system. (see above section "Config procedures used"). Proxy-password with special character.

*

*curl http://google.com say "curl: (5) Could not resolve proxy..."
When change all .profile from %23 to # the error on wget changes, but curl not.  Wget changes to "Error parsing proxy URL http://user:pass@pac._ProxyDomain_/proxy.pac:8080: Bad port number"
PS: when used $ on password the system (something in the internal export http_proxy  command or use of http_proxy confused it with a variable).
CONTEXT-1.2
Same as context-1.1 above, but password with no special character. Good and clean proxy-password.

*

*curl http://google.com say "curl: (5) Could not resolve proxy..."
CONTEXT-2
After (the proxied) cable connection and no proxy configurations in the system (but confirmed that connection is working on browser after automatic popup form login).

*

*curl -x 192.168.0.1:8080 http://google.com "curl: (7) Failed to connect..."

*curl --verbose -x "http://user:pass@pac._proxyDomain_/proxy.pac" http://google.com say "curl: (5) Could not resolve proxy..."

Other configs in use
As @Roadowl suggested to check:

*

*files ~/.netrc and ~root/.netrc not exists

*file more /etc/wgetrc exists, but all commented, exept by  passive_ftp = on


text:
Q: Synchronized copying display with jProgressBar I wanted to monitor the progress of my file getting copied from source to destination. I have used synchronized keyword but somehow it not working as i expect it to be, my logic might be wrong. I will be glad if you help me out.
Here is my Code.
public class Download extends javax.swing.JFrame {
    int val=0;
    private Timer t;
    private ActionListener a;

/* Creates new form Download */
    public Download() {
       initComponents();
       jProgressBar1.setValue(val);
       a = new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent ae) {
            if (jProgressBar1.getValue() < val)
                jProgressBar1.setValue(jProgressBar1.getValue()+1);
            else
                t.stop();
          }
       };
    }
    public synchronized void copy(String source,String url)
    {
      try {
        val+=25;
        t=new Timer(200,a);
        t.start();
        FileInputStream fs = new FileInputStream(source);
        FileOutputStream os = new FileOutputStream(url);
        int b;
        while ((b = fs.read()) != -1) {
           os.write(b);
        }
        os.close();
        fs.close();
      } catch (Exception E) {
        E.printStackTrace();
      }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      JFileChooser chooser = new JFileChooser();
      chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      String url = null;
      int returnValue = chooser.showDialog(null, "Select");
      if (returnValue == JFileChooser.APPROVE_OPTION) {
         url = chooser.getSelectedFile().getPath();
      } else {
         dispose();
      }
      JOptionPane.showMessageDialog(this,"Wait for Completion");

      if(CB1.isSelected()==true)
      {
        File f = new File(getClass().getResource("/PCycle/Ele.pdf").getFile());
        String source= f.getAbsolutePath();
        copy(source,(url+"\\"+CB1.getText()+".pdf"));
      }
      if(CB2.isSelected()==true)
      {
        File f = new File(getClass().getResource("/PCycle/Mech.pdf").getFile());
        String source= f.getAbsolutePath();
        copy(source,(url+"\\"+CB2.getText()+".pdf"));
      }
      if(CB3.isSelected()==true)
      {
        File f = new File(getClass().getResource("/PCycle/Phy.pdf").getFile());
        String source= f.getAbsolutePath();
        copy(source,(url+"\\"+CB3.getText()+".pdf"));
      }
      if(CB4.isSelected()==true)
      {
        File f = new File(getClass().getResource("/PCycle/Civil.pdf").getFile());
        String source= f.getAbsolutePath();
        copy(source,(url+"\\"+CB4.getText()+".pdf"));
      }

      JOptionPane.showMessageDialog(this,"Completed");

      try {
            jProgressBar1.setValue(100);
            Thread.sleep(3000);
      } catch (InterruptedException ex) {
            Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex);
      }
      System.exit(0);
   }
}

Here I tried to implement a logic in such a that, whenever we call "copy" method it will copy the file from one location to another and before that it should run the timer method by which the progress on the jProgressBar is displayed.  But unfortunately even after using synchronized it is not displaying the progress for each file.

A: The problem is you are blocking Swing's Event Dispatching Thread (EDT).
Swing does all drawing when the EDT is not busy responding to events.  In this case jButton1ActionPerformed is not returning until all files have been copied.  So although a Timer is started during each copy() call, the timers never get a chance to expire, because jButton1ActionPerformed has never returned.
In this case, you want to use a SwingWorker to copy the files in a background thread.

*

*When you want to start copying the files:

*

*start the timer in the main thread

*create and start the SwingWorker.

*open a model dialog to block further user actions (or otherwise disable the UI)

*As the timer expires, your progress bar will advance, and be drawn.

*When the SwingWorker is done() (which is executed on the EDT),

*

*stop the timer

*dismiss the dialog (or re-enable the UI)

Note: Do not create or access any UI items, or create/start/stop timers, from the background worker thread.  These actions must only be performed on the EDT.

Rough example, showing disabling UI element, starting SwingWorker, publishing from the worker to show progress (which file is being download), enabling UI when the worker finishes.
File copy is faked using a 3 seconds sleep.
package progress;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class Download extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(Download::new);
    }

    private final JButton downloadBtn = new JButton("Start Download");
    private final JProgressBar progressBar = new JProgressBar();
    private final Timer timer = new Timer(200, this::timerTick);

    Download() {
        super("Download Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationByPlatform(true);

        downloadBtn.addActionListener(this::startDownload);
        add(downloadBtn, BorderLayout.PAGE_START);

        progressBar.setStringPainted(true);
        add(progressBar, BorderLayout.PAGE_END);

        setVisible(true);
    }

    private void startDownload(ActionEvent evt) {
        downloadBtn.setEnabled(false);
        timer.start();
        DownloadWorker worker = new DownloadWorker("File1", "FileB", "AnotherFile");
        worker.execute();
    }

    private void timerTick(ActionEvent evt) {
        progressBar.setValue(progressBar.getValue()+2);
    }

    private class DownloadWorker extends SwingWorker<Void, String> {

        private final String[] files;

        DownloadWorker(String ...files) {
            this.files = files;

            progressBar.setValue(0);
        }

        @Override
        protected Void doInBackground() throws Exception {
            for(String file : files) {
                publish(file);

                // Copy the file
                Thread.sleep(3000);  // Pretend copy takes a few seconds
            }
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            String file = chunks.get(chunks.size()-1);  // Just last published filename
            progressBar.setString("Downloading "+file + " ...");
        }

        @Override
        protected void done() {
            progressBar.setString("Complete");
            progressBar.setValue(100);
            timer.stop();
            downloadBtn.setEnabled(true);   // Re-enable UI
        }
    }
}


text:
Q: How to get a value from DataStore preferences, as Flow, within viewmodel i have a situation that I get resolved with SharedPreferences.
But now I'm migrating to kotlin and DataStore.
I faced this problem.
I have a String value stored in shared preferences, among other key-value pairs.
This String is an URL, to use in baseUrl parameter on a Retrofit call.
My problem is what's the correct way to retrieve the value, when I'm running in a ViewModel, of a Fragment.
This is part of my code:
@Singleton
class PreferencesManager @Inject constructor(
    @ApplicationContext context: Context,
    anioDao: AnioDao
) {

   val baseUrlFlow = dataStore.data
        .catch { exception ->
            if (exception is IOException) {
                Log.e(TAG, "Error reading preferences: ", exception)
                emit(emptyPreferences())
            } else {
                throw exception
            }
        }
        .map {
            it[PreferencesKeys.BASER_URL] ?: "http://192.168.2.109:1337"
        }

}

then in ViewModel class
class EnsayosViewModel @ViewModelInject constructor(
    private val ensayoRepository: EnsayoRepository,
    private val anioRepository: AnioRepository,
    private val localidadRepository: LocalidadRepository,
    private val epocaRepository: EpocaRepository,
    private val preferencesManager: PreferencesManager,
    private val agrotrackerApi: AgrotrackerApi,
    @Assisted private val state: SavedStateHandle

) :
    ViewModel() {

...

//Base Url
val baseUrlFlow = preferencesManager.baseUrlFlow
private val _baseUrl = MutableLiveData<String>()
private fun getBaseUrl() {

    viewModelScope.launch {
        baseUrlFlow.flowOn(Dispatchers.IO).collect{
            _baseUrl.value = it
        }
    }
}

  ...

fun fetchEsayosFromAT() {

 //This is where I want to get value of the base_url key.

}

But it seems to be very complex, for a simple task...
What I'm missing? I'm really lost.
Best Regards

A: One method of getting the shared preferences data is to transform Flow to LiveData. It works fine, but it is likely to be replaced with StateFlow/SharedFlow as a preferred method.

*

*create a method in the Preference repository returning Flow
override fun getBaseUrlPreferencesFlow(): Flow<String> = context.dataStore.data
.catch { exception ->
    if (exception is IOException) {
        Log.e(TAG, "Error reading preferences: ", exception)
        emit(emptyPreferences())
    } else {
        throw exception
    }
}
.map { pref ->
   it[PreferencesKeys.BASER_URL] ?: "http://192.168.2.109:1337"
}

*In your ViewModel init the LiveData as shown below (you can access this from ViewModel or Fragment)
val baseUrlLiveData: LiveData<String> =
yourInjectedRepository.getBaseUrlPreferencesFlow().asLiveData()

*(Optional) in ViewModel - add helper method to process the base url
private fun processUrl(): String {
  viewModelScope.launch {
       // base url http://192.168.2.109:1337
       val url = baseUrlLiveData.value
    }
}


text:
Q: SAP Crystal Report Visual Studio 2010 How can the parameter prompt in SAP Crystal Report be disabled? I'm using Visual Studio 2010.
My Code is:
{
    NPB.Report.CrLetter objCrLetter = new NPB.Report.CrLetter();
    NPB.Report.frmViewer objView = new NPB.Report.frmViewer();

    private void btnGenerateLetters_Click(object sender, EventArgs e)
    {
        objCrLetter.ParameterFields["LetterDate"].DefaultValues.AddValue(dtpLetterDate.Value.ToShortTimeString());
        objCrLetter.ParameterFields["Salutation"].DefaultValues.AddValue(cboboxSalutation.Text);
        objCrLetter.ParameterFields["Address"].DefaultValues.AddValue("2");
        objCrLetter.ParameterFields["City"].DefaultValues.AddValue("3");
        objCrLetter.ParameterFields["State"].DefaultValues.AddValue("4");
        objCrLetter.ParameterFields["ZipCode"].DefaultValues.AddValue("5");
        objView.crViewer.ReportSource = objCrLetter;
        objView.Show();
    }
}

A: I would probably change your code so that for each Parameter in the Crystal Report would clear the current & default values then pass in the correct value.
So you need to do something like this for each parameter:
ParameterDiscreteValue paramDV = new ParameterDiscreteValue();
paramDV.Value = "Parameter Value";
objCrLetter.ParameterFields["@ParameterName"].CurrentValues.Clear();
objCrLetter.ParameterFields["@ParameterName"].DefaultValues.Clear();
objCrLetter.ParameterFields["@ParameterName"].CurrentValues.Add(paramDV);

This should prevent the Parameter Prompt from appearing.

A: This answers are almost perfect, but, You should pay attention to the when setting de data source.
This setting should happens before you set the parameters.


text:
Q: What does it mean by "to begin my life with the beginning of my life" as in David Copperfield? Quote from the opening of David Copperfield by Charles Dickens:

Whether I shall turn out to be the hero of my own life, or whether that station will be held by anybody else, these pages must show. To begin my life with the beginning of my life, I record that I was born (as I have been informed and believe) on a Friday, at twelve o'clock at night. It was remarked that the clock began to strike, and I began to cry, simultaneously.

What does it mean exactly when he wrote "to begin my life with the beginning of my life"? Is it that David was beginning to write about his life like a biography (therefore "I" record ...) starting from the very beginning? Does it have anything to do with "my own life" in the very first sentence?
I could not find any resources analysing the book in detail while trying to look into the style of Dickens. I am not a native speaker of English and might be lacking in background. Thank you in advance for your help.

A: Your instinct is right: this is a mild word-play in which the narrator uses my life in a double sense to mean both

*

*the course of my life, all the important events which happened to me, and

*the literary work, my narrative of the events.
So the phrase you ask about may be understood as

To begin my life2 with the beginning of my life1 ...

A similar word-play is present in the first sentence, where hero is employed in the double sense of one who behaves heroically and the principal character in a work of fiction.

A: You could also say I begin my biography or the narration of my life with my birth.


text:
Q: Is any method can get current file path? Sorry for bothering with trivial things. For example abc.R is run under c:\temp. How to get the path inside the code? I am trying to avoid writing a fixed path, which can make it more dynamic. Thanks.

A: If you only want to find the current working directory, try having a look at ?getwd.


text:
Q: IntelliJ - Could not save project: null I have a Play/Scala project that I've imported into IntelliJ 13. Every now and then, the IDE will pop up with an error dialog that says Could not save project: null.
Sometimes restarting IntelliJ will fix the issue, but I'd really like to know the cause of it and how to stop it permanently. I'd include more details, but I'm not really sure what's relevant yet.

A: Might be that an exception happened during saving. Check the log (Help | Show log) to see if that is the case. Then report a bug with the log attached.


text:
Q: rigidity of representations of dehn fillings on the figure eight knot Consider a Dehn filling of the figure eight knot with coprime parameters (p,q) denoted by M.
I am interested in the representation space of M in $SU_2$.
I wonder wether all such representations are infinitesimally isolated or said differently
$H^1(M,Ad_\rho)=0$ for all non central $\rho:\pi_1(M)\to SU_2$.
The representation space of the figure eight knot is described (except for the 2 isolated solutions) by the curve
$$F(x,y)=cos(x)+1-cos(4y)+cos(2y)=0$$
where $x$ and $y$ are the angles of the meridian and the longitude respectively.
The question is equivalent to saying that the line of equation $px+qy=0$ meets transversely the curve $F(x,y)=0$.
This is clear for geometric reasons if $|p/q|<\sqrt{20}$ and can be proven for $|p/q|>\sqrt{20}$ by showing that the polynomial
$$\Phi=X^{2p}-X^{p+4q}+X^{p+2q}+2X^p+X^{p-2q}-X^{p-4q}+1$$
has simple roots except $-1$ if $p$ is odd and $\pm i$ if $4|p$.
This is a simple test which I ran with my computer for all $p<200$: the answer is yes. But I don't find a general argument. Any help is welcome!
Julien Marché
ps: of course a theoretical argument would be better but I don't know any.


text:
Q: How to retrieve the leaf children from JSON in Javascript? If I have a json object, and I don't really know how complex it is, I would like to restructure it as following example, how can I write it in Javascript?
Assume that I have a json object as following:
{
    "a": 1,
    "b": {
            "c": 2,
            "d": {
                     "e": 3
                  }
         }
    "f": {
            "g": 4
         }
}

Now, I would like to have following expected result:
{
   "a": 1,
   "b.c": 2,
   "b.d.e": 3,
   "f.g": 4
}

A: There is a library that looks to do the job if you can make use of them: https://www.npmjs.com/package/flat
Or something like:
let original = {
    "a": 1,
    "b": {
        "c": 2,
        "d": {
            "e": 3
        }
    },
    "f": {
        "g": 4
    }
}

function flattenObj(obj, parent = '', res = {}){
    for(let key in obj){
        let propName = parent ? parent + '.' + key : key;
        if(typeof obj[key] == 'object'){
            flattenObj(obj[key], propName, res);
        } else {
            res[propName] = obj[key];
        }
    }
    return res;
}

let response = flattenObj(original)

console.log(response)


text:
Q: Access env variables inside docker entrypoint script I want to pass environment variables in my docker run command and access them in my entrypoint shell script.
This is my super simple Dockerfile for test purposes:
FROM ubuntu:20.04

WORKDIR /

ADD entrypoint.sh .

RUN chmod 755 entrypoint.sh

ENTRYPOINT [ "/entrypoint.sh" ]

And this is the entrypoint.sh:
#!/bin/sh

printf "env var TEST = ${TEST} "

I just build the Dockerfile like this: docker build -t test:1.0 .
And then run it like this: docker run -i test:1.0 -e TEST='Hello world'
Unfortunately the output is not containing the env var.

A: For the record: Predefining the variables is not the solution.
The order of the args is important, like David Maze said.
# incorrect
docker run -i test:1.0 -e TEST='Hello world'

# correct
docker run -i -e TEST='Hello world' test:1.0

A: Something like this will work:
entrypoint.sh
#!/bin/sh
echo $MYVAR

Dockerfile
FROM alpine:3.15.4
WORKDIR /home/app
COPY ./entrypoint.sh .
ENV MYVAR=""
ENTRYPOINT ["/bin/sh", "/home/app/entrypoint.sh"]

And then you can build & run the container while setting the environment variable with:
$ docker build -t test . && docker run -e MYVAR="hello world" test


text:
Q: require.js and refactoring for unit testing overview
guys, recently I want to refactor my simple project, and I read some article about how to write testable javascript.
The basic idea I got is: to make data abstraction using constructor and selector (principle in SICP), but now because of the single pattern of require.js, I don't know how to organize my project.
detail about the project
Here is the details:
The project is Tic-Tac-Toe with unbeatable AI. I implement it and decompose it into several part using require.js
The github address is: hit me
new thought
And right now: I begin to rewrite it, here is my new thought:
I create a game.js file for the whole game object and code is:
This is game constructor
function Game(pureCells) {
    this.currentPlayer = turnEnum.secondPlayer;
    this.board = this._createBoard(pureCells)
}

and I have some action function on it's prototype, here just list two:
Game.prototype.changeTurn = function changeTurn(){
    this.currentPlayer = - this.currentPlayer;
    if(currentPlayer == turnEnum.firstPlayer){
        if(document.board.real[1].checked) perfectMove();
    }else {
        if(document.board.real[0].checked) perfectMove();
    }
}

Game.prototype._createBoard = function(pureCells) {
    var allCells = []
    _.each(pureCells, function(el, i){
        allCells.push(new CellConstructor(el))
    })

    var board = new BoardConstructor(allCells)
    return board
}

And the board.js file is the same structure:
function Board(el) {
    this.element = el
    this.state = this._getState()
    this.winner = this._detectWin()
}

Board.prototype._getState = function() {
    var state = [];
    _.each(this.element, function(cell, i){
        state.push(cell.element.value)
    })

    return state;
}

Board.prototype.isFull = function(){
    if(_.contains(this.state, ''))
        return false
    return true
}

And you can see that the board is one of the dependency of game.
The problem
Here I want to describe my problem:
Actually I have another file cell.js is also the same structure.  it's one of the dependency of board.
So now I want to use some function in both game and board, for example, when I handle the click event of cell, I need to detect the state of the board, and this function is in board.
first, I don't want to make circle dependency,
second, even though I inject board and game into cell.js file, but the instance I create will not the same with the one I will create in the main.js( the main file of require.js)
give a hint
So sorry for the long description, and thank your patience for reading it. Please give some hint or advice! Thank you very much!

A: shared.js -- no dependencies:
var sharedObj = {};
var sharedFunc = function () {}

define ({
    sharedObj: sharedObj,
    sharedFunc: sharedFunc
});

shared.js -- dependencies:
define(["dep1", "dep2"], function(dep1, dep2) {
    var sharedObj = {};
    var sharedFunc = function () {}

    return {
        sharedObj: sharedObj,
        sharedFunc: sharedFunc
    };
});

main.js:
requirejs(["shared", "cell"], function(shared, cell) {
    shared.sharedFunc();
    shared.sharedObj.something = "whatever";
    cell.someFunc();
});

cell.js
define(["shared"], function(shared) {
    function someFunc() {
         // you can do something with shared.sharedObj.something here
         // or call shared.sharedFunc() here
    }

    return {
        someFunc: someFunc
    };
});


text:
Q: How to overwrite workbook file with Apache POI? My code is as simple as below. I just create a xlsx workbook, save it to a file. Then I reopen it from the file, make some changes and try to overwrite it.
    Workbook wb = new XSSFWorkbook();
    wb.createSheet("test");

    wb.write(new FileOutputStream("file.xlsx"));
    wb.close();

    // works fine until this point

    wb = WorkbookFactory.create(new File("file.xlsx"));
    wb.createSheet("test2");

    // fails with "Unexpected end of ZLIB input stream"
    wb.write(new FileOutputStream("file.xlsx"));
    // wb.write(new FileOutputStream("file2.xlsx")); // works fine and creates both files
    wb.close();

The initial creation of the file goes ok. I tested pausing the code and opened the file in Excel to make sure it's valid.
I can open the recently created file and make changes. The problem happens on overwrite (wb.write). I get org.apache.poi.ooxml.POIXMLException: java.io.EOFException: Unexpected end of ZLIB input stream. The file becomes 0 byte.
Strangely, if I do wb.write(new FileOutputStream("file2.xlsx")); instead of wb.write(new FileOutputStream("file.xlsx")); everything works fine. Both files file.xlsx and file2.xlsx are created and have the changes applied. This was pointed here.
Also, the problem is not about opened streams or such. Because if I execute only the second part of the code after the file already exists and is valid it also fails.


text:
Q: Multidata trigger condition for listbox to check if an item is selected I want to disable a button if there are no items in the listbox.
I am now confused on which property I should check in the Multidata trigger condition for the listbox in order to check whether there is any element in the listbox. Please help.
<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding ElementName=JobItemsListBox, Path=ItemsSource}"
                   Value="">
        </Condition>
    </MultiDataTrigger.Conditions>
    <Setter Property="IsEnabled" Value="False" />
</MultiDataTrigger>

A: qqww2 comment is correct -- this works
<Style TargetType="Button">
    <Setter Property="IsEnabled" Value="True" />
    <Style.Triggers>
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding ElementName=listBox1, Path=Items.Count}" Value="0" />
            </MultiDataTrigger.Conditions>
            <Setter Property="IsEnabled" Value="False" />
        </MultiDataTrigger>
    </Style.Triggers>
</Style>


text:
Q: System of Three Equations - Prove that at least two numbers' absolute value is equal. Question :

Prove that at least two of the numbers $a,b,c$ must have the absolute values equal in order that the system of following equations in $x,y$ may be consistent
$$ a^2x+b^2y+c^2=0$$
$$a^4x+b^4y+c^4 =0$$
$$x+y+1=0$$

I found $x=\frac{c^2(b^2-c^2)}{a^2(a^2-b^2)}$ and $y=\frac{c^2(c^2-a^2)}{b^2(a^2-b^2)}$ from first two equation.
After putting $x$ and $y$ in $3rd$ equation.
$$\frac{c^2(b^2-c^2)}{a^2(a^2-b^2)}+\frac{c^2(c^2-a^2)}{b^2(a^2-b^2)}+1=0 $$
I did prove it but I am not satisfied with the process as I have to use an identity(never seen and found in the simplification)$$a^2b^2(a^2-b^2)+b^2c^2(b^2-c^2)+c^2a^2(c^2-a^2)=-(a^2-b^2)(b^2-c^2)(c^2-a^2)$$ and the simplification nearly took 30 minutes(which is not good in exam)
Is there any other fast and efficient way to prove or simplify this ?

A: $$a^2x+a^2y+a^2=0$$
$$\implies (a^2-b^2)y+(a^2-c^2)=0$$
$$a^4x+a^4y+a^4=0$$
$$\implies (a^4-b^4)y+(a^4-c^4)=0$$
If $|a|\neq |b|$ and $|a|\neq |c|$, then ${a^4-b^4\over a^2-b^2}={a^4-c^4\over a^2-c^2}$ which imlies $a^2+b^2=a^2+c^2$ which is $|b|=|c|$

A: As $$\begin{pmatrix}1&1&1\\a^2&b^2&c^2\\a^4&b^4&c^4\end{pmatrix}\begin{pmatrix}x\\y\\1\end{pmatrix}=\begin{pmatrix}0\\0\\0\end{pmatrix},$$
the matrix must be singular, i.e., a non-trivial linear combinations of the rows is zero, i.e., there are numbers $\alpha,\beta,\gamma$, not all $=0$, such that the polynomial $$
\alpha+\beta t+\gamma t^2$$
has at least three roots $a^2,b^2,c^2$. But such a quadratic (or perhaps even linear) polynomial cannot have more than two distinct roots.
Hence two of these squares must be equal, hence two of $a,b,c$ differ by at most a factor of $-1$ (and therefore have the same absolute value).


text:
Q: cloud_firestore android:foregroundServiceType not found Getting the following issue when trying to run my Flutter app on Android. Below are the files as well. Any thoughts? I've had to upgrade my cloud_firestore along side the other Firestore packages I've been using. All of the packages are listed below.
Launching lib/main.dart on Pixel 3 XL in debug mode...
lib/main.dart:1

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDevDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /Users/zee/Repos/bazaaroh/build/app/intermediates/packaged_manifests/devDebug/AndroidManifest.xml:115: AAPT: error: attribute android:foregroundServiceType not found.
2

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 8s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin cloud_firestore...
Exception: The plugin cloud_firestore could not be built due to the issue above.

build.gradle
buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.1'
        classpath 'com.google.gms:google-services:4.3.4'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
        classpath 'com.google.firebase:perf-plugin:1.3.1' // Performance Monitoring plugin
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}
configurations.all {
    resolutionStrategy {
        "androidx.core:core:1.0.2"  //Update to "androidx.core:core:1.1.0"
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app/build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
def flutterVersionName = localProperties.getProperty('flutter.versionName')

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.firebase.firebase-perf'

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        minSdkVersion 28
        targetSdkVersion 29
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        /*64 Build issue*/
        ndk {
            // Set up a supported SO library framework
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'//, 'mips', 'mips64'
        }
        /*64 Build issue*/
        multiDexEnabled true
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']

            firebaseCrashlytics {
                nativeSymbolUploadEnabled true
            }
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled true
            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    // Specifies the flavor dimensions.
    flavorDimensions "app"
    productFlavors {
        dev {
            dimension "app"
            applicationId "com.app.bazaaroh"
        }
        prod {
            dimension "app"
            applicationId "com.app.bazaaroh"
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
    implementation 'androidx.multidex:multidex:2.0.0'
    implementation 'com.android.support:multidex:1.0.1'

    // (Recommended) Add Analytics
    implementation 'com.google.firebase:firebase-perf:19.0.1'
    implementation 'com.google.firebase:firebase-crashlytics:17.3.0'
    implementation 'com.google.firebase:firebase-analytics:18.0.1'
    implementation 'com.google.firebase:firebase-crashlytics-ndk:17.3.0'
}
apply plugin: 'com.google.gms.google-services'

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.bazaaroh">

    <uses-permission android:name="android.permission.INTERNET"/>
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
    <application
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <meta-data
                android:name="flutterEmbedding"
                android:value="2" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_action_name" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/custom_cyan" />

        <meta-data android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_api_key"/>

        <meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>

        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                    "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.yalantis.ucrop.UCropActivity"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

    </application>
</manifest>

pubspec.yaml
algolia: ^0.1.7
cupertino_icons: ^0.1.3
carousel_pro: ^1.0.0
carousel_slider: 2.1.0
cloud_firestore: ^0.16.0
device_info: 0.4.2+4
firebase_auth: ^0.20.0+1
firebase_core: ^0.7.0
firebase_messaging: 6.0.15
firebase_storage: ^7.0.0
flare_flutter: ^2.0.3
flutter_cache_manager: ^1.1.3
flutter_facebook_login: 3.0.0
flutter_image_compress: 0.7.0
font_awesome_flutter: 8.5.0
# geoflutterfire: ^2.1.0
google_maps_flutter: 0.5.21+15
google_sign_in: ^4.5.3
image_cropper: ^1.1.2
image_picker: 0.6.7+6
cached_network_image: ^2.0.0
intl: ^0.16.1
keyboard_visibility: ^0.5.6
liquid_pull_to_refresh: ^1.1.1
location: 3.2.1
modal_progress_hud: ^0.1.3
package_info: 0.4.0+18
photo_view: ^0.9.2
provider: ^4.0.1
pub_semver: 1.4.4
rxdart: ^0.23.1
shared_preferences: 0.5.7+3
sign_in_with_apple: 2.5.2
simple_moment: ^1.0.4
url_launcher: 5.4.1


text:
Q: postfixadmin error Table 'postfixadmin.config' doesn't exist I am trying to get postfixadmin to work on my Ubuntu 17.10 system. This is the error I am getting:
DEBUG INFORMATION:
Invalid query: Table 'postfixadmin.config' doesn't exist

Check your error_log for the failed query.

Please check the documentation and website for more information.

the /var/log/apache2/error_log shows some permission denied error:
[Sun Apr 15 01:11:16.468872 2018] [php7:warn] [pid 3513] [client 76.80.54.221:55168] PHP Warning:  session_start(): open(/var/lib/php/sessions/sess_otkuleekb07jjoab4q7utomggc, O_RDWR) failed: Permission denied (13) in /usr/share/postfixadmin/common.php on line 26
[Sun Apr 15 01:11:16.468894 2018] [php7:warn] [pid 3513] [client 76.80.54.221:55168] PHP Warning:  session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /usr/share/postfixadmin/common.php on line 26
[Sun Apr 15 01:11:16.468922 2018] [php7:warn] [pid 3513] [client 76.80.54.221:55168] PHP Warning:  session_destroy(): Trying to destroy uninitialized session in /usr/share/postfixadmin/common.php on line 30
[Sun Apr 15 01:11:16.468945 2018] [php7:warn] [pid 3513] [client 76.80.54.221:55168] PHP Warning:  session_start(): open(/var/lib/php/sessions/sess_otkuleekb07jjoab4q7utomggc, O_RDWR) failed: Permission denied (13) in

A MySQL database for postfixadmin has been started, but the script did not add any tables.
How can I fix this?

A: I found that running https://yourdomainname/postfixadmin/setup.php helped me find the problem. And that in fact the table config was missing, because the install process never got triggered. It was using setup.php that made things start to fall in place.


text:
Q: highcharts.js - Dynamic Label Color Is it possible to change the label color when gauge color changes?
Here is my js fiddle - the requirement is to color the number the same way as the gauge:
http://jsfiddle.net/e76o9otk/735/
dataLabels: {
            format: '
{y}
' +
                   '
'
        }

A: Use the formatter callback function to include logic in the label text like this:
dataLabels: {
  formatter: function() {
    let color = ''
    if (this.y > 50) {
      color = '#55BF3B' //green
    } else if (this.y > 10) {
      color = '#DDDF0D' //yellow
    } else {
      color = '#DF5353' //red
    }
    return '
' + this.y + '
' + '
'
    },
  }

Working JSFiddle example: http://jsfiddle.net/ewolden/x6j1ywdb/

If you want the dataLabel to be a gradient, you can implement (or borrow) a gradient function, such as this one: Programmatically Lighten or Darken a hex color (or rgb, and blend colors)
Working JSFiddle example: (with gradient dataLabels): http://jsfiddle.net/ewolden/x6j1ywdb/12/


text:
Q: New laptop screen only works for 1 second after resolution changes After smashing my old laptop LCD, I ordered a replacement part from a dismantled 2nd hand laptop. I attached the screen, and the first time I turned it on the screen worked perfectly. Since a reboot however, the screen flicks on for around 1s after boot, and then becomes blank / black. No backlight is on and no image is visible on the screen.
If I use an external monitor to change the resolution of the laptop screen using Xrandr, both screens flicker and the laptop again becomes visible for a very short time, before returning to black.
When I plug back in my old smashed LCD, the screen works fine apart from being smashed - it doesn't go black and I can use it normally.
The laptop is a Dell Inspiron 15. Does anyone know what I can do? Is this a hardware issue or a driver issue?
Thanks for the help!

A: I believe your new-old spare screen is damaged. My asumption is based on that your old screen works, shattered but works and your new screen works only for a brief period of time any time the connection is reset, so I think it's realted to the guts of the screen, probably some capacitor has gone bad.
One thing that's not clear to me, Does the external monitor also turn off to when the built-in screen turns off?
@Sam To clarify, the external monitor stays on and so I am able to use it as a "desktop" of sorts. The laptop screen goes black when the monitor is on. Thanks for the help, and I am happy to accept your last comment as an answer if you post it.
Having that information, sadly I'm sure your spare screen is bad the only two thing you can do is to test the board(painfully long process) or change it.
Cheers.


text:
Q: Duplicate columns values to fit column names array I would like to duplicate u to fit d_range. In clear i would like to put d_range in column names and repeat values as needed to fit the array. In this case the d_range is
     DatetimeIndex(['2019-06-24', '2019-06-25'], dtype='datetime64[ns]', freq='D')
current output:
      balance
BTC     5000
ETH    10000
BCH     1046

my code:
d_range = pd.date_range(start= datetime.combine(datetime.today() - timedelta(days=1), datetime.min.time()),   end= datetime.combine(datetime.today() , datetime.min.time()) )
currency = np.array(['BTC','ETH','BCH'])
u = np.array([5000,10000,1046])
cl_bal = pd.DataFrame(u, index= currency, dtype= int)
cl_bal.columns = ['balance'] * len(cl_bal.columns)

A: Use MultiIndex.from_product with np.repeat:
cl_bal = pd.DataFrame(np.repeat(u, len(d_range)),
                     index= pd.MultiIndex.from_product([currency, d_range]),
                     dtype= int)
print (cl_bal)
                    0
BTC 2019-06-24   5000
    2019-06-25   5000
ETH 2019-06-24  10000
    2019-06-25  10000
BCH 2019-06-24   1046
    2019-06-25   1046


text:
Q: How add Expires headers on Css.php file (Scaffold) I use SocialEngine for my website, I want to speed my website so I have use Gtmetrix and PageSpeed to see what I can improve
I see that Add Expires headers have 0/100 ..
I have do research but how I can add on Exprires headers my CSS that look like this  ..
https://www.exemple.com/application/css.php?request=application%2Fthemes%2Fmytheme%2Ftheme.css&c=2174&pageStart=332433&pageEnd=85951
https://www.exemple.com/application/css.php?request=application%2Fthemes%2Fmytheme%2Ftheme.css&c=2174&pageStart=667827&pageEnd=345656
https://www.exemple.com/application/css.php?request=application%2Fthemes%2Fmytheme%2Ftheme.css&c=2174&pageStart=1019386&pageEnd=6576458

How I can do ? Thank you
My .htaccess:
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>

Themes /application/themes/* We utilize a framework called CSS
  Scaffold which makes editing your community's theme a simple process.
  Each theme is stored in its own directory within
  /applications/themes/. A default theme is automatically loaded when
  you first install SocialEngine. Each theme contains two files:
  constants.css and theme.css.
At the top of constants.css, you'll find a series of global CSS
  settings (called "constants"). You can edit these to adjust the
  colors, fonts, and other styles throughout your entire community.
The other file, theme.css, contains more specific styles that are used
  throughout your community. Many of these styles inherit values from
  constants.css. If you want to override any of the default styles on
  your community, you can edit them here. If they aren't present in
  theme.css (and are being loaded from outside the theme itself), you
  can override them by adding new styles to the bottom of theme.css.
More information about how to work with CSS Scaffold is available on
  Github or Google for CSScaffold for videos and tutorials.

A: You already have configured
ExpiresByType text/css "access 1 month"

so CSS files should have the correct header.
It seems, that application/css.php delivers the appropriate CSS file. In order to trigger the expires header, the script must also set the correct mime type for the CSS files returned.
This can be accomplished with a header of Content-Type
header('Content-Type: text/css');

Alternatively, you could also add your own Expires header, e.g.
$plus_month = date('r', strtotime('+1 month'));
header("Expires: " . $plus_month);


text:
Q: jQuery Promises and Deferred, confusion I thought I'd finally got my head around promises but it seems I'm straying a little.
Can anyone put me out of my misery and explain what I'm doing wrong here:
t010 = {
      myGet: function(url) {
        var result = new $.Deferred();
        result.resolve(ajaxRequest(url));
      }
    }
Which is then called by my main method as so:
$.when(t010.myGet(seatId), t010.myGet(roomId)).then(function(d1, d2) {
  console.log(d1);
}
I just console log undefined every time.
I think what i'm trying to achieve is fairly obvious, I want to call myGet twice and when both are complete do something with the results.
Thanks all!

A: You have to return the promise to use $.when
t010 = {
  myGet: function(url) {
    var result = new $.Deferred();
    result.resolve(ajaxRequest(url));

    return resolve.promise();
  }
}

but that resolves the promise immediately, passing back the result of the ajaxRequest function, which is probably undefined at that time?
But, the ajaxRequest already looks like it returns a promise, you can return it directly
t010 = {
  myGet: function(url) {
    return ajaxRequest(url));
  }
}

assuming your ajax function looks something like
function ajaxRequest(url) {

    return $.ajax({
        url : url
    });

}


text:
Q: Optical receiver output voltage higher than power supply The part is a optical receiver from Broadcom. It has TTL output, but specified with a maximum output-high voltage higher than the power supply. I wonder what's special structure internal may make it goes beyond the power supply. As known, it's not good to do this in digital design.

A: With a low impedance source rated for TTL compatible output, it is easy to get overshoot from reactive probe and ground impedance.  This is no cause for concern.
Measurement errors may be avoided with 10:1 probe tip and ring near output.


text:
Q: error in attribute extended from trait in scala i am using scala and i have a trait with an attribute "name" i extended this trait in Userclass where i am accessing the attribute
 when i tried to declare name in the trait like this
val name : String

it gave error in child class that child class ha unimplemented member
but when i tried
val name : String = ""

it just worked fine
please tell me the difference and reason why it was not working before and why it worked after the modification

A: I'm assuming your code looks something like this:
trait hasName {
  val name : String
}

class Person extends hasName

A trait is, by nature, abstract, which means that it allowed to have unimplemented methods.  In effect, what the trait is declaring is this:

All classes extending hasName are guaranteed to have a val name : String instance variable.  What is in that variable is dependent on the actual child class

In the case above, your code is expanded to:
trait hasName {
  val name : String = ???
}

where the ??? means essentially that the particular 'function' is unimplemented.
After your modification:
trait hasName {
  val name : String
}

class Person extends hasName {val name : String = ""}

The extending class, Person overrides the hasName trait's implementation, or in this case, lack thereof, with its own implementation.
Alternatively, if you do:
trait hasName {
  val name : String = ""
}

You are adding an implementation to hasName, so every child class will, by default, have that implementation.


text:
Q: error C4703: potentially uninitialized local pointer variable 'pNamesPtr' used I'm working on a crypter project and  ran into the following error when attempting to compile the program.

main.cpp(520): error C4703: potentially uninitialized local pointer
  variable 'pNamesPtr' used
  ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

        DLLNAMES[i].UsedAlready = 0;
    }

    *dwOutSize = (DWORD)pNamesPtr - (DWORD)pBuffer;//*<----is line 520 of error
    *dwImportsSize = *dwOutSize - *dwIATSize;
    return pBuffer;
}
#pragma pack(1)
typedef struct

Can someone help me with this error? Do you need more code in order to have a good answer?

A: This warning isn't always a bug, sometimes its just the result of an optimization. Since it is in your code and you don't know what is this it might actually be a bug.
For example if I write:
int i;

if (this_and_that)
    i = 5;

if (whatever)
    printf("%d\n", i);  // <--- this may give a potential blahblah warning

If you are optimizing then you may know that the value of whatever is always true when the value of this_and_that is true so if printf gets called then i is already guaranteed to be initialized but the compiler often can not figure out the relation between this_and_that and whatever, this is why you get the warning. One possible quick fix to this warning is initializing the variable to a default value right where you declare it. In my opinion sparing with initialization is a bad practice and a source of a lot of bugs.

A: It means that

*

*you don't initialise pNamesPtr when you declare it, so it starts with an invalid value; and

*the compiler can't be sure that you will have assigned a valid value to it before using it.

Check all the code paths from the declaration to the point of use. Do they all assign something sensible to the variable? If not, fix it so they do.
If they do, and you're convinced that you're assigning it correctly, could you simplify the code so that it's obvious to the compiler that it is?
If all else fails, then you could silence the compiler by initialising it to nullptr or some other default value in the initialisation. But only do that if you're really sure your code is correct - compilers are usually good at spotting mistakes like this.

A: This error mean that compier don't know if used variable have assigned value.
For example:
int i;
if( someBool )
    i= 123;
someFunction();
if( someBool )
    printf("%d", i );

If someFunction() change value of someBool then you may end up calling printf with i argument while i doesn't have any value assigned.
If you are sure that your code is correct you may disbale that error in Visual Studio by putting at the top of your cpp file line:
#pragma warning (disable: 4703)

Or you may disable that check for whole project by going to Properties / C/C++ /  General / SDL checks and set it to No (/sdl-).
Alternatively if you don't care about performance you may just assign anything to pNamesPtr where it's defined.

A: Put this in your code:
xtype *pNamesPtr = NULL


text:
Q: SharePoint 2013 Searching multiple Site collections? Is there a Search or Portal site Hierarchy/ Structure option in SharePoint 2013 that would enable a searching of specific and multiple site collections (not just Search all)
We opened a ticket with Microsoft O365 and they said this is not possible without custom development and that search queries can't span multiple Site collections.
Is this true?

A: It depends what exactly you want, but yes that is entirely possible.
You want to add to your search query the term:
path:http(s)://domain/path/to/site/collection
That will restrict your results to only include results who's url contains the path specified, or in other words, who are part of the specified site (or site collection) or it's sub-sites. To search multiple site collections at once, use:
(path:http://domain/site1 OR path:http://domain/site2 OR path:http://domain/site3)
If you want to save patterns like this, you can save it as a Result Source, either in central admin (does o365 give you a central admin? I'm too used to on premises) or in site settings for a specific site collection. If you need it to be accessible from a number of places, but can't set it application wide, set up a new search centre site collection, create the result source there, and set each of the other site collections you want to use that result source to send queries to the search centre (under Search Settings in Site Settings)

A: That is O365, limitation and limitation.
Did you try Search Results Web Part. You need to configure it and it will return the results on the base of query. I know its not solution but still little alternate.
http://office.microsoft.com/en-us/support/sharepoint-help/sharepointsearch/about-configuring-the-search-results-web-part-HA102848383.aspx


text:
Q: jquery cascaded focus and change function not working with textfield Help! Function below is working with the dropdown (rubriekskeuze) but not with the textfield (plaatsnaam).
$("#rubriekskeuze,#plaatsnaam").focus(function () {
    //Opslaan huidige waarde
    if (this.id == 'plaatsnaam'){var originele_plaatsnaam = this.value;}else {var originele_rubriek = this.value;}
   }).change(function() {alert('plaa');
        if (this.id == 'rubriekskeuze' && vraag_categorieupdate_gesteld == 0){
            var vraag_update_rub = confirm("Weet u zeker dat u de rubriek wilt wijzigen, bij wijzigen komen de nu ingevulde kenmerken te vervallen en moeten deze opnieuw ingevuld worden voor de nieuwe rubriek");
        }
        if (vraag_categorieupdate_gesteld == 1 || vraag_update_rub){
            alert('dd');
        }
   });

A: Figured it out! It didn't work because of the autocomplete in the textfield...