text:
Q: Why do objects stop cooling down / losing heat? Complete beginner on the physics of heat absorption / loss, so bear with me.  When I make a hot beverage, it starts out hot, but then gradually cools down as it loses heat.  However, it eventually stops cooling down, or else it would reach the impossible temperature of absolute zero.  My question is why do objects stop losing heat?
My best guess is that it enters into a type of chemical equilibrium with the atmosphere.  Am I thinking along the correct lines here?

A: When two objects/systems have the same temperature, they can be said to be in thermal equilibrium, and this means that there will be no net heat transfer between them.  I cannot further emphasize how important the word net here is.
 This means that there is heat transfer, but heat transferred from system A to B equals to heat transferred from system B to A, so they remain at the same temperatures.

chemical equilibrium with the atmosphere.

It is thermal equilibrium here, not chemical.  Hence to conclude, an object never stops losing heat, but will stop losing net heat when it achieves thermal equilibrium with the atmosphere.

A: I'd like to point something out that the other answers are glossing over (understandably; this is somewhat of a small detail).
As mentioned; heat transfer is proportional to temperature difference.  As the object cools; the temperature decreases and less heat is transferred.
So consider the process as it plays out.  As the object approaches the temperature of the surroundings, it begins to cool less.  This process actually creates an exponential decay; where the hot cup temperature approaches the value of the surroundings temperature; but only reaches it after a very long time.
(Note: with the usual large scale engineering heat transfer models, it would reach that temperature after infinite time, but there may be higher order/microscopic effects which may make that not apply)
So the reason your object doesn't go to absolute zero is because the cooling doesn't even reach room temperature very fast.  It may cover 99% of the distance relatively quickly; but the cooling speed will continue to slow down as it approaches this equilibrium.

A: heat transfer is driven by temperature differences. once your beverage cools down to a temperature equal to that of its surroundings, heat transfer stops.

A: Cooling is loss of heat, and that heat goes elsewhere (your hand
around the cup, the warm air rising above the beverage...).
Other objects lose heat too, any of which can go into your beverage.   Heat is never destroyed (by the second law of thermodynamics), so
it is unsurprising that your beverage doesn't approach absolute zero.
Other objects lose heat too, any of which can go into your beverage.
The temperature balance will eventually be reached with any objects
that have a thermal connection to the beverage, and that (by definition,
or 'the zeroth law' of thermodynamics) means zero temperature difference.
It does not imply zero temperature, rather zero expected heat
exchange (gain or loss).

A: The basic reason for this is probability. The situation where two objects have the same temperature is the most likely state of the system, subject to the constraint that the energy of the total system (for example your room) is constant. This is the macroscopic state with the maximal number of microstates. Let us call this number the multiplicity $\Omega$.
This number is the product of the multiplicity of the cup and the multiplicity of the rest of the room: $\Omega = \Omega_{cup} \times \Omega_r$. The multiplicities depend very strongly on the internal energy $E$. When the cup is hot, energy is transferred to the room because the fractional increase in $\Omega_r$ is greater than the fractional decrease of the multiplicity of the cup. This makes that the total $\Omega$ increases.
Eventually, thermal equilibrium will be reached, the most probable macrostate, the state with the highest multiplicity. Then the fractional changes of $\Omega$ of the cup and of the room are equal and opposite when a small amount of energy is transferred between them. For example when the multiplicity of the cup goes up by one promille, the multiplicity of the room goes down by one promille, leaving the product unchanged at its maximum.
This is what temperature is. When two systems have the same temperature, they have the same relative change of multiplicity with energy $\frac{1}{\Omega}\frac{{\rm d}\Omega}{{\rm d}E}$. At room temperature this is about 4 % per milli-eV.
For the cognoscenti: with the definition of entropy $S = k \ln\Omega$ and $\frac{dS}{dE} = \frac{k}{\Omega} \frac{d\Omega}{dE} = \frac{1}{T}$ we recognize the fractional change of $\Omega$ with energy as the thermodynamic beta (coldness) $\beta = \frac{1}{kT} =\frac{1}{\Omega}\frac{{\rm d}\Omega}{{\rm d}E}$.


text:
Q: Python Popen WHOIS OS command fail test Prefacing this with the text 'just another beginner'. when you have the result of a whois command via the Popen command, how do you test if its good ?
Normally when Python returns a list of whatever you can test the length of it and that has usually sufficed for me, but this is a little more arbitrary.
eg
im testing for a domains country of origin, but sometimes the domains that gethostbyaddr gives me are not recognised by the WHOIS server. So, i thought i would go with sending it an ip in case of failure but I've ended up with this not so pretty less than 70 characters test. Just wondering if anyone knows what the 'standard' way of doing this is.
w = Popen(['whois', domain], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
                whois_result = w.communicate()[0]
                print len(whois_result)
                if len(whois_result) <= 70:
                        w = Popen(['whois', p_ip], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
                        whois_result = w.communicate()[0]
                        print len(whois_result)
                        if len(whois_result) <= 70:
                                print "complete and utter whois failure, its you isnt it, not me."
                        test = re.search("country.+([A-Z].)",whois_result)
                        countryid = test.group(1)

A: To answer your direct question, look for this string in the output of a whois command to see whether there was a problem...

No match for "insert_domain_here"

To address other meaningful issues to your task... your Popen command is going at things the hard way... you don't need a PIPE for stdin and you can call .communicate() directly on the Popen to make this a bit more efficient... I rewrote with what I think you have in mind...
from subprocess import Popen, PIPE, STDOUT
import re

## Text result of the whois is stored in whois_result...
whois_result = Popen(['whois', domain], stdout=PIPE,
    stderr=STDOUT).communicate()[0]
if 'No match for' in whois_result:
    print "Processing whois failure on '%s'" % domain
    whois_result = Popen(['whois', p_ip], stdout=PIPE,
        stderr=STDOUT).communicate()[0]
    if 'No match for' in whois_result:
            print "complete and utter whois failure, its you isnt it, not me."
    test = re.search("country.+([A-Z].)",whois_result)
    countryid = test.group(1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Asynchronous process runner with inputstream reader using Futuretask I'm trying to run an asynchronous process and getting its inputstream (if there is).
This is my code:
    CommandCall commandCall = new CommandCall(commands);
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Integer> task = executor.submit(commandCall);

and this is the process run Task
public class CommandCall implements Callable<Integer> {

    private byte[] output;
    private int retval=-1;
    private String[] commands=null;
    Process process=null;

    public CommandCall(String[] commands) throws Exception {
        this.commands=commands;
        this.output=null;
    }

    public void destroy() {
        try {
            if(process!=null) process.destroy();
        }catch(Exception e){}
    }

    public byte[] getByteArray() {
        return output;
    }

    public int getRetval() {
        return retval;
    }

    @Override
    public Integer call() throws Exception {
        try{
            process = new ProcessBuilder(commands).start();
            // here i must read the process input and store it to this.output
            // this must be a non lockable read because the process can be without any output
            retval= process.waitFor();
        }finally{
            try{
                if(bos!=null) bos.close();
            }catch(Exception e){}
        }
        return retval;
    }

}

I can't get the process output, please mind 2 very important thing:

*

*Process must be async because I need to manage a timeout

*Process's InputStream can be optional and must not lock the thread waiting for content: there can be a process without any output.

UPDATE
I'm trying this version...  seems to work but I don't know if it is strong enought.
@Override
public Integer call() throws Exception {
    InputStream is=null;
    try{
        process = new ProcessBuilder(commands).start();
        is=process.getInputStream();
        int len;
        int size = 1024;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[size];
        while ((len = is.read(buf, 0, size)) != -1)
            bos.write(buf, 0, len);
        output = bos.toByteArray();
        retval= process.waitFor();
    }finally{
        try{
            if(is!=null) is.close();
        }catch(Exception e){}
    }
    return retval;
}

A: The behavior that is observing the process' output should be itself in an own thread. Once the process is terminated, this thread should be terminated, too.
So basically you can do this:
@Override
public Integer call() throws Exception {
    Thread outputObserver = null;

    try(ByteArrayOutputStream  baos = new ByteArrayOutputStream()) {
        this.process = new ProcessBuilder(commands).start();
        outputObserver = new OutputObserver(process.getInputStream(), baos);
        outputObserver.start();
        this.retval = process.waitFor();
        this.output = baos.toByteArray();
    }finally{
        if(outputObserver != null) outputObserver.interrupt();
    }

    return this.retval;
}

private static OutputObserver extends Thread {
    private final InputStream input;
    private final OutputStream output;

    OutputObserver(InputStream input, OutputStream output) {
        this.input = input;
        this.output = output;
    }

    @Override
    public void run() {
         while(!Thread.interrupted()) {
             // Copy bytes from input to output here (handling any exceptions).
             // Maybe use 3rd party libs for that.
         }
         // Make sure to copy remaining bytes here, too.
    }
}

A couple of notes:

*

*I did not test any code. Maybe I made some subtle mistakes, but the direction should be clear.

*Usually I would not extend Thread but rather implement Runnable. I simply wanted to not over-complicate things.

*I did not provide code for copying bytes from an input stream to an output stream. If you need help on this, do a little search in the web. You will find many solutions.


text:
Q: Unset document element in Mongo CXX I have a class that has a bsoncxx::document::view view as a private attribute, and a method that get a document from the Mongo database and save the result in the local bsoncxx::document::value value variable and then get the view from the value.view() and save it in the class bsoncxx::document::view view variable:
const bool User::search_one_by_id(const std::string &id = "")
{
    // The prototype of the method below: const std::tuple<bool, bsoncxx::document::value> search_one_by_id(mongocxx::collection &, const std::string &) const;
    auto status = Crud::search_one_by_id(this->collection, id);

    if (std::get<0>(status))
    {
        // Error
        return EXIT_FAILURE;
    }
    else
    {
        // Success
        bsoncxx::document::value value = std::get<1>(status);

        bsoncxx::document::view view = value.view();

        this->view = view;

        return EXIT_SUCCESS;
    }
}

The problem is that if I get some element from the view in the method above, i.e the code below before the return EXIT_SUCCESS, no errors are issued.
        bsoncxx::document::element element = this->view["first_name"];

        std::cout << "First Name: " << element.get_utf8().value.to_string();

But if I get a view, save it in the bsoncxx::document::view view variable and try to get some element from the view in another class method:
void get_element()
{
    bsoncxx::document::element element = this->view["first_name"];

    std::cout << "First Name: " << element.get_utf8().value.to_string();
}

I receive the error:
terminate called after throwing an instance of 'bsoncxx::v_noabi::exception'
  what():  unset document::element
Makefile:26: recipe for target 'run' failed
make: *** [run] Aborted (core dumped)

I had tried to use a pointer to save the reference to the view that I get in the search_one_by_id method. I had check if the type of the attribute (first_name) I'm getting is the right type to get the value of the element. I had check if the attribute exist in the document. I had tried to use the release() method from the view in the User::search_one_by_id. I had check if the view is empty through:
if (this->view.empty())
{
    std::cout << "Empty: " << this->view.empty();
}
else
{
    std::cout << "Loaded: " << this->view.empty() << " length " << this->view.length();
}

Inside the get_element method, and the output is:
# If I comment the call to search_one_by_id
$ Empty: 1

# If I enable the call to search_one_by_id
$ Loaded: 0 length 129

The GDB log to backtrace:
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007ffff6fd7801 in __GI_abort () at abort.c:79
#2  0x00007ffff762c957 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff7632ab6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007ffff7632af1 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007ffff7632d24 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007ffff793985c in bsoncxx::v_noabi::document::element::type() const () from /usr/local/lib/libbsoncxx.so._noabi
#7  0x00007ffff7939abc in bsoncxx::v_noabi::document::element::get_utf8() const () from /usr/local/lib/libbsoncxx.so._noabi
#8  0x0000555555559353 in User::get_element() ()
#9  0x0000555555556668 in main ()

Some tips ? The project can be found on Github
References:
Unset Document::element, MongoCXX Find Option Projection
Document value
Document view
Document element
document::element::operator[] overloads should not throw when given an invalid element
How do I get the type of a variable?

A: i think you need to keep the pointer to buffer of value somewhere. view object is pointing to deleted memory i suppose. try something like this
class User
{
   bsoncxx::document::value _value;   <<< store at class level
};

const bool User::search_one_by_id(const std::string &id = "")
{
    // The prototype of the method below: const std::tuple<bool, bsoncxx::document::value> search_one_by_id(mongocxx::collection &, const std::string &) const;
    auto status = Crud::search_one_by_id(this->collection, id);

    if (std::get<0>(status))
    {
        // Error
        return EXIT_FAILURE;
    }
    else
    {
        // Success
        _value = std::get<1>(status);
        this->view = _value.view();

        return EXIT_SUCCESS;
    }
}


text:
Q: How to open new tab or open new window in an already visible GUI on button press? I'm wondering how you open a new tab/window in an already opened GUI with Netbeans.
Also the game I am trying to make will have 1 question per window and have 4 answer buttons you can choose from, if you get the correct answer your score is kept in a variable that can be used throughout the entire code.
**package pokemontrivia;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;

public class triviagui extends javax.swing.JFrame implements ActionListener{

    public triviagui() {
        initComponents();
        init();
    }
    private void init(){
          setTitle("Pokemon Trivia Game");
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setSize(600, 480);
          setLocationRelativeTo(null);
          setVisible(true);
          quitButton.addActionListener(new CloseListener());
    }

     @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        easyqestionsLabel = new javax.swing.JTextField();
        mediumqestionsLabel = new javax.swing.JTextField();
        hardqestionsLabel = new javax.swing.JTextField();
        playButton3 = new javax.swing.JButton();
        playButton2 = new javax.swing.JButton();
        playButton1 = new javax.swing.JButton();
        quitButton = new javax.swing.JButton();
        settingsButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jTextField1.setText("Welcome to Pokemon Trivia !");

        easyqestionsLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        easyqestionsLabel.setText("Easy Questions");

        mediumqestionsLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        mediumqestionsLabel.setText("Medium Questions");

        hardqestionsLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        hardqestionsLabel.setText("Hard Questions");

        playButton3.setText("Play !");

        playButton2.setText("Play !");

        playButton1.setText("Play !");

        quitButton.setText("Quit");

        settingsButton.setText("Settings");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(85, 85, 85)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(mediumqestionsLabel)
                        .addComponent(playButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(easyqestionsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(hardqestionsLabel)
                            .addComponent(playButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(playButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(settingsButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(quitButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(84, 84, 84))
            .addGroup(layout.createSequentialGroup()
                .addGap(116, 116, 116)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(127, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {easyqestionsLabel, hardqestionsLabel, mediumqestionsLabel});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(settingsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(17, 17, 17)
                        .addComponent(quitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(easyqestionsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(playButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(mediumqestionsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(playButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hardqestionsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(playButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(69, 69, 69))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {playButton1, playButton2, playButton3});

        pack();
    }// </editor-fold>

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(triviagui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(triviagui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(triviagui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(triviagui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                new triviagui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTextField easyqestionsLabel;
    private javax.swing.JTextField hardqestionsLabel;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField mediumqestionsLabel;
    private javax.swing.JButton playButton1;
    private javax.swing.JButton playButton2;
    private javax.swing.JButton playButton3;
    private javax.swing.JButton quitButton;
    private javax.swing.JButton settingsButton;
    // End of variables declaration

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}**

A: I'd tend to simply have a JLabel for the question and 4 x JRadioButton objects in a button group for the answers.  When the user selects an answer and is informed of right/wrong, change the text (using setText()) of the question and possible answers.
This has the advantage of only requiring a single panel for as many as thousands of questions.
If it is necessary to have one panel for the question and another for the result, then use a CardLayout with two cards.  One for the questions, the other for the answers.
This short example shows how to use a CardLayout.


text:
Q: How to get only distinct values from joined multiple tables Here i want to show only distict values
var projects = (from dtid in db.Types.Where(dtid => dtid.Site == 1)
                    join diid in di on dtid.TypeId equals diid.TypeId
                    join dicid in dic on diid.DonationId equals dicid.DonationId
                    join eeid in ee.Where(eeid => eeid.IsActive == true) on dicid.ExEnId equals eeid.ExEnId
                    join cid in c on eeid.CoId equals cid.CoId
                    where dtid.DonationTypeId == id

                    select new Newmodel
                    {
                        countries = cid,
                        exEn = eeid,
                        donationItemCountries = dicid,
                        donation = diid,
                        types = dtid

                    }).Distinct().ToList().Take(100) ;

return View(projects);

I have a multiple table with some related data which I want to show only unique country to the view using the .NET core entity framework Here is the code.
Models
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace website.Models

{
    public class Newmodel
    {

        public Types types { get; set; }
        public Donation donation { get; set; }
        public DonationCountries donationCountries { get; set; }
        public ExEn exEn { get; set; }
        public Countries countries { get; set; }

    }
}

A: Distinct compared through what? Calling Distinct() without and IEqualityComparer does the same as if you normally use ==, meaning it looks if the references are equal. I'm guessing you want to compare by country name or country id, which means you'll need a custom IEqualityComparer, luckily enough they're quite easy to implement:
class NewmodelEqualityComparer : IEqualityComparer<Newmodel>
{
    public bool Equals(Newmodel n1, Newmodel n2)
    {
        // Replace '.countries' with whatever property you want to compare
        return n1.countries == n2.countries;
    }

    public int GetHashCode(Newmodel n)
    {
        return n.GetHashCode()
    }
}

Your call to Distinct then needs to simply pass this as its equality comparer, like so:
.Distinct(new NewmodelEqualityComparer()).Take(100).ToList();

Notice how I switched the positions of Take and ToList, this is because if you ToList first and then Take 100 the whole underlying original List will be processed and then 100 will be taken. We can make this a lot more efficient by first taking 100 and then converting the underlying collection to a list, saving potentially thousands of calls to Distinct. This is due to deferred execution provided by IEnumerable and LINQ


text:
Q: dynamic vue widget inside custom post Im fairly new to WP development and am trying to create a plugin that generates a widget depending on the settings set in the custom post type.
The widget is written in vue.js, and i would like to supply it with data from the WPDB (that i download and refresh using the plugin).
So a user can create a new custom post, set variables (example: URL of where the data is) and other settings inside that post, and then use the shortcode to display the widget.
I've created the plugin, read about custom post types and the REST API and created the frontend Widget.
My problem is this:

*

*How do i get Data from the DB to the frontend (vue.js)? Can i use the
REST API for the WPDB?

*How can i use a custom post type to "feed" information into my
widget? I assume i can just get the data from the WPDB about my custom post (storing the settings as part of the custom post), but that just brings me back to the first question.

*Do i use a "post template" to "inject" my widget, or is there something else for that?

A:

*

*How do i get Data from the DB to the frontend (vue.js)? Can i use the REST API for the WPDB?

The REST API works for this, or you could include the data in the HTML as JSON or a window variable

*

*How can i use a custom post type to "feed" information into my widget? I assume i can just get the data from the WPDB about my custom post (storing the settings as part of the custom post), but that just brings me back to the first question.

The REST API, this is pretty much the same question as above. Note that fetching posts in WP via WPDB is highly unusual, and is commonly considered a code smell and bad practice. WP_Query is a far superior/easier method

*

*Do i use a "post template" to "inject" my widget, or is there something else for that?

You could do that, but it would be easier to build a block or shortcode
Keep in mind, that retrieving the data and putting/embedding something in a post are on topic, but Vue.js is offtopic, you'll need to consult Vue.js communities on how it's used.


text:
Q: SQL Server 2005 Remote Login Permissions I have a user Sql Authentication account that has remote access to my database server.  The user has a default database, and is only able to access or modify that DB.  So far so good.  However, I'd like to prevent the user from viewing the other databases that he doesn't have access to anyway.
Inside server permissions, I can deny the user the ability to "View Any Database", but then he can't see even the one database he's allowed to modify.  He can still execute SQL against it, but he has no gui access through sql mgmt studio.
Is there a way to set this up properly?
Thanks.

A: Try setting Server Role to Public and Database Role to db_owner.

A: You can allow view in SSMS if your remote login owns the database.. which is different to db_owner


text:
Q: Chef serverspec `describe command` using an or statement I would like to use a serverspec check and run it against two acceptable outcomes, so that if either passes then the check passes.  I want my check to pass if the exit status of the command is either 0 or 1.  Here is my check:
describe command("rm /var/tmp/*.test") do
  its(:exit_status) { should eq 0 }
end

Right now it can only check if the exit status is 0.  How can I change my check to use either 0 or 1 as an acceptable exit status?

A: Use a compound matcher.
its(:exit_status) { should eq(0).or eq(1) }


text:
Q: Why isn't my Django template properly calculating the length of my collection? In my view:
posts = Post.objects.all()
print len(posts)

prints '2'
In my template
{{ posts|length }}

results in '0' in the browser

A: 1)Are u sure, that posts are available in template?
2)Why don`t u use count?


text:
Q: Reverse CSS indentation in Zend Studio 8 I'm working in Zend Studio 8 based on Eclipse and found that with a CSS file open one can easily format the file to be laid out nicely using  Ctrl + Shift + F*
It works quick in big files.
Is there a reverse function where I can reduce all selector properties to one line, or even the entire file to one line?

A: If I'm reading this correctly, you want something that can compress your CSS.
I'd use a online program like CSSCompressor or Minify.


text:
Q: I want to add randomly a to z in columns using loops.how can i do this? I want to add randomly a to z in columns using loops.how can i do this?

 I want to add randomly a to z in columns using loops.how can i do this?
example:
this my columns
     name
0    Tim
1    Mit
2    Jason
3    Jasim
4    Sible

Expected results:
     name
0    Tima
1    Mitb
2    Jasonc
3    Jasim
4    Siblex

A: import numpy as np
import string
# create a list of characters
choice_list = list(string.ascii_lowercase)
# generate sudo random letter from the list
rand = np.random.choice(choice_list, len(df))
# append strings
df['name_new'] = df['name'].values + rand

    name name_new
0    Tim     Tima
1    Mit     Mite
2  Jason   Jasonz
3  Jasim   Jasimp
4  Sible   Siblec

update
import numpy as np
import string
# create a list of characters
choice_list = list(string.ascii_lowercase)

# create a rand sample of your dataframe
random_sample = df['name'].sample(3) # your sample size

# generate sudo random letter from the list
rand = np.random.choice(choice_list, len(random_sample))

# append strings using iloc
df.iloc[random_sample.index, 0] = random_sample.values + rand

     name
0    Timy
1    Mitp
2  Jasony
3   Jasim
4   Sible

A: I wouldn't use loops here; you can get the same result with a .apply() call with a lambda function inside. .apply() performs the same function on every row of your data, and lambdas let you create anonymous functions.
If you have a string containing all the letters you want to add, you can then use the choice function from the random module to pick a letter at random and add it to the string.
The lambda function looks like this: lambda x: x + choice(letters). Essentially, it says that for any value x, it will return x plus a randomly chosen letter.
Assuming that your column of names is called data, here is an example of the above:
from random import choice

letters = "abcdefghijklmnopqrstuvwxyz"

data.apply(lambda x: x + choice(letters))


text:
Q: Nothing happens after logging in with Devise I'm having a strange and probably very simple issue with Devise. The worst part is I've successfully installed and ran it with another app but can't seem to replicate my steps with this current project.
Here's what happens: I put before_filter :authenticate_user! at the top of my controller. When visiting a method in the controller, the sign up form is generated successfully. Unfortunately, after filling out the login form the page seems to refresh and I'm faced with the login form again.
I have no idea what's going on. Any ideas where I should be looking to fix this silly little problem?
Thank you!

A: I would check your model. If you have devise :confirmable but haven't set up your app to send out confirmation emails, the user wouldn't be getting confirmed, so its likely the culprit of your issue.


text:
Q: iOS CoreData NSFetchedResultsController sections and sorting I currently have a CoreData entity that has a name and date attributes, and I would like to create a NSFetchedResultsController that returns the results sectioned by name sorted by date descending (both the sections and its contents), and if possible, only one entry per section. I prefer not to use NSDictionaryResultType.
Lets say I have the following entries:
Name | Date (year/month/day)
-----+----------------------
Anne | 2014/01/16
John | 2014/01/17
John | 2014/01/15
Nick | 2014/01/13
Nick | 2014/01/10

For the above data I wish to obtain only the following results:
Section | Entry Date
--------+-----------
John    | 2014/01/17
Anne    | 2014/01/16
Nick    | 2014/01/13

How do I create the NSFetchedResultsControllerto obtain only the data and in the order listed above?

As of now I have the following code:
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:moc];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"my predicate" argumentArray:...]];
[fetchRequest setPredicate:predicate];

NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:moc
                                          sectionNameKeyPath:@"name"
                                                   cacheName:nil];

The above code sections the data by name, but each section doesn't have its entries sorted by dateAND it has entries that are not from that name!
The result that I want is the table showing unique name sorted by date like showed in the beginning of the post.
Update: I've been unable to do this, so I switched to result type dictionary and used group by for now, I will leave the question open in the hopes someone knows how to do it.

A: Here is a snippet of some code, in regards to my comment
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EntityThingO"];

NSSortDescriptor *sortDescriptorDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
NSSortDescriptor *sortDescriptorName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
fetchRequest.sortDescriptors = @[sortDescriptorDate , sortDescriptorName];
[fetchRequest setFetchBatchSize:10];

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                managedObjectContext:context
                                                                  sectionNameKeyPath:@"date"
                                                                           cacheName:nil];

A: There is no way (that I am aware of) to limit each section to one result in the NSFetchedResultsController.
But, you might not have to do this. You could probably get away with not displaying everything that is not in the first section.
Also, you should be aware that you should not section the request by using any other key than the key used in the primary sort descriptor

If you are using this with a tableView you could try something like this:
FRC creation
NSSortDescriptor *sdName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSSortDescriptor *sdDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
// sort by name, then sort by date
[fetchRequest setSortDescriptors:@[sdName, sdDate]];
[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:moc
                                      sectionNameKeyPath:@"name"
                                               cacheName:nil];

// fetch...

and the tableViewDataSource:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSFetchedResultsController *fetchedResultsController = [self fetchedResultsController];
    return [fetchedResultsController.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1; // only display one result for each section
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSFetchedResultsController *fetchedResultsController = [self fetchedResultsController];
    YourObject *object = [fetchedResultsController objectAtIndexPath:indexPath];
    ... configure cell ...

Depending on how many objects you have per person this might not be feasible. If there are a lot of entries you won't display I would recommend to normalize the core data model. E.g.:

You then would display a list of Persons. But maybe this normalization would be a good idea regardless of the number of objects per name. Fetching more objects than are displayed smells fishy to me.


text:
Q: Django deployment with Docker on EB failed and 502 badgateway Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY ./config/requirements.txt .
RUN pip install -r requirements.txt

COPY . .

docker-compose.yml
version: '3'

services:
    web:
        build: .
        command: python manage.py runserver 0:8000
        ports:
            - '8000:8000'
        depends_on:
            - db
            - redis
    db:
        image: postgres
        environment:
            - POSTGRES_USER=postgres_test
            - POSTGRES_PASSWORD=postgres_test_pw

    redis:
        image: redis
        ports:
            - '6379:6379'

and in vscode terminal
eb init -> choose docker , Docker running on 64bit Amazon Linux 2
eb create -> application balancer type
and when "eb open" i got 502 badgateway
what should i do

A: By default, EB looks for app running on PORT 8080. You can configure it to the port of your choosing. - Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.

*

*In the navigation pane, choose Environments, and then choose the name of your environment from the list.

*In the navigation pane, choose Configuration.

*In the Software configuration category, choose Edit.

*Looks for "Environment properties".

*Add property name as "PORT" and value as "8000"

*Apply the changes.


text:
Q: Adding a constraint to an existing For Each Loop I have this existing For Each code that searches "A2:J1501" for the player id starting with "V2". Once it finds the first instance of the player id it adds all the id's in "A:J" of that row into the dictionary. Then it cuts the row onto the Lineups sheet and moves onto "V3". If "V3" is already in the dictionary it highlights it yellow and moves onto "V4" until if finds a player id that is not already in the dictionary. Now, I want to add a constraint to this code. I don't want it to search any row of the "A2:J1501" range unless the Team Stack in column "T" matches the Team name next to the player name in column "X." If the code is searching for "V10" and "X10" = "LAA" I only want the code to search within rows "A2:J1501" where column "T" = "X10". Hopefully that is clear.
Here is the code I have:
Sub Get_Lineups_Stacking()

    Dim wsData As Worksheet, c As Range, dict As Object, v, rw As Range
    Dim wsLineups As Worksheet, c2 As Range, f As Range
    Dim Check As Range
    Dim CheckCell As Integer

    Set dict = CreateObject("scripting.dictionary")                         'for tracking already-seen values

    Set wsLineups = ThisWorkbook.Worksheets("Lineups")
    Set wsData = ThisWorkbook.Worksheets("Data")

    For Each c In wsData.Range("V2", wsData.Cells(Rows.Count, "V").End(xlUp))
        v = c.Value
        If dict.exists(CStr(v)) Then
            c.Interior.Color = vbYellow                                     'already seen this value in L or a data row
        Else
            Set f = wsData.Range("A2:J1501").Find(v, lookat:=xlWhole, LookIn:=xlValues, searchorder:=xlByRows)
            If Not f Is Nothing Then
                Set rw = f.EntireRow.Columns("A").Resize(1, 10) 'A to J
                For Each c2 In rw.Cells                                     'add all values from this row to the dictionary
                    dict(CStr(c2)) = True
                Next c2
                rw.Cut Destination:=wsLineups.Cells(Rows.Count, "A").End(xlUp).Offset(1)
                c.Interior.Color = vbYellow
            Else
                c.Interior.Color = vbRed                                    'flag no matching row
            End If
        End If                                                              'haven't already seen this col L value
    Next c                                                                  'next Col L value

    Set wsData = Sheets("Data")
    wsData.Range("V:W").Interior.Color = xlNone

    Set Check = wsLineups.Range("A" & HowManyLineups)
    If IsEmpty(Check) = True Then
    Call Get_Lineups
    End If

    Application.ScreenUpdating = True

End Sub

I also attached a screenshot of my excel sheet for visual reference.

Thank you very much.


text:
Q: Getting the page source of imgur I'm trying to get the page source of an imgur website using requests, but the results I'm getting are different from the source. I understand that these pages are rendered using JS, but that is not what I am searching for.
It seems I'm getting redirected because they detect I'm using an automated browser, but I'd prefer not to use selenium here. For example, see the following code to scrape the page source of two imgur ID's (one valid ID and one invalid ID) with different page sources.
import requests
from bs4 import BeautifulSoup

url1 = "https://i.imgur.com/ssXK5" #valid ID
url2 = "https://i.imgur.com/ssXK4" #invalid ID

def get_source(url):
    headers = {
    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36"}

    page = requests.get(url, headers = headers)
    soup = BeautifulSoup(page.content, 'html.parser')
    return soup

page1 = get_source(url1)
page2 = get_source(url2)

print(page1==page2)
#True

The scraped page sources are identical, so I presume it's an anti-scraping thing. I know there is an imgur API, but I'd like to know how to circumvent such a redirection, if possible. Is there any way to get the actual source code using the requests module?
Thanks.


text:
Q: Padding an image in Python I am trying to add columns and rows on all sides.
padded_array = np.zeros([img.shape[0] + (size//2) + (size//2), img.shape[1] + (size//2) + (size//2)])
padded_array[size//2 : padded_array.shape[0]-(size//2), size//2 : padded_array.shape[1]-(size//2)] = gray

Here, img is the original image and gray is the gray-scaled image and shape of both of them is same.
Now, I am trying to create a padded_array by adding (size//2) rows on top and below and
(size//2) columns left and right.
size is always odd.
When I try to pad, I don't understand why the gray image is not broadcasted into the padded array.
Instead, what it is doing is broadcasting value 255 on all pixels in that range of gray image and padded rows and columns are left blank.
I am adding the screenshots of both the images, please have a look.

*

*Gray Scale Image is :

*Padded Image after broadcasting gray is :

A: You can divide image width / image height and multiply with a constant.
import matplotlib.pyplot as plt

def pad(image, h=2):
    w = (image.shape[0]/image.shape[1]) * h
    plt.figure(figsize=(w, h))
    plt.imshow(im)
    plt.axis('off')
    plt.show()

im = plt.imread('blur.png')
pad(im)

Output:

A: The mistake here was while defining the padded_array I didn't define the data type of array to be int, it was float by default and that was the reason for white image, as soon as I defined the data in padded_array are int, everything turned out fine.


text:
Q: Clearing Vue JS v-for Select Field I have a simple application that uses a v-for in a select statement that generates two select tags. The groupedSKUAttributes variable that creates the select statement looks like this:
groupedSKUAttributes = {colour: [{id: 1, name: 'colour', value: 'red'},
                                 {id: 2, name: 'colour', value: 'blue'}],
                        size: [{id: 3, name: 'size', value: '40'},
                               {id: 4, name: 'size', value: '42'}]}

I also have a button that I want to clear the select fields. How do I get the clear method to make each of the select fields choose their default <option value='null' selected>select a {{ attributeName }}</option> value? I can't figure out if I'm meant to use a v-model here for the groupedSKUAttributes. Any advice would be appreciated.
The template looks like this:
<template>
  <div>
    <select
      v-for='(attribute, attributeName) in groupedSKUAttributes'
      :key='attribute'
      @change='update(attributeName, $event.target.value)'>
      <option value='null' selected>select a {{ attributeName }}</option>
      <option
        v-for='a in attribute'
        :value='a.id'
        :label='a.value'
        :key='a.id'>
      </option>
    </select>
  </div>
  <button @click='clear'>clear</button>
</template>

And the JS script looks like this:
<script>
export default {
  name: 'app',
  data() {
    return {
      groupedSKUAttributes: null,
    }
  },
  methods: {
    clear() {
      console.log('clear');
    },
    update(attributeName, attributeValue) {
      console.log(attributeName, attributeValue);
    },
    getSKUAttributes() {
      API
        .get('/sku_attribute/get')
        .then((res) => {
          this.skuAttributes = res.data;
          this.groupedSKUAttributes = this.groupBy(this.skuAttributes, 'name');
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getSKUAttributes();
  }
}
</script>

A: The v-model directive works within the v-for without any issues.
<script>
  export default {
    name: 'app',

    data() {
      return {
        groupedSKUAttributes: null,
        selected: {}
      }
    },

    methods: {
      clear() {
        this.generateDefaultSelected(this.generateDefaultSelected);
      },
      update(attributeName, attributeValue) {
        this.selected[attributeName] = attributeValue;
      },
      getSKUAttributes() {
        API
          .get('/sku_attribute/get')
          .then((res) => {
            this.skuAttributes = res.data;
            this.groupedSKUAttributes = this.groupBy(this.skuAttributes, 'name');

            // Call this method to reset v-model
            this.generateDefaultSelected(this.groupedSKUAttributes);
          })
          .catch((error) => {
            console.error(error);
          });
      },

      generateDefaultSelected(groupedSKUAttributes) {
        // Reset the object that maintains the v-model reference;
        this.selected = {};

        Object.keys(groupedSKUAttributes).forEach((name) => {
          // Or, set it to the default value, you need to select
          this.selected[name] = '';
        });
      }
    },

    created() {
      this.getSKUAttributes();
    }
  }
</script>

In the above code, generateDefaultSelected method resets the selected object that maintains the v-model for all your selects.
In the template, you can use v-model or unidirectional value/@change pair:
<!-- Using v-model -->
<select
  v-for='(attribute, attributeName) in groupedSKUAttributes'
  :key='attributeName' v-model="selected[attributeName]">

<!-- Unidirection flow without v-model -->
<select
  v-for='(attribute, attributeName) in groupedSKUAttributes'
  :key='attributeName' :value="selected[attributeName]"
  @change='update(attributeName, $event.target.value)'>


text:
Q: Yii2 karthik editable column first row not working I used karthik grid view and editable column to edit my grid view data. it not work for the first row of the grid view and work for the other rows when i enter value to the first row it give error like this

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

my gridview code is.
<?= GridView::widget([
            'dataProvider' => $dataProvider,
            'pjax' => true,
            'pjaxSettings' => [
                    'options' => [
                        'id' => 'grid',

                    ]
                    ],
            'export'=>false,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                [
                    'header'=>'Sub Category',
                    'value'=>'item.subCategory.name',
                ],
                'item.code',
                [
                    'header'=>'Brand',
                    'value'=>'item.brand.name',
                ],
                'item.description',
                'item.pack_size',
                [
                    'header'=>'Unit',
                    'value'=>'item.unit',
                ],
                [
                    'header'=>'Last Price',
                    'value'=>function($model){
                        $customerId = $model->customerOrderRequest->customer_id;
                        $lastPurchasedPrice = Item::getLastPurchasedPrice($customerId,$model->item_id);
                        return '$ ' . number_format($lastPurchasedPrice, 2);
                    }
                ],
                [
                    'class' => 'kartik\grid\EditableColumn',
                    'attribute'=>'qty',
                    'editableOptions' =>
                    [
                      'formOptions' => ['action' => 'customer-order-request']
                    ],
                    'header' => 'Qty',
                ],
                [
                    'header'=>'Estimate',
                    'value'=>function($model)
                    {
                        return '123123.00';
                    }
                ],
                [
                    'header'=>'Price (UNIT)',
                    'format'=>'raw',
                    'value'=>function($modal){
                        $salse_rep_id = Yii::$app->user->identity->ref_id;
                        $exsist_respond = Respond::find()->where(['sales_rep_id'=>$salse_rep_id,'customer_order_request_id'=>$modal->customer_order_request_id])->one();
                        if(!empty($exsist_respond)){
                            $exsist_respond_item = RespondItem::find()->where(['item_id'=>$modal->item_id,'respond_id'=>$exsist_respond->id])->one();
                            if(!empty($exsist_respond_item)){
                            $price = $exsist_respond_item->price;
                            }  else {
                            $price = NULL;
                            }

                        }  else {
                            $price = NULL;
                        }
                        if(!empty($exsist_respond) && $exsist_respond->status !="Pending"){
                              return $price;
                        }else{

                        return "<input type='text' class='respond-item' cor='$modal->customer_order_request_id' value='$price' item_id='$modal->item_id' />";

                        }

                        },
                    'visible'=>(Yii::$app->user->identity->ref_table =="sales_rep")? true:false
                ],

            ],
        ]); ?>

and my controller is
public function actionEditable()
{
    if (Yii::$app->request->post('hasEditable'))
    {
        $customerItemsId = Yii::$app->request->post('editableKey');
        print_r($customerItemsId);die();
        $model = RequestItem::findOne($customerItemsId);

        $out = Json::encode(['output'=>'', 'message'=>'']);

        $post = [];
        $posted = current($_POST['RequestItem']);
        $post['RequestItem'] = $posted;

        if ($model->load($post))
        {

            $model->save();
            $output = '';

            $out = Json::encode(['output'=>$output, 'message'=>'']);
        }
        echo $out;
        return;
    }

}

any one can help me with this problem.

A: Form tag nested.
a trick: Add a fake form to let browser remove it.
I meet this problem today, cause I put a form in another, they are nested.
So the browser remove the first nested form.
In the official W3C XHTML specification, Section B. "Element Prohibitions", states that:

"form must not contain other form elements."

official website
Following is sample code:
       <form id="thisisMainForm">
          <form id="dummy"> ->This will get Removed
                <gridview id="thisisEditableGridView">
                      Gridviewcode.....
                </gridview>
          </form>
       </form>


text:
Q: Start thread from the same location after crash I'm writing a Worker Role for Windows Azure. The worker receives messages from a queue and for every message it spins up a thread.
Threads are calling external API and that involve a lot of thread waiting: i.e. I can call "Create An Instance", API would return 202 Accepted and then I'll have to poll API for "Completed" answer. Sometimes the wait can be 5 minutes. The whole process can take from 10 to 30 minutes, with about 10 calls to the API.
30 minutes in the life of Azure Worker Role is a lot and Restart/Redeploy/Crash can happen during that time. And my process is not idempotent, I can't create the same resource twice without a problem.
What I would like to do is on every critical call to API, store the state of the thread somewhere. So if the thread crashes somewhere, another worker role can pick up a message from the queue and take off from the same point of process, where the previous was interrupted.
One of the ideas was to report thread status and persist that somewhere. Something like this pseudocode:
pubilc class WorkerRole{
    public override Run(){
        while(true)
        {
            var message = Queue.GetMessage();
            var messageProcessor = new MessageProcessor(message);
            var thread = new Thread();
            thread.Run(messageProcessor.Process());
            Thread.Sleep(1 minute);
        }
    }
}

public class MessageProcessor
{
    private QueueMessage message;
    public MessageProcessor(QueueMessage message){
        this.message = message
    }

    public void Process()
    {
        if(!ThreadReporter.IsComplete(message, "Step1")
        {
            ExtenalApi.StartStep1();
        }
        ThreadReporter.ReportCompletion(message, "Step1");

        if(!ThreadReporter.IsComplete(message, "Step2"))
        {
            ExternalApi.StartStep2();
        }
        ThreadReporter.ReportCompletion(message, "Step2");
    }
}

ThreadReporter would save a flag somewhere in DB that Step1 is complete or would check if flag for Step1 is already set for that particular message (work request).
I can feel that this approach would have a lot of problems and the code would be horrible. But I struggle to think of a better way to do that.
I've seen Jon Skeet was saving some kind of MemoryDump of an application and after restart taking off from the same place. Can a thread state be serialised to be saved in a DB?
Also I've heard that Workflow Foundation can do that as well. I've never worked with WF and have no clue about it. Any hints about WF?
So, the question is, what is the best way to implement workflow (that is essentially a workflow) that after crash can start from the last point?

A: This is exactly the kind of thing that Long-Running persisted workflows were designed to solve.
Having a thread run and pause (presumably with loop-thread-sleep's) is not ideal as you said.
Might be time for some re-architecting. Your suggestion of persisting the current state of play after each step to a DB would work alright but if you have the bandwidth, I'd definitely look into Long Running workflows.
http://msdn.microsoft.com/en-us/library/ff432975.aspx


text:
Q: C++ debugger_hook_dummy throws exception I am trying to debug an application and one day it suddenly started doing this, having been previously working:
__declspec(noinline)
void __cdecl _CRT_DEBUGGER_HOOK(int _Reserved)
{
/* assign 0 to _debugger_hook_dummy so that the function is not folded
in retail */
(_Reserved);
_debugger_hook_dummy = 0;
}

The application then cannot start.
I have read that this is related to dependencies; I do have multiple dll dependencies but they all compile correctly and I have ensured that they are all compiled in the same mode. I have tried in both release and debug mode and I get the same error above.
Any ideas would be extremely helpful as I would love to have a proper debugger again.

A: I had a similar issue and it turned out to be that there was too many bytes on the stack (in debug mode only) which resulted in program counter corruption and eventually this error.  Visual Studio 2010 wasn't reporting the error as stack overflow but once I reduced the bytes on the stack the problem went away.


text:
Q: Gmail policy for https images with missing SSL certificate I'm working on an EN store for a client, which is on a separate domain from the original language (and this second domain does not - yet - have a valid SSL certificate).
When sending emails, the images are visible on yahoo. However, on gmail they are missing (404). The image URLs generated by gmail look like this:

https://ci4.googleusercontent.com/proxy/A_CCC-sd3OA3rSPyxMwmVMzZQrdMke4_UkaB1B7QZO_J-#https://www.bla-bla.com/images/en/discounts.jpg

https://www.bla-bla.com/images/en/discounts.jpg works fine if copied in a separate tab, but not in gmail.
Is it possible that the images are not shown because of the missing SSL certificate ? I'm not sure where I can find some documentation on these rules.


text:
Q: How do I stop oracle JDK from hijacking PATH and breaking update-alternatives? I installed oracle jdk on ubuntu 14.04. Now I want to toggle back to openjdk:
sudo update-alternatives --config java
sudo update-alternatives --config javac

But it doesn't work. It seems oracle's jdk somehow keeps adding itself to my $PATH:
...:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin:...

I've found and killed /etc/profile.d/jdk.csh, but there seems to be a failsafe. The audacity!!
How can I fix this?

A: I think you are on the right track by removing /etc/profile.d/jdk.csh and /etc/profile.d/jdk.sh. You just have to re-login or reboot so that the PATH changes have effect.


text:
Q: Unhandled Rejection (TypeError): Cannot read property 'replace' of undefined I am using MongoDB as my database for my Reactjs project. Here, when I am trying to connect the database, it gives me this error - "Unhandled Rejection (TypeError): Cannot read property 'replace' of undefined"
Here's the code of App.js
 import React from "react";
import Sidebar from "./Sidebar";
import Feed from "./Feed";
import Widgets from "./Widgets";
import "./App.css";
import { MongoClient } from "mongodb";

function App() {
  // Connection URI
  const uri =
    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
  // Create a new MongoClient
  const client = new MongoClient(uri);
  async function run() {
    try {
      // Connect the client to the server
      await client.connect();
      // Establish and verify connection
      await client.db("posts").command({ ping: 1 });
      console.log("Connected successfully to server");
    } finally {
      // Ensures that the client will close when you finish/error
      await client.close();
    }
  }
  run();

  return (
    <div className="app">
      <Sidebar />
      <Feed />
      <Widgets />
    </div>
  );
}

export default App;

Any help is greatly appreciated !

A: You need to create a backend for your React app and connect to database from there. Then expose an endpoint like /api/posts and call that in your React app with fetch or something similar, e.g.
fetch('http://localhost:4000/api/posts')
  .then(response => response.json())
  .then(posts => console.log(posts));


text:
Q: Using curly braces in QML input mask I have a QML line edit, and am trying to use the input mask to ensure a valid UID is entered.  My input mask is set like this:
inputMask: ">\\{NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN\\}"

and my text property is set to: "{49f93de5-1da6-4e3a-a2e4-64795dc89ebb}"
When I run my program the curly braces are missing from the screen's edit field (but the hyphens are present and character masks are correctly applied).  How can I show the { and } ?  I assumed escaping them in the mask was all that was necessary.

A: I think your problem relates to this
Edited: wrapping the input string in qsTr() allows the curly braces to show in the input text.
in QML I use TextInput and it works :
import QtQuick 2.14
import QtQuick.Window 2.14

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TextInput {
        id: textInput
        x: 116
        y: 94
        width: 237
        height: 53
        text: qsTr("{49f93de5-1da6-4e3a-a2e4-64795dc89ebb}")
        font.pixelSize: 12
        inputMask: ">\\{NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN\\}"
    }

}


text:
Q: Spring-ws multiple request in one request I have a problem.
I want to create multiple request in one request.
<xsd:element name="SendMemberStatusRequest">
    <xsd:complexType>
        <xsd:sequence>
        <xsd:element name="MemberStatusRequest" type="member:MemberStatusRequest"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
<xsd:element name="SendMemberStatusResponse">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="MemberStatusResponse" type="member:MemberStatusResponse"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

This is my xsd code. For one "MemberStatusRequest" but i want to use, who want to send request may be send 1 request may be send 10 request. Anybody can help me ?
<xsd:element name="SendMemberStatusRequest">
    <xsd:complexType>
        <xsd:sequence>
        <xsd:element  name="MemberStatusRequest" type="member:MemberStatusRequest"/>
        <xsd:element  name="MemberStatusRequest" type="member:MemberStatusRequest"/>
        .........
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

A: This should help you:
<xsd:element name="SendMemberStatusRequest">
    <xsd:complexType>
        <xsd:element name="MemberStatusRequest" type="member:MemberStatusRequest" maxOccurs="unbounded"/>
    </xsd:complexType>
</xsd:element>

By default minOccurs/maxOccurs is "1".
Your Request Class on the matter should have List<MemberStatusRequest> requests property.


text:
Q: Do I need more than 1 Antenna / Comms / Communotron? What might the reason for taking more than 1 Antenna into orbit / space?

A: After a little searching I found an update to this question. Please refer to Antenna / Range table (Commnet) by Toukiedatak at /r/KerbalSpaceProgram.
It seems to be contested, but there is a consensus that more antennae increase the communication range of the craft. I believe the phrase Commnet is the term for KSP 1.2's new communication network simulation capability.

A: As far as I can determine, there is no decisive advantage in attaching more than one antenna to a craft in the stock (unmodded) game - it will not increase your transmission speed if you have multiple.
However there are a few cases where it may be desirable:
The most expensive antenna (the Communotron 88-88) is an electricity hog; if a latter stage of your rocket has reduced electrical generation or storage capacity (or you are planning for some accidental damage), it may be prudent to stick an additional cheaper antenna to your vessel so you can safely transmit without running out of power in these situations.
Spares in case a planned landing turns out less than ideal and some parts get destroyed on the process.
If your rocket is designed to launch probes, or otherwise detach a section to investigate science while the main craft does other things; each detachable section will need its own antenna, unless you plan to rendezvous and reattach to the main vessel.
You are OCD about symmetry, and for whatever reason it was not possible/practical to place the antenna on the center of your symmetrical axis. Also, I'll roll "Just for aesthetics" under this.

A: For stock KSP - there is no reason. One antenna is enough to transmit science.
Though there are mods that expand antenna usage, e.g. RemoteTech
Also another option is to 'just stick-em on' to future proof your crafts for upcoming 1.1 update with enhancements regarding antenna usage, as mentioned in dev notes here.

A: Having more than one antenna allows you to upload more than one science result simultaneously. Your energy use will of course scale accordingly.


text:
Q: how can I run a script at the bash command line such that its configuration is identical to its configuration when it is run by cron? I want to write and test scripts that do not depend on any of the personal environment variables accessible to me at the command line. For instance, each time I open a new command line window on my macbook pro, $PATH is updated by having my personal bin directory prepended to it --- as well as several other directories, such as
/usr/sbin:/sbin:/Library/TeX/texbin:/Library/Apple/usr/bin

This occurs apparently because my $HOME/.profile is automatically sourced when a window opens up. In addition, a large number of other variables are defined at login because my personal .bashrc is sourced automatically.
Ultimately, I want to be able to run a script as a cron job --- using crontab -l. But if the script depends on my personal configuration, or if it tries to access a script that lives in my personal bin, it will halt with error.
So I write a script, test it at the command line, set up a cron job to run it; and when the time comes, it halts with error, because it turns out that the script depended on one of my personal environment variables.
Currently, then, the only way I know to test such a script is to set up a cron job --- say, five minutes from now---and then wait for the cron job to run. It's clumsy and slow.
Is there a direct and immediate way to run a script so that it does not know anything from $HOME/.profile?
The script I tested this with:
#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper qw(Dumper);
$Data::Dumper::Sortkeys = 1;
print Dumper {%ENV};

The following command
> jaw20210419test.pl | wc
    2532    3098  118462

produces many lines of output, as you see, because of all that I define in my .bashrc.
With the following,
> sudo jaw20210419test.pl | wc
Password:
      20      59     831
>

the output is much less, but it still has an updated $PATH including my personal bin. I do not understand this, since the $PATH gets updated by $HOME/.profile, and that file sources my personal $HOME/u/kh/.bashrc.
If however I run this with a cron job, then it does not have an updated $PATH. The script says
$VAR1 = {
          'HOME' => '/Users/kpr',
          'LOGNAME' => 'kpr',
          'PATH' => '/usr/bin:/bin',
          'PWD' => '/Users/kpr',
          'SHELL' => '/bin/sh',
          'SHLVL' => '1',
          'USER' => 'kpr',
          'VERSIONER_PERL_VERSION' => '5.18',
          '_' => '/Users/kpr/u/kh/bin/jaw20210419test.pl',
          '__CF_USER_TEXT_ENCODING' => '0x1F5:0x0:0x0'
        };

This is the configuration I want to test the script with. Note that it knows who I am --- $USER --- and where $HOME is.
By contrast, two other proposed solutions, from
How to start a shell without any user configuration?,
do not even know know where $HOME is:
> echo $cdbin # personal environment variable
/Users/kpr/u/kh/bin
> env -i perl $cdbin/jaw20210419test.pl
$VAR1 = {
          'VERSIONER_PERL_VERSION' => '5.18',
          '__CF_USER_TEXT_ENCODING' => '0x1F5:0x0:0x0'
        };
> env --noprofile --norc  perl $cdbin/jaw20210419test.pl
env: illegal option -- n
usage: env [-iv] [-P utilpath] [-S string] [-u name]
           [name=value ...] [utility [argument ...]]
> echo $SHELL
/bin/bash
>
> env -i sh -c  $cdbin/jaw20210419test.pl
$VAR1 = {
          'PWD' => '/Users/kpr/u/sng/2021/FR-Wegelin-TO-stackoverflow',
          'SHLVL' => '1',
          'VERSIONER_PERL_VERSION' => '5.18',
          '_' => '/Users/kpr/u/kh/bin/jaw20210419test.pl',
          '__CF_USER_TEXT_ENCODING' => '0x1F5:0x0:0x0'
        };

so I am still lost.

A: Of note, you can not technically do what you wish. Bash goes to great lengths to determine if you are running an interactive shell or a non-interactive shell. Running from cron will forever be non-interactive as is running from a terminal will forever be marked as interactive.
You want a number of entries not present in cron for your test shell, for example PS1 for a prompt. Also there are quite a few read only environment variables. If you try to unset them you get an error:
bash: unset: SHELLOPTS: cannot unset: readonly variable

You can get 95 percent there by this method:
% env -i bash --noprofile --norc
bash-3.2$ source be-cron.sh
bash-3.2$

The file be-cron.sh will "unset" most of the interactive environment variables:
#!/bin/bash
unset BASH
unset BASH_ENV
unset BASH_VERSION
unset COLORFGBG
unset COLORTERM
unset COLUMNS
unset COMMAND_MODE
unset DIRSTACK
unset DISPLAY
unset EDITOR
unset GROUP
unset GROUPS
unset HISTFILE
unset HISTFILESIZE
unset HISTSIZE
unset HOST
unset HOSTNAME
unset HOSTTYPE
unset IFS
unset ITERM_PROFILE
unset ITERM_SESSION_ID
unset LC_TERMINAL
unset LC_TERMINAL_VERSION
unset LINES
unset LaunchInstanceID
unset MACHTYPE
unset MAILCHECK
unset MANPATH
unset MANPATH_WITHOUT_PERLBREW
unset OPTERR
unset OPTIND
unset OSTYPE
unset PATH_WITHOUT_PERLBREW
unset PERLBREW_HOME
unset PERLBREW_PATH
unset PERLBREW_ROOT
unset PERLBREW_SHELLRC_VERSION
unset PIPESTATUS
unset PS2
unset PS4
unset SECURITYSESSIONID
unset SSH_AUTH_SOCK
unset TERM
unset TERM_PROGRAM
unset TERM_PROGRAM_VERSION
unset TERM_SESSION_ID
unset TMPDIR
unset VENDOR
unset XPC_FLAGS
unset XPC_SERVICE_NAME
unset __CFBundleIdentifier


text:
Q: Parsing content with the HTML Agility Pack and Linq i am trying to get significant content for searched keywords in html.
using the code below for generate a HtmlNodeCollection
var findclasses = doc.DocumentNode.SelectNodes("//body//*[not(self::script)]").Where(x => x.InnerHtml.Contains("SearchedKeywordText") && x.InnerHtml.Contains("SearchedKeyword1Text")).OrderBy(x => x.Name);
                string FirstContent = findclasses.First().InnerText;

And i am getting this result

*

*Results View    Expanding the Results View will enumerate the IEnumerable

*[0] Name: "div"}    HtmlAgilityPack.HtmlNode

*[1] Name: "div"}    HtmlAgilityPack.HtmlNode

*[2] Name: "div"}    HtmlAgilityPack.HtmlNode

*[3] Name: "ul"} HtmlAgilityPack.HtmlNode

*[4] Name: "li"} HtmlAgilityPack.HtmlNode

*[5] Name: "span"}   HtmlAgilityPack.HtmlNode

*[6] Name: "span"}   HtmlAgilityPack.HtmlNode

*[7] Name: "div"}    HtmlAgilityPack.HtmlNode

*[8] Name: "span"}   HtmlAgilityPack.HtmlNode

*[9] Name: "span"}   HtmlAgilityPack.HtmlNode

*[10]    Name: "ul"} HtmlAgilityPack.HtmlNode

*[11]    Name: "li"} HtmlAgilityPack.HtmlNode

But when i want to simple modify the code to get string from outside:
string search1 = "SearchedKeywordText";
string search2 = "SearchedKeyword1Text";
..
..
var findclasses = doc.DocumentNode.SelectNodes("//body//*[not(self::script)]").Where(x => x.InnerHtml.Contains(search1) && x.InnerHtml.Contains(search2)).OrderBy(x => x.Name);
                    string FirstContent = findclasses.First().InnerText;

Result:

*

*Results View    Expanding the Results View will enumerate the IEnumerable
      Empty   "Enumeration yielded no results"

Enumeration in first block is work good for me but after that changes it does not work. Is there any idea for this simple question ?

A: You are calling .First() on an empty IEnumerable
You could use .Any() to check if findclasses is not empty
if (findclasses.Any())
{
   string firstContent = findclasses.First().InnerText;
}

*

*Why is it empty?

maybe there are results but there is a case mistmatch and you need to make your search case insensitive, for that rather than
x.InnerHtml.Contains(search1)

you can do something like:
x.InnerHtml.IndexOf(search1,StringComparison.InvariantCultureIgnoreCase)>=0

that will return true if the search keyword is found regardless of the letter case.


text:
Q: React Sidenav - Bootstrap 4 & Material Design not working I have tried to implement the Sidebar with navigation from mdbreact to use bootstrap and material design.
I have just copy pasted the code from the example from: https://mdbootstrap.com/docs/react/navigation/sidenav/
import React from 'react';
import { MDBIcon, MDBSideNavCat, MDBSideNavNav, MDBSideNav,
         MDBSideNavLink, MDBContainer, MDBRow, MDBBtn } from 'mdbreact';

class SideNav extends React.Component {
  constructor(props) {
  super(props);
  this.state = {isOpen: false};

  this.handleToggle = this.handleToggle.bind(this);
 }

 state = {
    isOpen: false
 };

 handleToggle() {
    this.setState({ isOpen: !this.state.isOpen });
 }

 render() {

 return (
  <MDBContainer>
    <MDBRow>
      <MDBBtn onClick={this.handleToggle}><MDBIcon icon="bars" size="5x" /></MDBBtn>
    </MDBRow>
    <MDBSideNav
      logo="https://mdbootstrap.com/img/logo/mdb-transparent.png"
      hidden
      triggerOpening={this.state.isOpen}
      breakWidth={1300}
      className="deep-purple darken-4"
    >

              <MDBIcon icon="facebook" />

              <MDBIcon icon="pinterest" />

              <MDBIcon icon="google-plus" />

              <MDBIcon icon="twitter" />

      <MDBSideNavNav>
        <MDBSideNavCat
          name="Submit blog"
          id="submit-blog"
          icon="chevron-right"
        >
          <MDBSideNavLink>Submit listing</MDBSideNavLink>
          <MDBSideNavLink>Registration form</MDBSideNavLink>
        </MDBSideNavCat>
        <MDBSideNavCat
          name="Instruction"
          id="instruction"
          icon="hand-pointer-o"
          href="#"
        >
          <MDBSideNavLink>For bloggers</MDBSideNavLink>
          <MDBSideNavLink>For authors</MDBSideNavLink>
        </MDBSideNavCat>
        <MDBSideNavCat name="About" id="about" icon="eye">
          <MDBSideNavLink>Instruction</MDBSideNavLink>
          <MDBSideNavLink>Monthly meetings</MDBSideNavLink>
        </MDBSideNavCat>
        <MDBSideNavCat name="Contact me" id="contact-me" icon="envelope-o">
          <MDBSideNavLink>FAQ</MDBSideNavLink>
          <MDBSideNavLink>Write a message</MDBSideNavLink>
        </MDBSideNavCat>
      </MDBSideNavNav>
    </MDBSideNav>
  </MDBContainer>
);
}
}

export default SideNav;

I'm getting a long error:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I think it something in the  but i'm not sure, anybody having the some problem? Thanks in advance.

A: I just found the answer to the question. You have to buy the pro version to use the SideNav. I overlook the red tag.


text:
Q: embedded variable in R string I am trying to loop and rename colnames in a data frame.
How can I embed a numeric variable in the R's colname string. I found the .(x) associated to the bquote/paste method for title in graphics but it doesn't work with a standard string.
In Ruby I can embed a variable in a string using #{x} in the following way
irb(main):005:0> (1..10).each{|i| p "hello no #{i}"}
"hello no 1"
"hello no 2"
"hello no 3"
"hello no 4"
"hello no 5"
"hello no 6"
"hello no 7"
"hello no 8"
"hello no 9"
"hello no 10"

Thanks

A: You can simply use sprintf(). For example:
i <- 4;
data[[sprintf("hello.%1.2d",i)]] <- ...;


text:
Q: Sub project dependent on root project in Gradle Can sub project dependent on or use some files or packages from the root project in gradle?
I have the following project:
root
├── project1
├── build.gradle
└── src
├── settings.gradle

I have the settings.gradle as following:
include 'project1'

The project1 need to use some files and packages from src of the root which is the root project, is there a way to do it?

A: I recommend this structure as it's more flexible and manageable. root will be just a wrapper and will contain subprojects only.
root
├── project1 (dependent on project 2)
|   |
|   |__build.gradle
|
|
|__ project2
|   |
|   |__ src
|   |__ build.gradle
|
├── build.gradle
├── settings.gradle

settings.gradle
include 'project1'
include 'project2'

EDIT:
If you need to have dependency on root, use following dependency in project1:
dependencies {
  compile project(':root')
}

In settings.gradle
rootProject.name = 'root'
include 'project1'


text:
Q: Advanced Installer: How to pass arguments to executable? I'm using Advanced Installer to wrap up my executable into a  nice friendly package. I would normally launch the executable from the command line via something like this:
> myExecutable.exe firstArg secondArg

Now I'm trying to add these arguments into the Advanced Installer package somehow but it is unclear how to do this. Some posts have suggested I need to add a private or public property, but they don't explain how to do this well. I feel like there should be some straightforward way how to do this within the AI GUI. Any help is much appreciated, thanks!!

A: In the Finish Actions panel of the ExitDialog is a Launch Application section.  It allows you to specify your application path and arguments.
As for using a property, use the Install Parameters screen to add your public (all caps) or private property and simply reference it as [MY_PUBLIC_PROPERTY] in the Arguments: text box.


text:
Q: How to make linear-gradient background in React-native How to crate gradient inside
<View />

https://github.com/react-native-community/react-native-linear-gradient

A: You can use LinearGradient instead of a View and put your content in there.
  <LinearGradient
    colors={['#373B44', '#4286f4', '#373B44']}
    style={{
      flex: 1,
    }}
  >
    <Text>
      Test
    </Text>
  </LinearGradient>

But also you can use View as a content in the LinearGradient.
  <LinearGradient
    colors={['#373B44', '#4286f4', '#373B44']}
    style={{
      flex: 1,
    }}
  >
    <View
      style={{
        margin: 20,
      }}
    >
      <Text>
        Test
      </Text>
    </View>
  </LinearGradient>

I also explained usage of react-native-linear-gradient and its features here with source code.

A: if you are using expo,
i had created a separate component
you can import it in any component and use it

import { fonts } from '@src/theme/typography'
import { LinearGradient } from 'expo-linear-gradient'
import React from 'react'
import { ViewStyle, StyleProp, StyleSheet, Text } from 'react-native'

const Button = (props) => {
    const { style, text } = props
    return(
        <LinearGradient
        colors={['#ffa700', '#ff9300']}
        style={[styles.container, style]}>
        <Text style={styles.text}>
        {text}
        </Text>
        </LinearGradient>
    )
}

const styles = StyleSheet.create({
    container: {
        height: 48,
        borderRadius: 8
    },
    text: {
        textAlign: 'center',
        marginTop: 'auto',
        marginBottom: 'auto',
        color: '#fefffe',
        fontSize: 18,
        fontFamily: fonts.medium,

    }
})

export default Button

A: Try with this steps :
1) import LinearGradient from react-native-linear-gradient library.
import LinearGradient from 'react-native-linear-gradient';

2) set some flex value to LinearGradient
<LinearGradient
    colors={['#33ccff', '#ff99cc']}
    style={{ flex:1 }}
>
    <View>
        //set your content or elements here
    </View>
</LinearGradient>


text:
Q: SQL Server 2008 R2 Restore a back up to a new database I have a full back up of a database, I want to update some records in some table in the current database from its old backup without affecting other records.
What is the best way to do this?
Basically I want to get some records from the old backup update old values to the current database without doing a restore, what are my options?

A: You cannot access the records in a database backup without restoring it to a database. You can however restore it to a different database from the one that it was backed up from.
The following link illustrates how to do this using Transact-SQL: http://msdn.microsoft.com/en-us/library/ms190447(v=sql.105).aspx
and in Management studio: http://msdn.microsoft.com/en-us/library/ms177429(v=sql.105).aspx
Then once you have the new database you can write SQL to join the two instances (obviously security considerations will need to be taken into account first). E.g
SELECT Table1.*, Table1_Backup.* FROM Table1
INNER JOIN DB_Restore.dbo.Table1 AS Table1_Backup ON Table1.ID = Table1_Backup.ID

or similar.
As @Flem mentions you could then use the MERGE statement to merge the two datasets, however you want.

A: You can use a third party tool for this that can read database backups and compare them to a live database (or to other database backups). Try ApexSQL Data Diff.

*

*Compare a live database to a database backup

*Filter by tables, so you don't waste time on other data

*You can use the filter to specify specific records

If this is not possible, then compare all records and tables, and once you see them in the grid, manually select the records you want to script

4 Generate the script to modify the records
You'll get the script such as this
DELETE FROM [HumanResources].[Shift] WHERE [ShiftID]=6

UPDATE [HumanResources].[Shift] SET [ModifiedDate]='20020601 00:00:00.000' WHERE [ShiftID]=1

INSERT INTO [Sales].[ShoppingCartItem] ([ShoppingCartItemID], [ShoppingCartID], [Quantity], [ProductID], [DateCreated], [ModifiedDate]) VALUES (2, N'14951', 3, 862, '20071211 17:54:07.603', '20071211 17:54:07.603')

A: I think the MERGE statement is your best option. To use this, you will need to be able to query both databases in one query (i.e. they are on the same SQL server instance or you can setup linked servers.