text:
Q: how to implement mysql query first in nodejs? ( or to implement condition query first ) it is first time to use node js So this question can be very basic question. I tried to use callback instead of just returning value but I couldn't solve the problem.
I heard that mysql query is executed after other code in node js.
But I want to put (if condition) query in the middle of the code and check the condition before implementing codes below query.
I am doing IoT thing ( sensor + android app + aws ubuntu server  with nodejs and using mysql for database )
I want to check if the sensor is working fine before adding data to server database.
So, I put the code to check if sensors are working fine before storing data in database. ( check by comparing the results from two sensors.  )
But the problem is that mysql query(to check if the sensors are right) is executed later than other code in node.js so I cannot check the condition in the middle.
How can I run condition query in the middle of the code and return any condition value?

app.get('/log', function(req, res){
        r = req.query;

        result_error = error_check(r.nickname);
        console.log("error check result"+result_error);

        insert_temp(r.nickname,r.left_num,r.right_num);
        //this function is called after error_check function, but when I saw the result, console.log in this function is called earlier than error_check function

        res.end('OK:' + JSON.stringify(req.query));
});

function error_check(nickname){
        var sql = mysql.format('select sum(left_num) as left_sum, sum(right_num) as right_sum from temp where nickname = ?  and today_date = date(current_date());',nickname);
        var query = connection.query(sql,function(err,result){
                if (err) throw err;
                console.log("Error check/// left_sum is "+result[0].left_sum + " right_sum is "+result[0].right_sum);
                if ((result[0].left_sum - result[0].right_sum >=30 )|| (result[0].right_sum - result[0].left_sum >=30 )){
                        console.log("Sensor is broken");
                        return 1;
                }
                else{
                        return -1;
                }
        });
        console.log(query);
}
/////////////////////////////but the result is
error check result undefined

(this is from insert_temp function! )nickname is ? left_num is ? right_num is ? gucheol 0 1

(this is from error_check function! this function is called before inset_temp function. error_check function is executed late...so I cannot check if sensor is wrong  )
Error check/// left_sum is 0 right_sum is 45
Sensor is broken

///but if we see the result from console/////
error check result undefined
(this is from insert_temp function! )nickname is ? left_num is ? right_num is ? gucheol 0 1
Error check/// left_sum is 0 right_sum is 45
Sensor is broken
(this is from error_check function! this function is called before insert_temp function. error_check function is executed late...so I cannot check if sensor is wrong  )

A: connection.query  is a asynchronous function so that will execute in end of event loop.
Instant of asynchronous way you can use synchronous way using util.promisify().
You can use like below to work your code,
app.get('/log', function(req, res){
        r = req.query;

        var sql = mysql.format('select sum(left_num) as left_sum, sum(right_num) as right_sum from temp where nickname = ?  and today_date = date(current_date());',r.nickname);
        var query = connection.query(sql,function(err,result){
                if (err) throw err;
                if ((result[0].left_sum - result[0].right_sum >=30 )|| (result[0].right_sum - result[0].left_sum >=30 )){
                        console.log("Sensor is broken");
                        res.end("NOT OK: Sensor is broken");
                }
                else{
                        insert_temp(r.nickname,r.left_num,r.right_num);
                        res.end('OK:' + JSON.stringify(req.query));
                }
        });
});

*

*Let me know if some error occur with this code.


text:
Q: git: aborting pull because of Gemfile.lock file which would be overwritten, even though it is in the .gitignore file I'm pulling my project with git.
I get this error: error: Your local changes to 'Gemfile.lock' would be overwritten by merge.  Aborting..
But 'Gemfile.lock' is in my .gitignore file, so git should not be interested in overwriting this file.
Any help?
Greets, Joern.

A: When a file is ignored by git, it is just excluded when you do a recursive git add. But git will never overwrite a file in a repository if it is not tracked (principe of least surprise). The ignored file could be expensive (time, ...) to generate.
However, even if a file is ignored someone can have committed a file with the same name (either with git add -f or because they have changed the .gitignore file in the same commit).
So if the file has been incorrectly added in a commit, you can rewrite history to remove it (if the repository has not been shared), you can create a new commit that remove the file in the other branch, and then merge it, or you can move away your local file, merge, and restore your local file.

A: Gemfile.lock must have been parth to the repository, otherwise git would not complain about it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to structure returned data from an api in React Native? I'm using a React Native react-native-snap-carousel which simply displays a carousel with image, title and subtitle. The data is loaded via a static file:
export const ENTRIES2 = [
  {
      title: 'Favourites landscapes 1',
      subtitle: 'Lorem ipsum dolor sit amet',
      illustration: 'https://i.imgur.com/SsJmZ9jl.jpg'
  },
  {
      title: 'Favourites landscapes 2',
      subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur',
      illustration: 'https://i.imgur.com/5tj6S7Ol.jpg'
  }
]

I have setup axios to retrieve data from an api:
axios.get('http://192.168.1.1/test')
      .then(function (response) {
        console.log(response);
        console.log(response.data);
        this.isLoading = false;
      })
      .catch(function (error) {
        console.log(error);
        this.error = error
        this.isLoading = false;
      });

how can I use this returned data to create a const structured in a similar way to the static file?
Thanks

A: It's pretty easy! You can set up your object however you need to like so. I'm assuming response.data is an array of entries here, but you'll have to modify to whatever your response uses.
axios.get('http://192.168.1.1/test')
  .then(function (response) {
    console.log(response.data);
    let data = []
    response.data.forEach(entry => {
      data.push({
        title: entry.title,
        subtitle: entry.subtitle
      })
    })
    this.isLoading = false
  })

If this method is in your component (like in componentDidMount), you can use setState to add the data to your state and then use it in your component.
...
  subtitle: entry.subtitle
})
this.isLoading = false
this.setState({data})

Then in your render method:
render () {
  const {data} = state
  return(
    <FlatList
      data={data}
      renderItem={({item}) => <Text>{item.title}</Text>}
    />
  )
}

The key here is creating the array of elements based off of what your api call returns, then saving those into the state of the component, which you can access to render them.

A: Looking the react-native-snap-carousel documentation, you can see the prop "data" is a array, look below.
return (
     <Carousel
          ref={(c) => { this._carousel = c; }}
          data={this.state.entries} <-- it's a array
          renderItem={this._renderItem}
          sliderWidth={sliderWidth}
          itemWidth={itemWidth}
         />
 );

So, in your component create a state will be receive the data from api.
state = {
    data: []
}

And use axios to retrieve the data in the componentWillMount.
componentWillMount() {
   axios.get('http://192.168.1.1/test')
      .then(function (response) {
        console.log(response);
        console.log(response.data);

        this.setState({
            data: response.data
        })

        this.isLoading = false;
      })
      .catch(function (error) {
        console.log(error);
        this.error = error
        this.isLoading = false;
      });
}


text:
Q: I make something wrong at the input of CSV I want to ask what i make wrong in csv.
I have an userinput that is "set" and I wanna "get" it into my CSV-File, but it still does not work.
That is my Method where the User take his Input in. It is in the class "auswahlMenue"
public void transaktionslisteEinlesen() throws TransaktionIOException{

    System.out.println("Transaktionsliste einlesen");

    // Einlesen von lokalen Attributen
    String beschreibungstext = MeineEingabe.erfasseString("Beschreibungstext: ");
    double betrag = MeineEingabe.erfasseDouble("Betrag:");
    LocalDateTime localdatetime = LocalDateTime.now();
    String transaktionsart = MeineEingabe.erfasseString("Transaktionsart:");
    String iban = ibangen.generate();

    /*
     * Abspreichern der lokalen Attributen in den Konstruktor der Klasse
     * Transaktion
     */
    Transaktion transaktion = new Transaktion();

    transaktion.setIban(iban);
    transaktion.setBeschreibungstext(beschreibungstext);
    transaktion.setBetrag(betrag);
    transaktion.setTart(transaktionsart);
    transaktion.setZeitStempel(localdatetime);

    TransaktionCsv transCSV = new TransaktionCsv();
    transCSV.schreibTransaktionZeilenweiseRaus("transaktion" konto.getTransaktionListe());
    konto.addTransaktion(transaktion);
    System.out.println("\nTransaktionsliste wurde eingelesen!");
}

This is the Method that i call. I open manuell the file from my project to check.
public void schreibTransaktionZeilenweiseRaus(String dateiname, ArrayList<Transaktion> transaktion) throws TransaktionIOException
{
    File datei = new File(dateiname);
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(datei));
        for (Transaktion transaktion1 : transaktion) {
            out.write(transaktion1.getIban() + ";" +transaktion1.getZeitStempel() + ";" +transaktion1.getTart() + ";" + transaktion1.getBeschreibungstext() + ";" + transaktion1.getBetrag() + ";\n");
        }
        out.close();
    } catch (FileNotFoundException e) {
        throw new TransaktionIOException("Datei existiert nicht.");
    } catch (IOException e) {
        throw new TransaktionIOException("Datei kann nicht geschrieben werden.");
    }
}

This Methode is reading the Transaktion Line-wise.
public ArrayList<String> liesTransaktionZeilenweiseEin(String dateiname) throws TransaktionIOException
{
    ArrayList<String> zeilen = new ArrayList<String>();

    File datei = new File(dateiname);
    try {
        BufferedReader in = new BufferedReader(new FileReader(datei));
        String zeile = null;
        while ((zeile = in.readLine()) != null) {
            zeilen.add(zeile);
        }
        in.close();
    } catch (FileNotFoundException e) {
        throw new TransaktionIOException("Datei existiert nicht.");
    } catch (IOException e) {
        throw new TransaktionIOException("Datei kann nicht gelesen werden.");
    }

    return zeilen;
}

The last one search a Transaktion in the CSV-File
public ArrayList<Transaktion> ermittleTransaktionAusCsv(ArrayList<String> zeilen) throws TransaktionCsvFormatException {
    ArrayList<Transaktion> transaktion = new ArrayList<Transaktion>();

    for (String zeile : zeilen) {
        String[] bestandteile = zeile.split(";");
        String iban = bestandteile[0];
        LocalDateTime zeitstempel;
        String transart =  bestandteile[2];
        String beschreibung = bestandteile[3];
        double betrag = 0.0;
        try {
            zeitstempel = LocalDateTime.parse(bestandteile[1]);
           betrag = Double.parseDouble(bestandteile[4]);
        } catch (NumberFormatException e) {
            throw new TransaktionCsvFormatException();
        }
        transaktion.add(new Transaktion(iban,zeitstempel,transart,beschreibung,betrag));
    }

    return transaktion;
}

I hope you can help me and I am sorry that I post so much code. I post so much because I am really confused.
Best Regards
GreenTea

A: I think you have complicated your writer. Just use FileWriter. See bellow:
String path = "/path/";
FileWriter writer = new FileWriter(path + dateiname + ".csv");
writer.append("data1;data2;data3");
writer.flush();
writer.close();

You can see this page is more detailled: https://www.mkyong.com/java/how-to-export-data-to-csv-file-java/
Cheers


text:
Q: Faithful linear representation of a nilpotent Lie algebra Let
\begin{align}
\mathfrak{g} = Span_{\mathbb{C}}\{ e_1, e_2, e_3, e_4, e_5: \text{ non-zero brackets are } [e_1, e_i]=e_{i+1}, i=2,3,4, [e_2, e_3]=e_5 \}
\end{align}
be a $5$-dimensional Lie algebra. I want to write $e_1, \ldots, e_5$ as matrices. That is, I need to find an injective homomorphism of Lie algebras: $\mathfrak{g} \to \mathfrak{gl}(V)$, $V$ is some vector space. Are there some general method to do this? I know that Ado's theorem says that this homomorphism always exists. But I don't know how to construct these matrices explicitly. Can some software like GAP compute the matrices of $e_1, \ldots, e_5$? Thank you very much.

A: The Lie algebra is filiform nilpotent and is generated by $e_1$ and $e_2$. It is known that any faithful Lie algebra representation $\rho:\mathfrak{f}_n\rightarrow \mathbb{gl}(V)$ of a $n$-dimensional filiform Lie algebra $\mathfrak{f}_n$ is of degree at least $n$. In the above example, we do not need to invoke Ado's theorem. It is enough to construct a faithful $5$-dimensional Lie algebra representation as follows. By Lie's theorem, we may assume that the operators $\rho(e_i)$ are simultaneously upper-triangular. We may even assume that $\rho(e_1)$ satisfies further properties. Then it is easy to compute explicit matrices $\rho(e_1)$ and $\rho(e_2)$, which determine a faithful representation of degree $5$. For details on this construction see, e.g., here, and for computational aspects and other methods in general see here, with references to GAP programs.
Edit: A short computation shows that
$$
\rho(e_1)=\begin{pmatrix} 0  & 1 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0 & 0
 \end{pmatrix},\;
\rho(e_2)=\begin{pmatrix} 0  & 0 & 3 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0
 \end{pmatrix}
$$
defines a representation of the above filiform Lie algebra, where the center is represented nontrivially, i.e., $\rho(e_5)\neq 0$, so that the representation is faithful.


text:
Q: React Metarial ui redirect to another tab after submission? I have a /home route that has two tabs, after submitting a form (I use Formik) I want to redirect the user to the first tab in the same route. So basically
 onSubmit: (values) => {
  dispatch(actions.userAdded(values));
  history.push(`/home`); // ??
},

doesn't work out. What is the best solution?
I am using MUI basic tab model.
 <AppBar position="static" color="default">
    <Tabs
      value={value}
      onChange={handleChange}
      indicatorColor="primary"
      textColor="primary"
      variant="fullWidth"
      aria-label="Rules"
    >
      <Tab label="Your Rules" {...a11yProps(0)} />
      <Tab label="Add New Rule" {...a11yProps(1)} />
    </Tabs>
  </AppBar>
  <SwipeableViews
    axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
    index={value}
    onChangeIndex={handleChangeIndex}
  >
    <TabPanel value={value} index={0} dir={theme.direction}>
      <DisplayUsers /> // I WANT TO GO HERE AFTER SUBMITION
    </TabPanel>
    <TabPanel value={value} index={1} dir={theme.direction}>
    <AddUsers />  // HERE I HAVE FORM
    </TabPanel>
  </SwipeableViews>


text:
Q: write unit test case for this method returning RxJava Future Can any one please help me to write a unit test case for this method returning RxJava Future object , I am able to write and mock for a method returning Single.
public Future<JsonObject> fetchVendorDetailsVendorIdAsFuture(String serviceURI, Map<String, String> headerMap) {

    if(vbConnectorCircuitBreaker == null){
        vbConnectorCircuitBreaker= CircuitBreakers.getVbConnectorCircuitBreaker();
    }
    return vbConnectorCircuitBreaker.execute(future -> {
        // get ok http client
        OkHttpClient client = okHTTPClientHelper.getOkHTTPClient();

        if(client != null){
            try{
                MediaType mediaType = MediaType.parse("application/json");
                Headers headers = Headers.of(headerMap);
                Request request = new Request.Builder()
                        .url(serviceURI)
                        .get()
                        .headers(headers)
                        .build();

                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    public void onResponse(Call call, Response response)
                            throws IOException {
                        String jsonData = response.body().string();
                        JsonObject jsonObject = new JsonObject(jsonData);
                        future.complete(jsonObject);
                    }

                    public void onFailure(Call call, IOException e) {

                        future.complete(null);
                    }
                });
            } catch(Exception exception) {

                future.complete(null);
            }
        } else {
            future.complete(null);
        }
    });
}

A: You can try using okhttp's MockWebServer.
That way, your Call can emit a real http request and you will be able to handle the server's response.
You can create the mocked server's response yourself using mockWebServer.enqueue(new MockResponse() ... )
There are a lot of different ways to write tests for this kind of problem and here is my suggestion:
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;

// other imports omitted

@ExtendWith(VertxExtension.class)
@Slf4j
public class VendorDetailsTest {

    private VendorDetailsVerticle sut;

    private MockWebServer mockWebServer;

    @BeforeEach
    public void setUp() {
        sut = new VendorDetailsVerticle();
        mockWebServer = new MockWebServer();
    }

    @Test
    public void testExecuteService(final Vertx vertx, final VertxTestContext testContext)
        throws InterruptedException {

        // given -----
        final JsonObject serverResponsePayload = new JsonObject().put("futureCompleted", true);
        mockWebServer.enqueue(new MockResponse()
            .setBody(serverResponsePayload.encode())
            .setResponseCode(200)
            .setHeader("content-type", "application/json"));

        // when -----
        final Future<JsonObject> jsonObjectFuture =
            sut.fetchVendorDetailsVendorIdAsFuture(mockWebServer.url("/").toString(), new HashMap<>());

        // then -----
        final RecordedRequest recordedRequest = mockWebServer.takeRequest();
        assertEquals("GET", recordedRequest.getMethod());
        assertEquals(1, mockWebServer.getRequestCount());
        testContext.assertComplete(jsonObjectFuture)
                           .map(val -> {
                               assertEquals("{'futureCompleted': true}", val.encode());
                               testContext.completeNow();
                               return val;
                           })
                           .onComplete(onComplete -> {
                               assertTrue(onComplete.succeeded());
                               log.info("done");
                           })
                           .onFailure(onError -> Assertions.fail());

    }
}

This test will of course need a little bit of customization to run in your project, but I hope it will give a picture on how to approach testing RxJava's futures.


text:
Q: How to install official php7.2 patch? I am using Magento 1.9.4.0. I try to install the PHP 7.2 support patch found here. I downloaded the version for 1.9.3.1 - 1.9.3.9.
I get:
$ patch -p0 < PATCH-1.9.3.1-1.9.3.9_PHP7-2018-09-13-08-01-43.2_v2
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/app/Mage.php b/app/Mage.php
|index 532eaca..9928cfa 100644
|--- a/app/Mage.php
|+++ b/app/Mage.php
--------------------------
File to patch:

Do I even need this patch, or does Magento 1.9.4.0 support PHP 7.2 out of the box?
I am using PHP 7.2.5

A: I found the answer here.
The instructions on the official site are wrong, you have to use patch –p1 < patch_file_name.patch instead of patch –p0 < patch_file_name.patch
So I executed patch –p1 < PATCH-1.9.3.1-1.9.3.9_PHP7-2018-09-13-08-01-43.2_v2
Then a few interactive questions showed up which I just answered with n because I had most of the patches already installed.
$ patch -p1 < PATCH-1.9.3.1-1.9.3.9_PHP7-2018-09-13-08-01-43.2_v2
patching file app/Mage.php
Hunk #1 succeeded at 56 with fuzz 2 (offset 3 lines).
patching file app/code/core/Mage/Core/Helper/Data.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Core/Helper/Data.php.rej
patching file app/code/core/Mage/Core/Model/Resource/Session.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Core/Model/Resource/Session.php.rej
patching file app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
2 out of 2 hunks ignored -- saving rejects to file app/code/core/Mage/Core/Model/Session/Abstract/Varien.php.rej
patching file app/code/core/Mage/Core/functions.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
2 out of 2 hunks ignored -- saving rejects to file app/code/core/Mage/Core/functions.php.rej
patching file app/code/core/Mage/Customer/Model/Customer/Attribute/Source/Group.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Customer/Model/Customer/Attribute/Source/Group.php.rej
patching file app/code/core/Mage/Customer/Model/Customer/Attribute/Source/Store.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Customer/Model/Customer/Attribute/Source/Store.php.rej
patching file app/code/core/Mage/Customer/Model/Customer/Attribute/Source/Website.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Customer/Model/Customer/Attribute/Source/Website.php.rej
patching file app/code/core/Mage/Customer/Model/Entity/Address/Attribute/Source/Country.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Customer/Model/Entity/Address/Attribute/Source/Country.php.rej
patching file app/code/core/Mage/Customer/Model/Resource/Address/Attribute/Source/Country.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Customer/Model/Resource/Address/Attribute/Source/Country.php.rej
patching file app/code/core/Mage/Customer/Model/Resource/Address/Attribute/Source/Region.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Customer/Model/Resource/Address/Attribute/Source/Region.php.rej
patching file app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Store.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Store.php.rej
patching file app/code/core/Mage/Install/etc/install.xml
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Install/etc/install.xml.rej
patching file app/code/core/Mage/Sales/etc/config.xml
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
2 out of 2 hunks ignored -- saving rejects to file app/code/core/Mage/Sales/etc/config.xml.rej
patching file app/code/core/Mage/Shipping/Model/Carrier/Abstract.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file app/code/core/Mage/Shipping/Model/Carrier/Abstract.php.rej
patching file app/code/core/Mage/Wishlist/Model/Observer.php
Hunk #1 FAILED at 102.
Hunk #2 FAILED at 125.
2 out of 2 hunks FAILED -- saving rejects to file app/code/core/Mage/Wishlist/Model/Observer.php.rej
patching file lib/Varien/Autoload.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file lib/Varien/Autoload.php.rej
patching file lib/Varien/File/Uploader.php
Hunk #1 FAILED at 519.
1 out of 1 hunk FAILED -- saving rejects to file lib/Varien/File/Uploader.php.rej
patching file lib/Varien/Io/Sftp.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
2 out of 2 hunks ignored -- saving rejects to file lib/Varien/Io/Sftp.php.rej
The next patch would create the file lib/mcrypt_compat/mcrypt.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
patching file lib/phpseclib/Crypt/AES.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
3 out of 3 hunks ignored -- saving rejects to file lib/phpseclib/Crypt/AES.php.rej
The next patch would create the file lib/phpseclib/Crypt/Base.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/Crypt/Blowfish.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
patching file lib/phpseclib/Crypt/DES.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
3 out of 3 hunks ignored -- saving rejects to file lib/phpseclib/Crypt/DES.php.rej
patching file lib/phpseclib/Crypt/Hash.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
29 out of 29 hunks ignored -- saving rejects to file lib/phpseclib/Crypt/Hash.php.rej
The next patch would create the file lib/phpseclib/Crypt/RC2.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
patching file lib/phpseclib/Crypt/RC4.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
5 out of 5 hunks ignored -- saving rejects to file lib/phpseclib/Crypt/RC4.php.rej
patching file lib/phpseclib/Crypt/RSA.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
101 out of 101 hunks ignored -- saving rejects to file lib/phpseclib/Crypt/RSA.php.rej
patching file lib/phpseclib/Crypt/Random.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored -- saving rejects to file lib/phpseclib/Crypt/Random.php.rej
patching file lib/phpseclib/Crypt/Rijndael.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
13 out of 13 hunks ignored -- saving rejects to file lib/phpseclib/Crypt/Rijndael.php.rej
patching file lib/phpseclib/Crypt/TripleDES.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
5 out of 5 hunks ignored -- saving rejects to file lib/phpseclib/Crypt/TripleDES.php.rej
The next patch would create the file lib/phpseclib/Crypt/Twofish.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/File/ANSI.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/File/ASN1.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/File/ASN1/Element.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/File/X509.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
patching file lib/phpseclib/Math/BigInteger.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
143 out of 143 hunks ignored -- saving rejects to file lib/phpseclib/Math/BigInteger.php.rej
The next patch would create the file lib/phpseclib/Net/SCP.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
patching file lib/phpseclib/Net/SFTP.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
41 out of 41 hunks ignored -- saving rejects to file lib/phpseclib/Net/SFTP.php.rej
The next patch would create the file lib/phpseclib/Net/SFTP/Stream.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
patching file lib/phpseclib/Net/SSH1.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
35 out of 35 hunks ignored -- saving rejects to file lib/phpseclib/Net/SSH1.php.rej
patching file lib/phpseclib/Net/SSH2.php
Reversed (or previously applied) patch detected!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
47 out of 47 hunks ignored -- saving rejects to file lib/phpseclib/Net/SSH2.php.rej
patching file lib/phpseclib/PHP/Compat/Function/array_fill.php
patching file lib/phpseclib/PHP/Compat/Function/bcpowmod.php
patching file lib/phpseclib/PHP/Compat/Function/str_split.php
The next patch would create the file lib/phpseclib/System/SSH/Agent.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/System/SSH/Agent/Identity.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/bootstrap.php,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored
The next patch would create the file lib/phpseclib/openssl.cnf,
which already exists!  Assume -R? [n] n
Apply anyway? [n] n
Skipping patch.
1 out of 1 hunk ignored


text:
Q: How to get a generic callback function or method with any types of return or parameters? I'm making some API and want to allow app developers to put their own callback function with any return types and any number of parameters. Below code is example I expect to work. I wonder how to define ?<?> userfunc in MyAPI.h
// MyAPI.h

using namespace API {
/**
* Executes callback function after a random time in its own thread.
* @param userfunc User defined callback function.
**/
void SetCallback(?<?> userfunc);
}

// application.cpp

#include "MyAPI.h"
#include <chrono>
#include <format>
#include <iostream>

std::string get_current_datetime() {
  const auto now = std::chrono::system_clock::now();
  return std::format("{:%d-%m-%Y %H:%M:%OS}", now);
}

bool callback_1(bool* triggered, std::string* registration_time) {
  *triggered = true;
  std::cout << "CALLBACK_1" << std::endl;
  std::cout << "registered: " << registration_time << std::endl;
  std::Cout << "triggered : " << get_current_datetime() << std::endl;
  return true;
}

int callback_2(int* triggered) {
  *triggered = 1;
  std::cout << "CALLBACK_2" << std::endl;
  return 1;
}

int main(void) {
  bool is_triggered_bool = false;
  int is_triggered_int = 0;
  std::string curr = get_current_datetime();
  API::SetCallback(std::bind(&callback_1, &is_triggered_bool, &curr));
  API::SetCallback(std::bind(&callback_2, &is_triggered_int))
  Sleep(3000);
  if (is_triggered_bool && is_triggered_int == 1) return 0;
  else return -1;
}

Any advice will appreciate


text:
Q: Webpack & Bower: Multiple css & js files I'm just getting started with Webpack (for use w/ React), and I'm running into an issues when trying to pull in bower packages. I have installed pickadate through bower and I have the following webpack config (original). Looking at the pickadate bower.json file, it has an array instead of just a string for main as it needs to pull in multiple js and css files.
// ./webpack/dev.config.js
// ...
resolve: {
  modulesDirectories: [
    'src',
    'node_modules',
    'bower_components'
  ],
  plugins: [
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
    )
  ],
  extensions: ['', '.json', '.js']
},

My Component:
import React, {Component, PropTypes} from 'react';

import $ from 'jquery';
import pickadate from 'pickadate';

class DateInput extends Component {
  // ...
}

I get the following errors for jquery and pickadate modules:
@ ./src/components/forms/DateInput.js 17:14-31
[0] ./src/components/forms/DateInput.js
[0] Module not found: Error: Cannot resolve module 'jquery' in /Users/chris7519/Desktop/react-redux-universal-hot-example/src/components/forms
[0] resolve module jquery in /Users/chris7519/Desktop/react-redux-universal-hot-example/src/components/forms
[0]   looking for modules in /Users/chris7519/Desktop/react-redux-universal-hot-example/src
[0]     /Users/chris7519/Desktop/react-redux-universal-hot-example/src/jquery doesn't exist (module as directory)
[0]     resolve 'file' jquery in /Users/chris7519/Desktop/react-redux-universal-hot-example/src
[0]       resolve file
[0]         /Users/chris7519/Desktop/react-redux-universal-hot-example/src/jquery doesn't exist
[0]         /Users/chris7519/Desktop/react-redux-universal-hot-example/src/jquery.json doesn't exist
[0]         /Users/chris7519/Desktop/react-redux-universal-hot-example/src/jquery.js doesn't exist

// ...

Module not found: Error: Cannot resolve module 'pickadate' in /Users/chris7519/Desktop/react-redux-universal-hot-example/src/components/forms
[0] resolve module pickadate in /Users/chris7519/Desktop/react-redux-universal-hot-example/src/components/forms
[0]   looking for modules in /Users/chris7519/Desktop/react-redux-universal-hot-example/src
[0]     /Users/chris7519/Desktop/react-redux-universal-hot-example/src/pickadate doesn't exist (module as directory)
[0]     resolve 'file' pickadate in /Users/chris7519/Desktop/react-redux-universal-hot-example/src
[0]       resolve file
[0]         /Users/chris7519/Desktop/react-redux-universal-hot-example/src/pickadate doesn't exist
[0]         /Users/chris7519/Desktop/react-redux-universal-hot-example/src/pickadate.json doesn't exist
[0]         /Users/chris7519/Desktop/react-redux-universal-hot-example/src/pickadate.js doesn't exist

I attempted to install both jquery and pickadate through npm, but I still get the error Cannot find module 'pickadate'

A: The pickadate module on npm has a broken package.json file: it doesn't specify a main entry, so webpack has no idea how to resolve require('pickadate'). You should probably file an issue upstream for them to fix this, but in the meanwhile you can fix it in your webpack.config.js.
So, you want to install both pickadate and jquery through npm, and then add the following to webpack.config.js:
{
    resolve: {
        alias: {
            'pickadate' : 'pickadate/lib/picker',
        },
    },
 }

This basically treats all instances of require('pickadate') into require('pickadate/lib/picker'). This reaches into the pickadate package and actually requires a real file. If upstream fixes their package.json to have a main entry, you can delete this alias from your config and all your requires will work properly.
More information about how the alias option works: http://webpack.github.io/docs/configuration.html#resolve-alias

A: The webpack.ResolverPlugin.DirectoryDescriptionFilePlugin doesn't handle bower.json description file when the 'main' field is an array, for example Bootstrap:
"main": [
"less/bootstrap.less",
"dist/js/bootstrap.js"
]

In that case, you should install the package using npm, and require() css files explicitly

A: I faced the same issue using a pickadate wrapper (ng-pickadate), hopefully most of the quirks will apply:

*

*Referencing the js files, pickadate package json entry point seems not to be ok.

*Disabling AMD for the pickadate node modules path.

*Add providepluing ($, Jquery, window.jquery).

Bellow the step by step guide (remove the angular part, if you just want to configure pickadate).
Following the steps mentioned in this thread, I manage to make it work without having to tweak the code under node_modules. Just a quick recap (angular 1, webpack 2 solution):
First install ng-pickadate

npm install ng-pickadate

It will download as well jquery and pickadate dependencies.

Then we need to add the depencies in our webpack.config, here there's a catch  pickadate.js package json main seems not to be pointing to the right entry point, we have to manually indicate which files we want to include:
diff
module.exports = {
  context: path.join(basePath, 'src'),
  resolve: {
    extensions: ['.js', '.ts']
  },
  entry: {
    app: './app/app.ts',
    vendor: [
+      'jquery',
+      'angular',
+      'pickadate/lib/picker',
+      'pickadate/lib/picker.date',
+      'ng-pickadate',
    ],

Now comes fun part, pickadate will try to load AMD modules, in my case we need commonjs, we don't want to change the code on the library, rather disable this
using a rule (loader), just only for the pickadate folder:
diff
  module: {
    rules: [
+      {
+        test: /pickadate/,
+        parser: { amd: false }
+      },
      {
        test: /\.ts$/,

Now let's  review our provide plugin and ensure we have all this ways of global referencing jquery (window.jquery quite important !)
diff
  plugins: [
+    new webpack.ProvidePlugin({
+      "$": "jquery",
+      "jQuery": "jquery",
+      "window.jQuery": "jquery",
    }),

It's time to start using this in our app, let's include it in the angular module where
we are using it (we are using angular 1.6):
```diff
import * as angular from 'angular';
import { LoginComponent } from './login.component';
export const LoginModule = angular.module('loginModule',
+ ['pickadate'])
  .component('login', LoginComponent)
;
```
And let's use the directive in the HTML (input)
diff

                            Birthdate
                            <input
                                type="text"
+                                pick-a-date="vm.curDate"/>

All this steps are just a recap of feedback got from several issues that were open, thanks to all the chaps that were providing the right tips :-). The parts that are new are marked with "+" (it seems stackoverflow doesn't support diff).


text:
Q: How to call a perl script from a Windows powershell script Can anyone please let me know how to call a perl script from a Windows powershell script (.ps1)?

A: You simply run it with the perl executable:
perl myscript.pl


text:
Q: Android Studio - Cannot resolve com.google.firebase.analytics I am using Android Studio and (tried) to add firebase.analytics via the menu (tools->firebase). I added the analytics function but
import com.google.firebase.analytics.FirebaseAnalytics;

results in an error since "analytics" cannot be resolved.
What is missing?
Many thanks!

A: Please make sure you've compiled all needed firebase libraries for analytics in your gradle app file.
dependencies {
  // ...
  compile 'com.google.firebase:firebase-core:11.8.0'

  // Getting a "Could not find" error? Make sure you have
  // added the Google maven respository to your root build.gradle
}

Check this for more information : https://firebase.google.com/docs/analytics/android/start/


text:
Q: Custom permalink post type not include -2 behind
I need help about custom permalink post type wordpress.
Now, I have a post with permarlink:

*

*domain.com/post-type/test

*domain.com/post-type/test-2

How can I setup format to:

*

*domain.com/post-type/test-%post-id%

*domain.com/post-type/test-%post-id% (not include -2 behind)

I've used a plugin:

*

*Custom Post Type Permalinks https://wordpress.org/plugins/custom-post-type-permalinks/
But not working, can someone please help me, thanks !

A: /**
 * unifying slug of the CPT by adding post id in the slug
 *
 * @param $slug
 * @param $post_id
 * @param $post_status
 * @param $post_type
 * @param $post_parent
 * @param $original_slug
 *
 * @return null|string|string[]
 */
function custom_permalink_slug_wp_unique_post_slug_callback( $original_slug, $slug, $post_id, $post_status, $post_type, $post_parent ) {

    // her we have to mention which post type to support
    $support_post_type = array( 'post', 'book' );

    if ( in_array( $post_type, $support_post_type ) ) {
        $slug = $slug . '-' . $post_id;
    }

    return $slug;
}

add_filter( 'pre_wp_unique_post_slug', 'custom_permalink_slug_wp_unique_post_slug_callback', 100, 6 );

Copy the above code and paste it, In your child themes functions.php file.
I have tested this out and it's working fine for me

A: Add this to your functions.php
add_filter( 'wp_unique_post_slug', function( $slug, $post_id, $post_status, $post_type, $post_parent, $original_slug ) {
  if ( $post_type == 'post' && $slug != $original_slug )
    $slug = preg_replace( '#\-[0-9]+$#', '-' . $post_id, $slug );

  return $slug;
}, 10, 6 );


text:
Q: How to connect to rabbitMQ for Azure using Serverless framework Is rabbitMQ for azure functions not supported in serverless framework?
There is a documentation corresponding to aws: https://www.serverless.com/framework/docs/providers/aws/events/rabbitmq
but I didn't find anything for Azure.
When I tried something like:
service: my-app

provider:
  name: azure
  location: West US
  runtime: nodejs14

plugins:
  - serverless-azure-functions
  - serverless-webpack

functions:
  currentTime:
    handler: main.endpoint
    events:
      - rabbitMQ: SMS
        name: myQueueItem
        connectionStringSetting: rabbitMQConnection

then was getting the error: "Binding  rabbitMQTrigger not supported".

A: Unfortunately, rabbitmq event is only available for aws provider and you cannot use it with Azure.


text:
Q: English translations of QGIS commands, algorithms and menu items For posting here at GIS SE, I often have to find the English equivalents of commands, functions, algorithms, menu items etc. of my German language version of QGIS. Sometimes, a word-by-word translation results in the exact equivalent in an english-language QGIS-installation, but sometimes they are named quite differently. So it's an effort to always find the correct description to point to the relevant menu, algorithm etc.
Is there somewhere a kind of lexicon/dictionary with translations?
Something like:
german: Eigenschaften, englisch: properties
german: Werkzeugkiste, englisch: processing toolbox
etc.
To have a translation of the official QGIS terminology would help a lot.

A: You can use a search within https://raw.githubusercontent.com/qgis/QGIS/master/i18n/qgis_de.ts
You can also use https://www.transifex.com/qgis/QGIS/language/de/ (you need to create an account) to ease the search.
Personally, it's too bothering to search as you can have multiple occurrences of text matching, so I take another approach. I change the language by going to "Settings" > "Options", "Options - General" tab, clicking on "Override System Locale", choosing "User interface translation" to "American English" then restarting QGIS to get menus in English. Do my stuff and then reset to my language when finished.
Running the following PyQGIS enable to change language in the Processing toolbox items (PS: it does not change everything as some translation strings are enabled at QGIS startup)
translator = QTranslator()
translator.load("qgis_de.qm", QgsApplication.i18nPath())
QgsApplication.installTranslator(translator)


text:
Q: Core Audio and retrieving data sources from a audio device I've managed to get a list of data sources from an audio device by using AudioObjectPropertyAddress and AudioObjectGetPropertyData().
Is it possible to get the volume of a data source without having to do a set?
The only way I can get the volume of a data source would be:

*

*set the data source id that I'm interested in as the devices's current data source

*get the volume of the device.

This is quite annoying as I would have to listen for a call back for the set of data source to be complete before I can query for the volume, and this is trouble some as I would like to query a few data sources that are on this device.
Thanks in advance!

A: I would think that you need to use the you need to use the low level AudioToolbox.framework to accomplish this. This Stackoverflow question has some sample code that lets you take the deviceID and get the volume for the specific device and it does not use callbacks.


text:
Q: Why Pythonw file is taking big CPU resources? I write a .pyw file and run it on background. But, when I do nothing, it takes 29% CPU. If I start any other software, it starts to take 49% - 50% CPU. Is there any way to reduce the CPU usage?
Code:
def check():
    time = str(datetime.datetime.now())
    time = time[11:13] + time[14:16]
    today = str(datetime.datetime.today())
    today = today[:4] + today[5:7] + today[8:10]

    file = open("alarms\\Today\\today.txt", "r")
    alarms = file.readlines()
    file.close()

    ID = ""
    hasAlarm = False
    i = 0
    while i < len(alarms):
        if time in alarms[i]:
            hasAlarm = True
            ID = alarms[i+1]
            break
        i += 2

    if hasAlarm:
        file = open("alarms\\ID\\alarmID.txt", "r")
        alarms = file.readlines()
        file.close()
        i = 0
        while i < len(alarms):
            if ID in alarms[i]:
                break
            i += 6
        name = alarms[i+1][:-1]
        showtime = change24to12(alarms[i+2][:-1])
        if os.path.exists(alarms[i+5][:-1]):
            ringtone = alarms[i+5][:-1]
        else:
            ringtone = "basic.mp3"

        app = QApplication(sys.argv)
        window = AlarmWindow(name, showtime, ringtone)

        file = open("alarms\\Today\\today.txt", "r")
        alarms = file.readlines()
        file.close()
        file = open("alarms\\Today\\today.txt", "w")
        file.writelines(alarms[2:])
        file.close()

        file = open("alarms\\Special Days\\" + today + ".txt", "r")
        alarms = file.readlines()
        file.close()
        i = 0
        flag = False
        while i < len(alarms):
            if time in alarms[i]:
                flag = True
                break
            i += 2
        if flag:
            file = open("alarms\\Special Days\\" + today + ".txt", "w")
            file.writelines(alarms[:i] + alarms[i+2:])
            file.close()

        notification.notify(title=name, message=showtime)

        app.exec()
while True:
    check()

I want that the infinite loop will run and call the function from the background.


text:
Q: Display error in | Error message |in Specflow Nunit I am writing in Feature file where I need to display error message
Here is my code:
Scenario: Registration of Client with alphanumeric ClientName
Given I have logged in as Administrator user
And  I have entered
| Field       | Value       |
| Client Name | ClientName2 |
When I goto Password
Then I should see :
| Client Name |
| ClientName2 |

Scenario: Registration of Client with ClientName containing symbols
Given I have logged in as Administrator user
And  I have entered
| Field       | Value       |
| Client Name | Client@Name |
When I goto Password
Then I should see :
| Error Message |
| Please enter only Alphanumeric characters |

I think it using like this will be easy in step definition
Please let me know can I use error message in table like client Name
Or is it against the specflow rules?

A: It seems to me that your step is a little too specific for each case. Its not exactly clear what the filed name is meant to mean in your scenario.
you have this step:
Then I should see :
| Client Name |
| ClientName2 |

Which seems to imply that the tile (Client Name) is the field you want to look in and 'ClientName2' is the value you are looking for, and then you have this in the error case:
Then I should see :
| Error Message |
| Please enter only Alphanumeric characters |

Does this imply that there is a field called Error Message?  If this is the case then I would set it up like you have done for the Given step and this as your first Then step:
Then I should see :
| Field       | Value       |
| Client Name | ClientName2 |

And this as your second Then step:
Then I should see :
| Field         | Value       |
| Error Message | Please enter only Alphanumeric characters |

If this does not represent a filed to look in then I would instead encode the different place to look in the actual step, and have a different step for checking for an error, like this:
Then I should see the client name 'ClientName2'

and
Then I should see the error message 'Please enter only Alphanumeric characters'

and make the implementation of these steps look in the correct elements on the page. This second approach has the advantage that if you decide to change how error messages are displayed (say they are warned on a popup) then you only need to change the implementation of the step which deals with the error message and you don't need to change every single step that uses an error message.
Ideally you would make your steps ignorant of the implementation. This makes the steps much more likely to be reusable.


text:
Q: std::map very slow if contents were deleted I've discovered a stange behaviour and I don't know, why it is as it is. Look at this code here:
        std::map<size_t, std::vector<Resource*>> bla;
        for(int i = 0; i<100000; i++) {
            std::vector<Resource*> blup;
            blup.push_back(new Resource());
            bla[i] = blup;
        }
        for (auto& resources : bla) {
            for (auto resource : resources.second) {
                delete resource;                        // <---- this delete here
            }
            resources.second.clear();
        }
        bla.clear();                                    // <---- this clear here

If I run this program in eclipse-debugger, the clear() on the last line took several seconds (too long in my opinion). For bigger maps (>10M elements) it needs up to several minutes(!).
But if I comment out the delete statement in the inner loop, then the clear() function become very fast (as fast as I expect it to be).
Without debugger the code is fast in both cases (with and without delete).
The class "Resource" is a small container class, containinig 2 uint64_t's and a std::string (and ofcourse some methods).
Why is clear() slow? And why it speeds up, if I don't delete the pointers. I don't understand it, because I even clear the vectors in the map. So the map should not see any pointers, it is a map between uint64_t and std::vectors.
I am using MinGw_64 for Windows (msys64, msys2-x86_64-20210419), and Eclipse.
Now I have switched to map-only without vectors. And all is fine with this. Clear is super fast, even, if I delete the pointers. But without vectors I have to think about my algorithm a little bit.


text:
Q: not find any control in cell     private void btnSaveStudy_Click(object sender, EventArgs e)
        {
            string valueFromlbl = string.Empty;

            for(int i = 0; i < tableContent.Rows.Count; i++)
            {
                for(int j = 0; j < tableContent.Rows[i].Cells.Count; j++)
                {
                    foreach(Control ctrl in tableContent.Rows[i].Cells[j].Controls)
                    {
                        Label lbl = ctrl as Label;
                        if(lbl != null)
                        {
                            valueFromlbl = lbl.Text;
                        }
                    }
                }
            }
        }

protected void Page_Load(object sender, EventArgs e)
{
HtmlTable table = null;
                HtmlTableRow row = null;
                HtmlTableCell cell = null;
                studyNumber = studyNumber + 1;
                uniqueID = uniqueID + 1;

                for(int i = 0; i < 5; i++)
                {
                    table = new HtmlTable();
                    row = new HtmlTableRow();

                    tableContent.Controls.AddAt(i, row);
                    for(int j = 0; j < 3; j++)
                    {
                        cell = new HtmlTableCell();
                        cell.Attributes.Add("Class", "csstablelisttd");
                        row.Attributes.Add("Class", "csstextheader");
                        row.Controls.AddAt(j, cell);

                        if(i == 0 && j == 0)
                        {
                            cell.InnerText = "Study : " + Convert.ToInt32(studyNumber);

                        }
                        else if(i == 1 && j == 0)
                        {
                            cell.InnerText = "Modality" + " : " + modality;
                        }
                        else if(i == 2 && j == 0)
                        {
                            cell.InnerText = "Start Date" + " : " + DateTime.Now.ToString("dd-MMM-yyyy");
                        }
                        else if(i == 3 && j == 0)
                        {
                            cell.InnerText = "Accession Number" + " : " + accessionNumber;
                        }
                        else if(i == 4 && j == 0)
                        {
                            Button btnSaveStudy = new Button();
                            btnSaveStudy.ID = "btnSaveStudy" + uniqueID;
                            btnSaveStudy.Text = "Save";
                            btnSaveStudy.Attributes.Add("Class", "cssbutton");
                            cell.Controls.Add(btnSaveStudy);
                            btnSaveStudy.Click += new EventHandler(btnSaveStudy_Click);
                        }
                        if(i == 1 && j == 1)
                        {
                            cell.InnerText = "AE Title" + " : " + schedule_Station_AE_Title;
                        }
                        else if(i == 1 && j == 2)
                        {
                            cell.InnerText = "Station Name" + " : " + schedule_Station_Name;
                        }
                        else if(i == 2 && j == 1)
                        {
                            cell.InnerText = "Start time" + " : " + startTime;
                        }
                        else if(i == 3 && j == 1)
                        {
                            cell.InnerText = "End time" + " : " + endTime;
                        }

                        else if(i == 2 && j == 2)
                        {
                            Label lblPriority = new Label();
                            lblPriority.ID = "lblPriority" + uniqueID;
                            lblPriority.Text = "Priority : ";
                            DropDownList ddlPriority = new DropDownList();
                            ddlPriority.ID = "ddlPriority" + uniqueID;
                            ddlPriority.Attributes.Add("Class", "csstextbox");
                            ddlPriority.Items.Add(new ListItem("MEDIUM", "4"));
                            ddlPriority.Items.Add(new ListItem("STAT", "1"));
                            ddlPriority.Items.Add(new ListItem("HIGH", "2"));
                            ddlPriority.Items.Add(new ListItem("ROUTINE", "3"));
                            ddlPriority.Items.Add(new ListItem("LOW", "5"));
                            cell.Controls.Add(lblPriority);
                            cell.Controls.Add(ddlPriority);
                        }
                        else if(i == 3 && j == 2)
                        {
                            Label lblStudy = new Label();
                            lblStudy.ID = "lblStudy" + uniqueID;
                            lblStudy.Text = "Study : ";
                            DropDownList ddlStudyList = new DropDownList();
                            ddlStudyList = BindStudy(ddlStudyList, Convert.ToInt32(acqModalityID), uniqueID);
                            ddlStudyList.Attributes.Add("Class", "csstextbox");
                            cell.Controls.Add(lblStudy);
                            cell.Controls.Add(ddlStudyList);
                        }
                    }
                }
            }}
I have added controls to table cell but not find any control

A: This appears to be an issue with the execution order. Remember that your controls are not added until after your click event.  So when your button click fires, the controls need to have been re-added before you can check for their existence.
(I would post this as a comment, but evidently, as I am new, I don't have enough points)

A: pass in the Page as the root and see if the control you are looking for comes back
private Control FindControlRecursive(Control rootControl, string controlID)
{
    if (rootControl.ID == controlID) return rootControl;

    foreach (Control controlToSearch in rootControl.Controls)
    {
        Control controlToReturn =
            FindControlRecursive(controlToSearch, controlID);
        if (controlToReturn != null) return controlToReturn;
    }
    return null;
}

A: You have simply forgotten to add the table itself to the page's control-collection.
Page.Controls.Add(table);

(it would be better to add it to a container control like PlaceHolder or Panel instead)


text:
Q: React Redux new data replacing current data instead of extend it and function only run once I'm using this package https://github.com/RealScout/redux-infinite-scroll to make infinite scroll on list of brand. Here is my code:
Container:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions, getBrands } from '../reducer';
import Infinite from 'react-infinite';
import InfiniteScroll from 'redux-infinite-scroll';
import SearchBox from '../components/SearchBox';
import CardList from '../components/CardList';

const { fetchBrands } = actions;

class BrandList extends Component {

    componentDidMount() {
        this.props.fetchBrands({ page: 1 });
    }

    renderList() {
        const brands = this.props.brands;
        return brands.map((brand) => {
            return (
                <CardList key={brand.id} name={brand.name} avatar={brand.avatar.thumbnail} follower={brand.follows_count} />
            );
        });

    }

    toggle() {
        return this.props.isFetching;
    }

    loadMore() {
        const {lastPage, currentPage} = this.props;
        const nextPage = currentPage ? parseInt(currentPage) + 1 : 1;
        if(currentPage && currentPage <= lastPage){
            this.props.fetchBrands({page: nextPage});
        }
    }

    render() {
        return (

                <SearchBox />

                    <InfiniteScroll
                        items={this.renderList()}
                        loadMore={this.loadMore.bind(this)}
                        />

        );
    }
}

function mapStateToProps(state) {
    return {
        brands: getBrands(state),
        isFetching: state.brand.isFetching,
        currentPage: state.brand.currentPage,
        lastPage: state.brand.lastPage
    };
}

export default connect(mapStateToProps, { fetchBrands })(BrandList);

Reducer:
import axios from 'axios';

// Define Types
export const types = {
    // brand list
    FETCH_BRANDS: 'fetch_brands',
    FETCH_BRANDS_SUCCESS: 'fetch_brands_success',
    FETCH_BRANDS_ERROR: 'fetch_brands_failure',
    FETCH_BRAND: 'fetch_brand',
    FETCH_BRAND_SUCCESS: 'fetch_brand_success',
    FETCH_BRAND_ERROR: 'fetch_brand_failure',
};

const { FETCH_BRANDS, FETCH_BRANDS_SUCCESS, FETCH_BRANDS_ERROR } = types;

// Define Reducer
export const INITIAL_STATE = { brands: [], brand: {}, isFetching: false, error: null, currentPage: 1 };

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case FETCH_BRANDS:
            return { ...state, isFetching: true };
        case FETCH_BRANDS_SUCCESS:
            return { ...state, brands: action.payload.brands.data, currentPage: action.payload.brands.current_page, lastPage: action.payload.brands.last_page };
        case FETCH_BRANDS_ERROR:
            return { ...state, error: action.payload };
        default:
            return state;
    }
}

// Define Actions
export const actions = {
    fetchBrands: ({page, count = 15}) => {
        return (dispatch) => {
            dispatch({ type: FETCH_BRANDS });
            axios.get(`brands?page=${page}&count=${count}`)
                .then((response) => {
                    const {data} = response;
                    if (data.code == 200) {
                        dispatch({ type: FETCH_BRANDS_SUCCESS, payload: data });
                    }
                });
        };
    }
};

// SELECTOR
export const getBrands = (state) => state.brand.brands;

*

*it run loadMore function successfully but it not extend current list, it replace it instead.

*loadmore function only run once. it should run 10 times.

do I miss something on my code to make it scroll?

A: Try adding
brands: [ ...state.brands, ...action.payload.brands.data]

like this in your reducer
case FETCH_BRANDS_SUCCESS:
     return { ...state, brands: [ ...state.brands, ...action.payload.brands.data], currentPage: action.payload.brands.current_page, lastPage: action.payload.brands.last_page };

Which means that you are concating current list with upcoming list (versioned data)


text:
Q: Udi Manber and Gene Myers Method I have a suffix array SA, and an array L that stores the length of LCP (longest common prefix) between two consecutive suffixes, i.e.
L[i]=LCP(SA[i-1],SA[i]) where 1<=i<=|SA|

It's also described here.
How should I use this array L to find the LCP(x,y) between given two suffixes x and y?

A: rank[0...7]: 4 6 8 1 2 3 5 7
string:      a a b a a a a b
-------------------------------------------
 sa[1] = 3 : a a a a b         height[1] = 0
 sa[2] = 4 : a a a b           height[2] = 3
 sa[3] = 5 : a a b             height[3] = 2
 sa[4] = 0 : a a b a a a a b   height[4] = 3
 sa[5] = 6 : a b               height[5] = 1
 sa[6] = 1 : a b a a a a b     height[6] = 2
 sa[7] = 7 : b                 height[7] = 0
 sa[8] = 2 : b a a a a b       height[8] = 1

Here array height is equal to array L
using array sa , we can easily calculate array rank
Then using Sparse Table (ST) algorithm to calculate rmq question.
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor#Range_Minimum_Query_%28RMQ%29
int *RMQ = height;
//int RMQ[N];
int mm[N];
int best[20][N]; //best[i][j] means the minimal value in the range [j, j + 2^i)
void initRMQ(int n){
  int i,j,a,b;
  for(mm[0]=-1,i=1;i<=n;i++)
  mm[i]=((i&(i-1))==0)?mm[i-1]+1:mm[i-1];
  for(i=1;i<=n;i++) best[0][i]=i;
  for(i=1;i<=mm[n];i++)
  for(j=1;j<=n+1-(1<<i);j++){
    a=best[i-1][j];
    b=best[i-1][j+(1<<(i-1))];
    if(RMQ[a]<RMQ[b]) best[i][j]=a;
    else best[i][j]=b;
  }
}
int askRMQ(int a,int b){
  int t;
  t=mm[b-a+1];b-=(1<<t)-1;
  a=best[t][a];b=best[t][b];
  return RMQ[a]<RMQ[b]?a:b;
}
int lcp(int a,int b){ //this is your answer
  int t;
  a=rank[a];b=rank[b];
  if(a>b) {t=a;a=b;b=t;}
  return(height[askRMQ(a+1,b)]);
}

Then just call the function lcp(). Time and space is O(nlogn)


text:
Q: Is there an advantage to using jQuery's $().on('mouseenter',function(){}) over $().mouseenter(function(){})? I frequently see code like:
$("#thing").on("mouseenter",function(){ Do stuff });

Personally, I almost always write:
$("#thing").mouseenter(function(){ Do stuff });

Similarly, I often write
$("#thing").click(function(){})

but I have seen people correct it to (yes, I know on is preferred over bind in v. 1.7+, so it's essentially the same preference issue):
$("#thing").bind("click",function(){})

Am I doing something "wrong", is there a deep difference between the two functions that I'm not seeing? It always seems to do what I want it to do, so it's never been a practical concern, but I'd be interested to know if there's a theoretical consideration I'm overlooking.

A: Not really, it's just a little faster as the mouseenter function calls on (or trigger if called without argument) as can be seen in the source code :
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );
    };
});

As you can see, the same can be said for many events.
Personally, I prefer to use the mouseenter (or click, etc.) function when I don't need the special features of on : one of the big advantages in my opinion in using jQuery is that it makes the code less verbose and more readable. And I don't think you should be corrected, ask the guys who corrects you why he does that.

A: Normally, the specific events like .click or $.post are shortcuts.  They act the same as using the .on and $.ajax functions but the latter normally have greater flexibility.  EG .on can bind to multiple event while .click only subscribes to clicks.  Same applies to the $.ajax function, there are more options where as the shortcuts have certain defaults set.

A: There's no practical difference between the two, the shorthand functions (.click(), .mouseover(), etc) call .on() to actually bind the event handler anyway. The only "advantage" to using .on() directly is that you don't have the additional overhead of a second function call; I suspect that's likely to be marginal enough that it's a very premature optimisation though.

A: It's not neccessarily wrong, but on has its advantages over the normal way.
By "binding" the event to your parent container $(parent).on(event, target, function() { //foobar }); you are able to add new target elements into your container, while not having to repeat the jquery to bind the event.


text: Q: How do environment variables work for a login shell? I am writing my own shell and I have a bit of confusion about environment variables. If you start any process logged into the user, it will have access to a few "standard environment variables" such as PATH. According to my research, the login shell sets these "standard environment variables". So logically, according to what I know about environment variables, all processes owned by the user should be child-processes of the login shell. So my question is, are all processes owned by the user indeed child-processes of the login shell, or does the login shell store environment variables in a special way so that the processes owned by the user can access them?


text:
Q: Understanding how a try except logic works within two while loops I'm having trouble understanding the mechanism of my code. I want to retrieve the realtime price data of a crypto from an exchange and print it every second, while creating a retry mechanism that catches an exception when it occurs.
while True:
    try_cnt = 10
    while try_cnt > 0:
        try:
            price = get_current_price(symbol)           # function imported from elsewhere
            print(price)
            time.sleep(1)
            try_cnt = 0
            break
        except Exception as e:
            print(e)
            try_cnt -= 1

This is how I have it set up but I'm having trouble follow the logic. This is how I see it as of now. After the code has been run:

*

*Price is retrieved

*try_cnt is set to 0 and the second while loop is broken

*The next second, try_cnt is reset to 10 and price is retrieved

*try_cnt is set to 0 again and the second while loop is broken

*repeat of this process

Am I understanding this correctly?
EDIT: the reason why I have a while loop outside is that I have other things that are going on at specific times besides the part I mentioned here. The part that I mentioned is supposed to be running all the time every second. For example,
while True:
    if now.hour == 0 and now.minute == 0 and now.second == 0:
        A = functionA(x,y)
    try_cnt = 10
    while try_cnt > 0:
        try:
            price = get_current_price(symbol)           # function imported from elsewhere
            print(price)
            time.sleep(1)
            try_cnt = 0
            break
        except Exception as e:
            print(e)
            try_cnt -= 1

A: I think that you are understanding everything just fine, but the code itself is a little silly and redundant. For example, setting try_cnt to 0 and then following that with break is pointless - both lines do the same thing. And unless there is some significance to the variable try_cnt that is not present within the code you posted, its existence seems pretty much useless to me. Here's code that does the exact same thing as the code above, but without the redundancies:
while True:
    try:
        price = get_current_price(symbol)
        print(price)
        time.sleep(1)
    except Exception as e:
        print(e)

In response to your edit, the while True loop encompassing everything makes a lot more sense. However, this means that your code isn't doing what you want it to do. The outer while loop ensures that even if try_cnt reaches 0, try_cnt will just be reset to 10 on the next pass and it will be as if no Exceptions ever occurred (besides the ten error messages in the console). If you want that inner while loop to stop executing when ten Exceptions occur, you need to place the try_cnt = 10 statement outside of both while loops like so:
try_cnt = 10
while True:
    if now.hour == 0 and now.minute == 0 and now.second == 0:
         A = functionA(x,y)
    while try_cnt > 0:
        try:
            price = get_current_price(symbol)
            print(price)
            time.sleep(1)
            try_cnt = 10
            break
        except Exception as e:
            print(e)
            try_cnt -= 1


text:
Q: Error:Unable to resolve dependency for ':app@playDebug/compileClasspath': Could not resolve project I have this problem, how can I fix these errors?
   - Error:Unable to resolve dependency for ':app@playDebug/compileClasspath': Could not resolve project :pray-times.

Unable to resolve dependency for ':app@playDebug/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes

   - Error:Unable to resolve dependency for ':app@playDebugAndroidTest/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@playDebugAndroidTest/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes

   - Error:Unable to resolve dependency for ':app@playDebugUnitTest/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@playDebugUnitTest/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

   - Error:Unable to resolve dependency for ':app@playRelease/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@playRelease/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

   - Error:Unable to resolve dependency for ':app@playReleaseUnitTest/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@playReleaseUnitTest/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

   - Error:Unable to resolve dependency for ':app@fdroidDebug/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@fdroidDebug/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

   - Error:Unable to resolve dependency for ':app@fdroidDebug/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@fdroidDebugAndroidTest/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

   - Error:Unable to resolve dependency for ':app@fdroidDebugAndroidTest/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@fdroidDebugUnitTest/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

   - Error:Unable to resolve dependency for ':app@fdroidRelease/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@fdroidRelease/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

   - Error:Unable to resolve dependency for ':app@fdroidReleaseUnitTest/compileClasspath': Could not resolve project :pray-times.
Unable to resolve dependency for ':app@fdroidReleaseUnitTest/compileClasspath': Could not resolve project :pray-times.

Could not resolve project :pray-times.
Required by:
    project :app
 > Unable to find a matching configuration of project :pray-times: None of the consumable configurations have attributes.

This is my build.gradle
buildscript {

    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        //noinspection GradleDynamicVersion
        classpath 'io.fabric.tools:gradle:+'
    }

    }

    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'

    android {
    sourceSets {
        main.assets.srcDirs += ['../changelogs']
    }

    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude '.readme'
    }

    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.metinkale.prayer"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 191
        versionName '3.6.6'
        multiDexEnabled false
        vectorDrawables.useSupportLibrary = true
    }

    dexOptions {
        javaMaxHeapSize "2g"
        preDexLibraries = false
    }

    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            zipAlignEnabled false
        }
        release {
            debuggable false
            minifyEnabled true
            zipAlignEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    flavorDimensions "store"
    productFlavors {
        fdroid {
            versionName = android.defaultConfig.versionName + " F-Droid"
            dimension "store"
        }
        play {
            versionName = android.defaultConfig.versionName + " Play Store"
            repositories {
                maven { url 'https://maven.fabric.io/public' }
            }
            dimension "store"
        }
    }

    compileOptions {
        targetCompatibility JavaVersion.VERSION_1_7
        sourceCompatibility JavaVersion.VERSION_1_7
    }

    testOptions {
        unitTests.returnDefaultValues = true
    }
    }

Everything is up to date.
    dependencies {
    playCompile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }
    //excludeInFDroid
    fdroidCompile('com.mapbox.mapboxsdk:mapbox-android-sdk:4.1.1@aar') {
        transitive = true
    }
    compile('com.mikepenz:aboutlibraries:5.8.5@aar') {
        transitive = true
    }

This application is addressed to Muslims.
    compile project(':pray-times')
    compile 'joda-time:joda-time:2.9.6:no-tzdb'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:percent:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:customtabs:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.support:preference-v14:26.1.0'
    compile 'com.koushikdutta.ion:ion:2.1.9'
    compile 'net.steamcrafted:materialiconlib:1.1.4'
    compile 'com.evernote:android-job:1.1.11'
    compile 'com.github.anrwatchdog:anrwatchdog:1.3.0'
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    playCompile 'com.google.android.gms:play-services-maps:11.8.0'
    playCompile 'com.google.android.gms:play-services-gcm:11.8.0'
    playCompile 'com.google.android.gms:play-services-location:11.8.0'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'us.feras.mdv:markdownview:1.1.0'

    }

I think the problem comes from here
This is "classpath":
    buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

I updated to the latest version.


text:
Q: Button on click creates alert to show data-id attribute I have a button like so:
<button data-id="1" onclick="showID()">Show ID</button>

And a function:
<script>
  function showID() {
   alert(($(this).data("id")));
  }
 </script>

I just want the data-id to be shown in the alert box. I've also tried
alert(($(this).data("id")));

But again nothing...

A: $(this) inside your click function indicates to either global in sloppy mode or undefined in strict mode.
You need to do like this:
<button data-id="1" onclick="showID(this)">Show ID</button>

<script>
  function showID(elem) {
   alert(($(elem).data("id")));
  }
 </script>

A: Try this

function showID(button) {
  alert($(button).attr('data-id'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button data-id="1" onclick="showID(this)">Show ID</button>

A: Currently this will not give you the right value, your code should be this way:
<button data-id="1" onclick="showID(this)">Show ID</button>

Then
<script>
  function showID(e) {
  alert(($(e).data("id")));
  }
</script>

A: this doesn't work the way you are trying.
pass this on click.
Check out this fiddle.
Here is the snippet.

function showID(ele) {
  alert(($(ele).attr("data-id")));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-id="1" onclick="showID(this)">Show ID</button>

A: Here there is an example, you have to pass the id to function in the button tag:
JavaScript - onClick to get the ID of the clicked button


text:
Q: Permission based authorization I would like users of my application to be able to create Roles dynamically and assign permissions to this roles.
Therefor Roles model is not going to be hardcoded.
Though, Permissions, as far as I understand do have to be hard-coded (because I'm going to hardcode theirs checks in application logic)
The best way I see is to keep Roles in database and create them on the fly and assign \ un-assign permissions.
And Permissions should be kept in an array (or hash, or associative array) and should be changed only by developer and require server restart.
Everything seems to be fine, but I would like to read about some best practices of permission based authorization (I can find a lot about Rolebased authorization, not Permission based) and about any possible disadvantages.
Also, I can't yet find the best way to manage "levels" of permissions.
For example, I have permissions called: "Act As Admin", "Manage Users", "Create/Read/Update/Delete User"
I would like to let Role with permission of "Act As Admin" to do everything (manager users, CRUD users etc).
Role with permission of "Manage Users" - automatically can CRUD users.
This approach is better because it won't require one to check a lot of "OR" conditions (can act as adminm, or can manage users, or can CRUD user...)
But how should I keep Permissions hash (array etc) in memory for this purposes?
I suppose, this question is language / framework / etc agnostic so I won't add such tags


text:
Q: Unable to get IAM security credentials from EC2 Instance Metadata Service error when using Aws Sdk in UWP I'm working with Aws Sdk and I'm trying to implement a login UI using UWP. I followed this online tutorial (which is for WPF) and I tried to make it works for the Universal Windows Platform as well.
The core part of the source code is the following (please note that is 90% similar to the one posted in the tutorial. The "only difference" is that I used

InitiateAuthAsync

instead of

AdminInitiateAuthAsync

    <!-- language: lang-cs -->
    private readonly AmazonCognitoIdentityProviderClient _client;
    private readonly string _clientId = "32fsoifj93fjsiispat";

    public MainPage()
    {
        this.InitializeComponent();
        var amazonCognitoIdentityProviderConfig = new AmazonCognitoIdentityProviderConfig();
        amazonCognitoIdentityProviderConfig.ServiceURL = "https://cognito-idp.eu-central-1.amazonaws.com/";
        _client = new AmazonCognitoIdentityProviderClient(amazonCognitoIdentityProviderConfig);
    }
    private async Task<bool> CheckPasswordAsync(string userName, string password)
    {
        try
        {
            List<HttpHeader> httpHeaders = new List<HttpHeader>();
            HttpHeader httpHeader = new HttpHeader
            {
                HeaderName = "X-Amz-Target",
                HeaderValue = "AWSCognitoIdentityProviderService.InitiateAuth"
            };
            httpHeaders.Add(httpHeader);
            httpHeader = new HttpHeader
            {
                HeaderName = "Content-Type",
                HeaderValue = "application/x-amz-json-1.1"
            };
            httpHeaders.Add(httpHeader);

            var authReq = new InitiateAuthRequest()
            {
                ClientId = _clientId,
                AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
            };
            authReq.AuthParameters.Add("USERNAME", userName);
            authReq.AuthParameters.Add("PASSWORD", password);

            var authResp = await _client.InitiateAuthAsync(authReq);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

Please consider that it is working properly with WPF framework. I'm able to get the TokenId and RefreshToken.
But if I try to copy and paste the same code in UWP I get the exception:

'Unable to get IAM security credentials from EC2 Instance Metadata Service.'

And if I try to investigate with Fiddler I get the following error:

[Fiddler] The connection to '169.254.169.254' failed. Error: NetworkUnreachable (0x2743). System.Net.Sockets.SocketException A socket operation was attempted to an unreachable network 169.254.169.254:80

I really can't understand why it tries to connect to the '169.254.169.254' address. Googling around I found other people experiencing the same issue (for example here). Do you have any idea?


text:
Q: can't see the HTML of a popup window how to interact with it from selenium I am trying to select Status form a new windows popup. After clicking the select status button it opens the dialog page but i can't see the HTML of that page. So not sure how to interact with that dialog page from selenium.
NB: I have switched to the new window but can't proceed from there.
HTML looks like this..

After clicking the select Status button following dialog page opens.

but i can see the html of the dialog page so how to interact with it form selenium?
Update -14/09/17
When i click on Select Status it call the below url. Opened the url in a separate tab and was able to see the HTML.

http://xxx.xxx.xxx.int/tasks/status.aspx?CurrFilters=OPEN

Tried to select a values from the new windows like below...
    public void SelectStatus()
    {
        _SelectStatus.Click();
        Browser.Switch_to_child_page();
        _container.FindElement(By.CssSelector("input[onclick^='SelectAll']")).Click();
    }

getting following error.

Test 'x.RegressionSuite.TestCases.xTest.TC_x' failed:
  OpenQA.Selenium.StaleElementReferenceException : Element is no longer
  valid

A: It looks like new windows popup. you can switch to new window. then interact with it.
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();

// Perform the click operation that opens new window

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

//select the checkbox
driver.findElement(By.xpath("xpath for checkbox")).click();

//click on select button
driver.findElement(By.xpath("xpath for submit")).click();

// Close the new window, if that window no more required
driver.close();

// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);


text:
Q: error_reporting(E_ALL) problem i have put error_reporting(E_ALL) on top of my php page now i comment this but it gives me the following notice but the rest of page work fine there is no problem in the page.
Notice: Undefined index: action in /var/www/cafe/view/ingredients.php on line 10 Call Stack: 0.0007 333108 1. {main}() /var/www/cafe/view/ingredients.php:0
what should i do to remove the notice from the top of my page.
on instructions page <form method="post" action="instructions.php?action=add&id="> and on the top of this page i get the action e.g $action=$_GET['action']; but this give me the notice –

A: Read the error message and look at the line of code it refers to (line 10). You're trying to access something ('action') which isn't defined.

A: You are trying to access index action of some array, an index that doesn't exist. Example: $some_variable['action'].
Try to run var_dump($some_variable);die; and you'll see that it doesn't exist.


text:
Q: website form date type issue  Reservation Date
 <input style="height:40px;width:300px;" type="date"   name="date">
   *<?php echo $dateErr;?>

Reservation Time
(Mon - Thur: 18:00 - 23:00 Fri - Sun: 12:00 - 00:00)
 <input type="time" align="center" style="height:40px;width:300px;" name="time">
*<?php echo $timeErr;?>

i am trying to make a form for a website. i used type date for the
  date entry and made the box larger. however the arrows are very small
  and do not take the whole box as shown in the image. does anyone know
  how to fix this ?

A: There is no native way to change the style of the arrow in the element. But you can hack a little bit around it. Check out this question. I think it's exactly what you're looking for.
Making up down arrow of HTML's input number very bigger and cleaner

A: Try to add Class and use this
.myinputdate::-webkit-inner-spin-button,
.myinputdate::-webkit-calendar-picker-indicator {
    display: none;
    -webkit-appearance: none;
 }

This only work in WebKit browser.


text:
Q: SignalR message sizes - how to know how large your messages are? I'm new to SignalR, and I'm trying to find a way to discover and print, client side, the size of the received message.
    orderHubConnection.On<OrdersViewModel>(Message.OrdersUpdate.Value, model =>
    {
        // How to obtain size of "model" here?

        HandleOrdersUpdate(model);
    });

When I work with Web API, I can access to the ContentLength like this
            response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                OrdersModel = await response.Content.ReadAsAsync<OrdersViewModel>();
                OrdersModelSize = response.Content.Headers.ContentLength;
            }

but in SignalR the message I receive is already deserialized, and it's hard to find the size of the received content.
Anyone experienced the same need? Following link asks pretty much the same question
Core SignalR message sizes - is there a way to log how large your messages are?
Thanks!


text:
Q: Volume of submanifold as integral of delta-function Let $M$ be an $n-m$ dimensional sub-manifold of $\mathbf R^n$ defined by the following set of equations:
\begin{equation}
f_1(\vec x)=0, \\
\vdots \\
f_m(\vec x)=0,
\end{equation}
(where $\vec x$ are coordinates in $\mathbf R^n$).
Is it true that the volume of $M$ is
\begin{equation}
\int d^nx\sqrt{\det (JJ^T)}\prod_{i=1}^m\delta(f_i(\vec x))
\end{equation}
where $\delta()$ is the Dirac-Delta and where $J$ is the rectangular matrix $J_{i\mu}\equiv \frac{\partial f_i(\vec x)}{\partial x^\mu}$ with $i=1,...,m$ and $\mu=1,...,n$?

A: One should distinguish between the volume of the submanifold (a number that might be infinite) and  the volume form, an exterior differential form $\omega$ of degree $n{-}m$ on the (presumed regular) 0 level set $M = f^{-1}(0)\subset \mathbb{R}^n$ of the mapping $f:\mathbb{R}^n\to\mathbb{R}^m$.
The formula for $\omega$ is easy to write down:  If $f = (f^1,\ldots,f^m)$ and we set $J^{ij} = J^{ji} =  \nabla f^i\cdot\nabla f^j$, then
$$
\omega(v_1,\ldots,v_{n-m})
= \frac{\Omega(\nabla f^1,\ldots,\nabla f^m,v_1,\ldots,v_{n-m})}{\det(J)^{1/2}},
$$
where $\Omega = \mathrm{d}x^1\wedge\cdots\wedge\mathrm{d}x^n$ is the volume form on $\mathbb{R}^n$.  Regularity is equivalent to the condition that $\det(J)$ be nonvanishing on $M=f^{-1}(0)$. This assumes, of course, that $M$ is given the orientation for which $\omega$ is a positive $n{-}m$ form.
For example, when $n=2$ and $m=1$, one finds that
$$
\omega = \frac{f_x\,\mathrm{d}y-f_y\,\mathrm{d}x}{\sqrt{{f_x}^2+{f_y}^2}}\,.
$$
There is, of course, no explicit formula for $\int_M\omega$ in terms of $f$, even when $f$ is a polynomial.


text:
Q: Output piped command to variable I'am trying to write a small script to create an JSON File. I have to store SSL Certificates inside this json, so i have to convert the CRT/KEY file to the required format.
Is there a Solution to store the result of:
cat $domain.key | sed s/$/\\n/ | tr -d '\n'

inside an Variable (bash.script)
input_key=`cat $domain.key | sed s/$/\\n/ | tr -d '\n'`

Does not run the "sed" after the cat (-:

A: This'll do it:
input_key=$(cat ${domain}.key | sed 's/$/\\n/' | tr -d '\n')

The sed is running in your example, but I believe something in the regex bits are getting interpreted by the shell. You simply need to wrap the regex in single quotes to avoid any shell interpretation. The following also works:
input_key=`cat ${domain}.key | sed 's/$/\\n/' | tr -d '\n'`


text:
Q: Convert RAID 5 to RAID 10 without data loss I have a Windows SBS 2011 server on a Dell R610 with RAID 5 configuration [3 disk].
Is there a way to convert it to RAID 10[4 or 6 disk] without losing anything or needing to re-install the whole OS and all the applications?

A: The only sane, sensible course of action is to back up and verify all your data before trying anything like this, just in case.
And if you're going to do that then you might as well go ahead and delete the old RAID array afterwards, and create a new one that is configured the way you want it to be. It's boring but if you do anything properly it's just about the only way that's guaranteed to work.

A: Assuming.. the new RAID layout presents itself to the OS in the same way as the previous RAID 5 device did..
Here be dragons
You could:

*

*Take an image with Clonezilla.

*Nuke the RAID layout, and add your disk, making it RAID 10.

*Use Clonezilla to squirt the image of your server back onto the disk.

It might be possible with other backup/imaging/clone tools too.

A: There are a few DELL raid controllers that supports "online capacity extension" (and this is exactly what you want! (; ). Here is an article covering this topic (sorry - I only found this german ressource)
http://de.community.dell.com/techcenter/systems-management/w/wiki/922.online-capacity-expansion-oce-raid-level-migration-rlm.aspx


text:
Q: Confused about marginal density My book says the following
If you have two continuous random variables $X$ and $Y$ in a joint pdf $f(x,y)$ then
$f(y)$ = $\int_{-\infty}^\infty f(x,y)dx$
$f(x)$ = $\int_{-\infty}^\infty f(x,y)dy$
My question is, is this by definition or is there a proof or theorem that gives this result. I wish to know WHY this is true.

A: Notice how $$F_{X}(x)=\mathbb{P}(X\leq x)=\int_{-\infty}^{\infty} \int_{-\infty}^x f_{XY}(t,y)dtdy$$ Take a derivative with respective to $x$ gives
$$f_{X}(x)=\int_{-\infty}^{\infty}\frac{d}{dx}\Bigg[\int_{-\infty}^xf_{XY}(t,y)dt\Bigg]dy=\int_{-\infty}^{\infty}f_{XY}(x,y)dy$$ Similar for $f_{Y}(y)$.


text:
Q: Can phppgadmin access a website database? I've a database with credentials which is my website's database.
Is there a way from my local machine to access this database using IP, User and Password?
Using Ubuntu 18.04, phppgadmin and PostgreSQL.
Thanks.

A: Yes, if you have root access to the server.

Warning: this method not recommended if you don't have a static IP address because you would need to open up your database to the world, which is disabled by default as a security measure, better use the method below.

If you want to ignore my warning:
In postgresql.conf:
listen_addresses = '*'
#or
listen_addresses = 'your-static-ip'

In pg_hba.conf add this to allow remote connections from any IP:
host    all             all              0.0.0.0/0                       md5
#or
host    all             all              your-static-ip/32               md5

Recommended method:
If you can connect to the server with ssh, there is a better/safer method:
Create a local port forwarding tunnel first:
ssh -L 5432:127.0.0.1:5432 your-server.com
#or
ssh -L 5432:localhost:5432 your-server.com

This will forward a local port via ssh to a port on your server. Then you can connect to that port using localhost as host.

A: Very probably not.
The provider that hosts the website will have restricted access to the database to requests coming from the web server. All other requests are ignored. Otherwise, they would be under a constant attack from hackers wanting to break into the database.
So the only programs that can access the database are those that run on your web server. Usually that means PHP programs, like those that your website is built from. Credentials to access the database will be stored in a config file. Additionally, as a service, hosting companies usually provide PHPMyAdmin (in the case of MySQL) or PHPPGAdmin (for PostgreSQL). With the latter, you need to provide database credentials yourself.


text:
Q: LMAX Disruptor Timeout EventHandler We have a system using Disruptor framework, it has five registered stages implementing EvenetHandler.
The stages work in Sequence, so a request can only move to second stage when the first stage is completed, this movement is maintained by Disruptor internally.
We have problem with the third stage, it's the bottleneck which takes lot of time as it makes different HTTP calls and stores response in the request object.
So, we want to move the request(with whatever response it has) ahead with the fourth and  fifth stage after some time has been spend in the third stage.
How can i timeout any specific stage(in this case Third stage) and forcefully move the request to the next stage ?
Or,
Is there a way to register some event which gets triggered after some defined timeout, this could be something like system level timeout ?

A: A solution we  tried is

*

*Have a hang detection thread which monitors the sequences processed by a stage ( or all the stages). Have a timing information in the Event processor itself.

*On time out interrupt the event processor thread. Which should make the event processor exit from the spin it is doing. So here we lost  the thread ( or one of the threads ) processing the stage

*Replace the event processor thread.

Solution needs writing our own event processor which is interrupt aware and a provision to add event stages dynamically to the disruptor