text:
Q: Show that $\sqrt{7}\notin\mathbb{Q}(\alpha)$, with $\alpha$ a root of $X^7+6X^3+3X+15$ Let $f=X^7+6X^3+3X+15\in\mathbb{Q}[x]$, and $\alpha\in\mathbb{C}$ such that $f(\alpha)=0$. I want to show $\sqrt{7}\notin\mathbb{Q}(\alpha)$
First of all, by Eisenstein's criterion, $f$ is irreducible in $Q[x]$, so we can say that $\deg (\text{Irr}(\alpha,\mathbb{Q}))=7=\left[\mathbb{Q}(\alpha):\mathbb{Q}\right]$.
Then, $\left\{1,\alpha,\ldots,\alpha^6\right\}$ is a $\mathbb{Q}$-basis of $\mathbb{Q}(\alpha)$. Then, $\sqrt{7}\in\mathbb{Q}(\alpha)\Longleftrightarrow \sqrt{7}=\lambda_0 1+\lambda_1\alpha+\cdots+\lambda_6\alpha^6$ with $\lambda_i\in\mathbb{Q}$. But I get stuck here. How should I proceed?

A: We take it as given, from user203327's work as expressed in the body of this question, that $[\Bbb Q(\alpha): \Bbb Q] = 7$.
Now suppose $\sqrt{7} \in \Bbb Q(\alpha)$; then we would have the tower of fields $\Bbb Q \subset \Bbb Q(\sqrt{7}) \subset \Bbb Q(\alpha)$.  We note that the quadratic polynomial $X^2 - 7$ is irreducible over $\Bbb Q$, since $\sqrt{7} \notin \Bbb Q$; thus $[\Bbb Q(\sqrt{7}): \Bbb Q] = \deg(X^2 - 7) = 2$.
Since $\Bbb Q \subset \Bbb Q(\sqrt{7}) \subset \Bbb Q(\alpha)$, we have $[\Bbb Q(\alpha): \Bbb Q] = [\Bbb Q(\alpha): \Bbb Q(\sqrt{7})][\Bbb Q(\sqrt{7}): \Bbb Q]$; substituting in for $[\Bbb Q(\alpha): \Bbb Q]$ and $[\Bbb Q(\sqrt{7}): \Bbb Q]$ yields the equation $2[\Bbb Q(\alpha): \Bbb Q(\sqrt{7})] = 7$.  But $2 \not \mid 7$; this contradiction shows that $\sqrt{7} \notin \Bbb Q(\alpha)$.  QED.


text:
Q: SQL-Statement: Calendar event related to contact I am in the process of developing an SQL query to let HeidiSQL display the calendar entries and connected contacts.
The appointments are included in the vtiger_activity table and the contacts in the vtiger_contactdetails table. A connection exists through the table "vtiger_crmentity".
SELECT a.subject
     , a.activitytype
     , a.date_start
     , a.due_date
     , a.time_start
     , a.time_end
     , d.firstname
     , d.lastname
  FROM vtiger_activity a
  LEFT
  JOIN vtiger_crmentity c
    ON c.crmid = a.activityid
  LEFT
  JOIN vtiger_contactdetails d
    ON d.contactid = c.crmid
 WHERE a.due_date >= '2019-05-18' AND a.date_start <= '2019-05-23'

Result of Query: it shows the dates in the time period but in the columns where it should show the contact is everywhere only NULL The query I need it for a Android App. I expected firstname and lastname, because the data exists.
Does anyone know where I have my mistake?
Ever thank you for your help

A: Your LEFT JOINs are in the wrong order.  If you want the names, they are from the details table, and that should be the first table in the FROM.  You will also need to move the conditions to the ON.
Something like this:
SELECT d.firstname, d.lastname, a.subject, a.activitytype
       a.date_start, a.due_date, a.time_start, a.time_end
FROM vtiger_contactdetails d LEFT JOIN
     vtiger_crmentity c
     ON d.contactid = c.crmid LEFT JOIN
     vtiger_activity a
     ON c.crmid = a.activityid AND
        a.due_date >= '2019-05-18' AND
        a.date_start <= '2019-05-23';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Photoshop-like navigator for website Are there any plugins or ideas about how to achieve a Photoshop-like navigator for a website?
What I mean is that the website is much wider/longer than the viewport and the user shall see in a small panel which part of the website he currently sees.
Appreciate every hint.
Update: some keywords I found so far: navigation / overview pane, birdview

A: I finally found jQuery.fracs which works perfectly for me: https://larsjung.de/jquery-fracs/


text:
Q: How can I reset a developing macOS app(Using UserDefaults and Realm) elegantly? In iOS developing, we can reset an app by uninstalling&reinstalling it, but in macOS developing, I have to find my app's UserDefaults plist and delete it, and run this line to flush the realm db:
try! FileManager.default.removeItem(at:Realm.Configuration.defaultConfiguration.fileURL!)
Is there a more elegant way to do all the things above?
Or just a better way to reset the realm db?

A: If you don't mind deleting the files yourself they are located in two different locations:

*

*NSUserDefaults are located in ~/Library/Preferences/your.app.bundle.identifier.plist
(see this answer too: https://stackoverflow.com/a/12637976/4063602)

*Your Realm file is located at: ~/Library/Application Support/your.app.bundle.identifier/ (see this answer too: https://stackoverflow.com/a/38280282/4063602)

Hope that helps you.


text:
Q: Why is bitset throwing out_of_range error? I am implementing a bloom filter with help of bitsets in c++ for finding out malicious URLs.
I have a bitset of 100 bits and a simple hash function. But still I get this error.
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define m 100
#define k 1

ll hash1(string str)
{
    ll value=0;
    for(ll i=0;i<str.size();i++)
    {
        value=(value+str[i])%m;
    }
    return value;
}

int main(int argc, char *argv[])
{
    vector<bitset<m>>v(1);
    ifstream fin;
    fin.open(argv[1]);

    string line;
    string temp;
    while(getline(fin,line))
    {
        vector<string>row;
        stringstream s(line);
        string word;
        while(getline(s ,word, ','))
        {
            row.push_back(word);
        }
        if(row.size()!=2) continue;
        for(ll i=0;i<k;i++)
        {
            if(row[1]=="bad")
            {
                v[0].set(hash1(row[0]));
                cout<<row[0]<<" inserted into bloom filter\n";
            }
        }
        row.clear();
    }
    //Now bitset contains all the malicious urls
    //Generating validation dataset
    fin.clear();
    fin.seekg(0);

    vector<vector<string>>validation;

    while(getline(fin,line))
    {
        vector<string>row;

        ll x=rand()%10;
        if(x>0) continue;

        string word;
        stringstream s(line);
        while(getline(s,word,','))
        {
            row.push_back(word);
        }
        validation.push_back(row);
        row.clear();
    }

    for(ll i=0;i<validation.size();i++)
    {
        if(v[0].test(hash1(validation[i][0])))
        {
            if(validation[i][1]=="bad")
            {
                cout<<i+1<<" : True Positive\n";
            }
            else
            {
                cout<<i+1<<" : False Positive\n";
            }
        }
        else
        {
            cout<<i+1<<" : True Negative\n";
        }
    }
    return 0;
}

The error is:-
terminate called after throwing an instance of 'std::out_of_range'
what():  bitset::set: __position (which is 18446744073709551587) >= _Nb (which is 100)
Aborted (core dumped)
The dataset contains 2 columns viz. URLs and good/bad.
This is a link to the dataset.
https://www.kaggle.com/antonyj453/urldataset

A: After reading carefully I thought the reason could be signed characters. If
signed characters are involved,
for (char i : str) {
    value = (value + i) % m;
}

could result in negative hashes. However it's unlikely that this would actually
happen, since urls don't often contain high ascii (indeed you would expect
their IDNA encoded
version
to be in the list).

A quick check reveals 70 such domains in the list
xn---21-6cdxogafsegjgafgrkj4opcf2a.xn--p1ai/images/aaa/,bad
xn--cafsolo-dya.de/media/header/A.php,bad
xn--b1afpdqbb8d.xn--p1ai/web/data/mail/-/aaaaa/Made.htm,bad
xn-----6kcbb3dhfdcijbv8e2b.xn--p1ai/libraries/openid/Auth/OpenID/sec/RBI/index/index.htm,bad

etc.

If that's not the case, then something else is throwing out_of_range.
Nothing /should/ because operator[] doesn't bounds-check according to the
standard.
However maybe some implementations do the bounds-checking in Debug builds (look
at MSVC here, they have all manner of iterator debugging enabled by default in
Debug builds, so maybe this as well?).

Ironically you could use some  bounds-checking yourself e.g. here:
int main(int argc, char* argv[]) {
    std::vector<std::string_view> const args(argv, argv + argc);
    std::string const filename(args.at(1));

This way you don't just invoke Undefined
Behaviour when the command
line argument is not given.

Line Ends
There's a gotcha with line-ends. The files are CRLF, sothe way you parse the
columns results in the last column containing "bad\r", instead of "bad" on
Linux .
Review/Simplify
In the search for other bugs I've simplified the code. It will perform a lot
better now. Here's the run-down of improvement suggestions.

*

*The includes. Just include what you need, really
#include <bitset>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

*No need for wonky types or macros.
static constexpr size_t m = 100;
static constexpr size_t k = 1; // unused for now

*As mentioned before, protect against signed character results:
static size_t hash1(std::string_view str) {
   size_t value = 0;
   for (unsigned char i : str) {
       value = (value + i) % m;
   }
   return value;
}

*Also as mentioned before protect against trailing special characters in the
classification text:
enum goodbad { good, bad, invalid }; // The Good, The Bad and ...

static goodbad to_classification(std::string_view text) {
    if (text == "bad") return bad;
    if (text == "good") return good;
    return invalid;
}

*Next up, a big one. You parse through the same file twice. And repeat the
code. Let's not. Instead have a function that parses it, and pass it a
callback to decide what to do with the parsed data.
While we're at it, let's stop ubiquitous vector<vector<vector<string> > >
disease. Really, you know how many columns there are, and what they mean.
This also reduces the allocations by a lot.
void process_csv(std::string filename, auto callback) {
    std::ifstream fin(filename);

    std::stringstream ss;
    for (std::string line; getline(fin, line);) {
        std::string_view row(line);

        // eat line end remnants
        row = row.substr(0, row.find_last_not_of("\r\n") + 1);

        if (auto comma = row.find_last_of(','); comma + 1) {
            auto url     = row.substr(0, comma);
            auto goodbad = row.substr(comma + 1);
            auto classif = to_classification(goodbad);

            if (classif == invalid)
                std::cerr << "Ignored unclassified line '" << row << "'\n";
            else
                callback(url, to_classification(goodbad));
        }
    }
}

That's all. Notice a key insight where we split using the last comma only. Because otherwise you got wrong results in case the url contained commas.

*Now, you can piece together the main program:
int main(int argc, char* argv[]) {
    std::vector const args(argv, argv + argc);
    std::string const filename(args.at(1));

Starting with the aforementioned safe way to use the command line arguments,
std::bitset<m> bloom;

reducing the verbosity vector<vector<> > syndrome (and improving the name - v?!)

*Here comes the first file reading pass:
size_t bloom_size = 0;
process_csv(filename,
    [&](std::string_view url, goodbad classification) {
        if (classification == bad) {
            bloom_size += 1;
            bloom.set(hash1(url));
            //std::cout << url << " inserted into bloom filter\n";
        }
    });

I decided it would not be necessary (and slow) to print all bad urls, so
let's print the number of them instead:
// Now bitset contains all the malicious urls
std::cerr << "Bloom filter primed with " << bloom_size << " bad urls\n";

*Now the validation pass:
// do a 1 in 10 validation check
process_csv(filename,
    [&bloom, line = 0](std::string_view url,
                       goodbad classification) mutable {
        line += 1;
        if (rand() % 10) return; // TODO #include <random>

        auto hit      = bloom.test(hash1(url));
        bool expected = (classification == bad);

        std::cout << line << ": " << std::boolalpha
                  << (hit == expected)
                  << (hit ? " positive" : " negative") << "\n";
    });
}

Live Demo
Live On Coliru
#include <bitset>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

static constexpr size_t m = 100;
//static constexpr size_t k = 1;

static size_t hash1(std::string_view str) {
    size_t value = 0;
    for (unsigned char i : str) {
        value = (value + i) % m;
    }
    return value;
}

enum goodbad { good, bad, invalid }; // The Good, The Bad and ...

static goodbad to_classification(std::string_view text) {
    if (text == "bad") return bad;
    if (text == "good") return good;
    return invalid;
}

void process_csv(std::string filename, auto callback) {
    std::ifstream fin(filename);

    std::stringstream ss;
    for (std::string line; getline(fin, line);) {
        std::string_view row(line);

        // eat line end remnants
        row = row.substr(0, row.find_last_not_of("\r\n") + 1);

        if (auto comma = row.find_last_of(','); comma + 1) {
            auto url     = row.substr(0, comma);
            auto goodbad = row.substr(comma + 1);
            auto classif = to_classification(goodbad);

            if (classif == invalid)
                std::cerr << "Ignored unclassified line '" << row << "'\n";
            else
                callback(url, to_classification(goodbad));
        }
    }
}

int main(int argc, char* argv[]) {
    std::vector const args(argv, argv + argc);
    std::string const filename(args.at(1));

    std::bitset<m> bloom;

    size_t bloom_size = 0;
    process_csv(filename, [&](std::string_view url, goodbad classification) {
        if (classification == bad) {
            bloom_size += 1;
            bloom.set(hash1(url));
        }
    });

    // Now bitset contains all the malicious urls
    std::cerr << "Bloom filter primed with " << bloom_size << " bad urls\n";

    // do a 1 in 10 validation check
    process_csv(filename,
        [&bloom, line = 0](std::string_view url,
                           goodbad classification) mutable {
            line += 1;
            if (rand() % 10) return;

            auto hit      = bloom.test(hash1(url));
            bool expected = (classification == bad);

            std::cout << line << ":" << std::boolalpha
                      << (hit == expected)
                      << (hit ? " positive" : " negative") << "\n";
        });
}

On Coliru only the bad dataset fits, so we never get any positives
g++ -std=c++2a -O2 -Wall -pedantic -pthread main.cpp
./a.out bad.csv  | cut -d: -f2 | sort | uniq -c | sort -n

Prints
Ignored unclassified line 'url,label'
Bloom filter primed with 75643 bad urls
Ignored unclassified line 'url,label'
   7602 true positive

On my own system:

Oh, and it runs in 0.4s instead of 3.7s before.
After parsing bug fix even faster: 0.093s on average for the full set.


text:
Q: How to sum the (pattern - 00h 00m 00.000s) time information in a column in google spreadsheet? I have a column in my excel/google spreadsheet with data of the pattern 00h 00m 00.000s . that is hours minutes and seconds data. I would like a total value (summation) of the values in the column and get the total hours mins seconds value.
I could do this by splitting the column values summing individual columns and then adding them. But I wanna know if there is any better efficient formula available.
Sample Data
CoL
00h 02m 36.947s
00h 01m 37.988s
00h 02m 52.138s
00h 03m 31.210s
00h 03m 11.153s

Total = Need Total related formula Here

A: You can convert the string to seconds separately in a adjacent column with a formula
=VALUE(MID(A1,1,2))*3600+VALUE(MID(A1,5,2))*60+VALUE(MID(A1,9,6))

Then you can reach to the standard format by using =SUM(B1:B5)/86400 and converting to the time format (in the ribbon)

A: Alternative, formatted as Duration (with milliseconds):
 =ArrayFormula(sum(1*left(regexreplace(A1:A,"[hms]",":"),14)))

assuming data is in ColumnA.


text:
Q: Is it possible to determine if a website has been encoded? So here's the problem leading to that question: I've got a tracking script that is causing my Google Ads text ads to be disapproved for having "Malicious or unwanted software." Neither is on the script.
The PHP script is encoded using eval(gzinflate(substr(base64_decode. Since hacked websites are often encoded (again, the one in question is not hacked), I'm wondering if Google is able to recognized that the site is encoded and that's triggering the red flag.
Thanks for any help on this.


text: Q: how to fill automatically one field of gravity form with phone number of WooCommerce customer? I make a form with id=1 and append three inputs I want to fill automatically phoneuserwc field  with billing_phone of the user


text:
Q: USPS API Address Validation Fail I'm trying to use the USPS API to validate an address. I've gone through the registration process, testing, and promotion to production.
I'm using PHP and the simplexml_load_file function to make the call. When I make the call in PHP, USPS returns an error:
[Number] => 80040B1A
[Description] => API Authorization failure. Verify is not a valid API name for this protocol.
[Source] => USPSCOM::DoAuth

If I copy and paste the url passed to the simplexml_load_file function, I get a successful response:
<AddressValidateResponse><Address ID="0"><Address2>1228 E MAIN ST</Address2><City>MONTROSE</City><State>CO</State><Zip5>81401</Zip5><Zip4>5821</Zip4></Address></AddressValidateResponse>

The url I'm using is (user ID changed):
http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=%3CAddressValidateRequest%20USERID=%123usrid456%27%3E%3CAddress%20ID=%270%27%3E%3CAddress1%3E1228%20East%20Main%20Street%3C/Address1%3E%3CAddress2%3E%3C/Address2%3E%3CCity%3EMontrose%3C/City%3E%3CState%3ECO%3C/State%3E%3CZip5%3E81401%3C/Zip5%3E%3CZip4%3E%3C/Zip4%3E%3C/Address%3E%3C/AddressValidateRequest%3E

I've called in to the 800 ICCC USPS number twice. The documentation is lacking in several respects, for instance, they say after registration the email will contain the url of the testing servers, but they aren't in the email. Also, having to call in for support and waiting on hold for almost an hour each time is frustrating. Ok, so enough complaining. Otherwise, USPS is awesome.
I've read numerous posts, and tried what was suggested, but haven't been able to make the call in PHP work. Here's what I've tried:

*

*urlencode the XML string in the url submitted

*urlencode the entire url

*test and production servers

*curl instead of simplexml_load_file

*I've copied the url that works from the browser address bar and pasted it into the PHP code - and I still get the same error.

I'm at a loss as what I should try next. Especially when I take the url passed to simplexml_load_file and copy/paste it into the browser address bar works properly.
Here's a snippet I've tried:
$url = "http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=<AddressValidateRequest%20USERID='123usrid456'><Address ID='0'><Address1></Address1><Address2>1228 East Main Street</Address2><City>Montrose</City><State>CO</State><Zip5>81401</Zip5><Zip4></Zip4></Address></AddressValidateRequest>";
$addr_data = simplexml_load_file($url);

User ID changed in the code above
I'm sure I'm missing something obvious.
Thanks in advance!
Sloan

A: Along with the HTTP GET request you not only send the address (which is presumably the same in your browser and simpleXML) but a bunch of headers too (e.g. cookies). I hazard a guess that the API also checks those headers. It is a bit odd for me that a user name is specified but access information (token/key/password) is not - aren't they sent by your browser as cookies? Take a new look at the API specification, especially general/authentication chapters; maybe you just forgot some prerequisite that is stashed away in those.
Here's what I'd do:

*

*Transition temporarily to curl so I can change the headers.

*Use the network debugger of a browser (e.g. Firefox F12->Net) to see what headers are sent.

*Set up the exactly same headers in curl and see if it works. If it does not the discontinue with this approach.

*Remove header one-by-one to see which are essential to success.


text:
Q: $S$ is bounded if and only if $D=\{\mathbf 0\}$ The set of all recession directions of the polyhedron $S=\{\mathbf x:\mathbf A\mathbf x \le \mathbf b ,\mathbf x \ge \mathbf 0\}$ is equal to  the set $D=\{\mathbf d:\mathbf A\mathbf d \le \mathbf 0 ,\mathbf d \ge \mathbf 0\}$, Use this to show that the set $S$ is bounded if and only if $D=\{\mathbf 0\}$

Assume $S$ is bounded by $M$ and let $\mathbf d$ be a recession directions of the polyhedron, then $\forall \mathbf x \in S,\forall \lambda \ge 0: \mathbf x +\lambda \mathbf d \in S$, since $S$ is bounded by $M$ it follows that $$\forall \mathbf x \in S,\forall \lambda \ge 0:|| \mathbf x +\lambda \mathbf d || \le M$$
I somehow was going to show that $||\mathbf d|| \le 0$ and since from the definition of norms $||\mathbf d|| \ge 0$ so $||\mathbf d||=0$ which shows that $\mathbf d =\mathbf 0$, but I could not prove the result.

A: On one hand if $\mathbf{d} \in D$ is nonzero and $\mathbf{x} \in S$ is any point then $A (\mathbf{x} + \lambda \mathbf{d}) = A \mathbf{x} + \lambda A \mathbf{d} \leq A \mathbf{x} \leq \mathbf{b}$ for all $\lambda > 0$, which shows that $S$ is unbounded (because $\mathbf{x} + \lambda \mathbf{b} \in S$ for arbitrarily large $\lambda$). This proves the contrapositive of the argument which you couldn't complete.
On the other hand the other direction is harder and a question equivalent to this direction has been answered before on this site: If $P$ is an unbounded polyhedron, there exists a point $c \in P$ and a vector $d \neq 0 $ such that $ \forall \lambda \geq 0$, $c+ \lambda d \in P$
But the argument is just that if $(\mathbf{x}_n)$ is a sequence in $S$ converging to infinity and $\mathbf{x} \in S$ is a fixed point, then the differences $\mathbf{x}_n - \mathbf{x}$ are eventually nonzero, in which case the new sequence of unit vectors $\mathbf{y}_n := \frac{\mathbf{x}_n - \mathbf{x}}{\lVert \mathbf{x}_n - \mathbf{x} \rVert}$ is eventually well-defined. By compactness of the finite dimensional unit ball there exists a subsequence $(\mathbf{y}_{n_k})$ converging to some $\mathbf{y}$. Of course $\mathbf{y}$ is a unit vector, so cannot be zero. The claim is then that $\mathbf{y} \in D$: to check this just observe (as in the linked question, since $A \mathbf{x_n} \leq \mathbf{b}$ for all $n$) that
$$
A \mathbf{y}
= \lim_{k \to \infty} A \mathbf{y}_{n_k}
= \lim_{k \to \infty} \frac{A \mathbf{x}_{n_k} - A \mathbf{x}}{\lVert \mathbf{x}_{n_k} - \mathbf{x} \rVert}
\leq \lim_{k \to \infty} \frac{\mathbf{b} - A \mathbf{x}}{\lVert \mathbf{x}_{n_k} - \mathbf{x} \rVert} = 0.
$$
In particular the last limit is zero because $\lVert \mathbf{x}_{n_k} \rVert \to \infty$ and thus $\lVert \mathbf{x}_{n_k} - \mathbf{x} \rVert \to \infty$ as $k \to \infty$. Because $\mathbf{y}$ is nonzero $D$ cannot be $\{\mathbf{0}\}$, so this completes the proof.


text:
Q: Centos/Polkit - allowing user to restart specific service I was wondering if anyone had a workaround for the following issue:
I'm on CentOS using systemd v219.
What I want to do is allow a non-root user to restart tomcat, but for this systemd version the action object doesn't seem to have keys defined for 'unit' (let alone for 'verb'), so it seems to be all or nothing. Either I allow that user free use of org.freedesktop.systemd1.manage-units which lets them restart any service or none.
Is there a workaround for this?
Thanks!


text:
Q: What is the proper way to sweep over all configs in an external config group? I want to store a config group in an external package and then sweep across all configs in that group with a hydra multirun call using glob(*), but the glob(*) doesn't seem to find the available configs.
Specifically, suppose I have some .yaml settings at the root of an external python package called hydra_demo.
hydra_demo
├── __init__.py
└── hyper_param_settings
    ├── v1.yaml
    ├── v2.yaml

My primary config file adds the package to the searchpath:
hydra:
  searchpath:
    - pkg://hydra_demo

As expected, I can use command-line override to use either config in the config group:
$ python experiments/main.py '+hyper_param_settings@=v1'
param=111

$ python experiments/main.py '+hyper_param_settings@=v2'
param=222

Also, as expected, if I don't specify a config from the group, it lists out the two options:
$ python experiments/main.py '+hyper_param_settings@='
In 'config': Could not find 'hyper_param_settings/'

Available options in 'hyper_param_settings':
        v1
        v2
Config search path:
        provider=hydra, path=pkg://hydra.conf
        provider=main, path=file:///path/to/experiments
        provider=hydra.searchpath in main, path=pkg://hydra_demo
        provider=schema, path=structured://

Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.

However, using glob to run all options doesn't work as I would have expected:
$ python experiments/main.py '+hyper_param_settings@=glob(*)' -m
[2021-12-30 22:42:53,656][HYDRA] Launching 0 jobs locally

But if I copy the hyper_param_settings folder from the package into the folder where the primary config is, I do get the expected behavior (but without achieving my goal of having the config groups in a separate package):
$ python experiments/main.py '+hyper_param_settings@=glob(*)' -m
[2021-12-30 22:43:17,342][HYDRA] Launching 2 jobs locally
[2021-12-30 22:43:17,342][HYDRA]        #0 : +hyper_param_settings@=v1
param=111
[2021-12-30 22:43:17,430][HYDRA]        #1 : +hyper_param_settings@=v2
param=222

Can anyone spot where I'm misunderstanding hydra?


text:
Q: SonarQube Analysis / Results / Issues by Team or Group Running SonarQube 5.6.7 and need to know if SonarQube can be configured to provide analysis of activity and issues by Team or Group, in addition to the already existing filter by Author

A: Nothing in the sonar-scm-jazzrtc source code suggests it can focus on activities (change sets) (by group/Team or not)
The plugin is just here to checkout the code (from the current stream) in a local workspace, in order for the Sonarqube scanner to scan.


text:
Q: How to create chart for date and time I get wrong chart when I create line chart. Could someone please advise what I am doing wrong here. Below are the column in excel

I get below output. Y axis not showing number above 1 and I dont see any line inside the chart

A: It seems that the hours are all in text format that caused the problem.
You can use this formula to convert the text into hours:
=NUMBERVALUE(B2)*24

See below example:


text:
Q: Showing properties of polynomials given by a two-term recursion. I'm currently dealing with the following kind of two-term recursion for real polynomials $p_{k}(x)$, $k \in \mathbb{N}$:
\begin{eqnarray}
 p_{0}(x) &=& 1, \\
 p_{1}(x) &=& 1-2x, \\
 p_{k+1}(x) &=& -p_{k-1}(x) + p_{k}(x)\left(2 - 4x\right).
\end{eqnarray}
Rewinding the recursion for the first few polynomials would give the following expanded forms:
\begin{eqnarray}
 p_{2}(x) &=& 1 - 8 x + 8 x^2, \\
 p_{3}(x) &=& 1 - 18 x + 48 x^2 - 32 x^3, \\
 p_{4}(x) &=& 1 - 32 x + 160 x^2 - 256 x^3 + 128 x^4, \\
 p_{5}(x) &=& 1 - 50 x + 400 x^2 - 1120 x^3 + 1280 x^4 - 512 x^5 \\
 p_{6}(x) &=& 1 - 72 x + 840 x^2 - 3584 x^3 + 6912 x^4 - 6144 x^5 + 2048 x^6.
\end{eqnarray}
Graph of the first four polynomials.
The above plots lead to the conclusion that all roots are within the interval $(0,1)$ and that $|p_{k}(x)| \leq 1$, if $0 \leq x \leq 1$.
Does anyone know a good way to actually verify/proof the above hypothesis for this kind of two-term recursion?


text:
Q: $p$-value when standard deviation is zero What test can be used to indicate a $p$-value when both sets of data in a comparison have standard deviation of 0? For example, Set 1 has values of 1, 1, 1 and Set 2 has values of 5, 5, 5.
Or is it OK to just say that since the standard deviation are 0 for each set and no numbers are the same in each set, that the $p$-value is <0.05?

A: *

*I think it may make sense to conduct a statistical test on this kind of data, but you haven't given much context to know what could be done.

*You definitely cannot just conclude that $p < 0.05$ just because there is no variance in the samples.  One problem is that to reach a p-value, you need to define a null hypothesis.  It's not clear from your question that you've defined a null hypothesis. (What kind of equivalence would be looking for?  Means, medians, stochastic equality?) A second problem is that you still need to take the sample size into account.  Imagine the edge case where you have one observation for each sample.  Can you jump to $p < 0.05$ in this case?

*One case you might get data like in your example would be if there are two candidates for a job, say, and you have three independent ratings for each, on a discrete 1 to 5 scale, like a Likert scale.  In this case, we can treat the responses as ordered categories and conduct a Cochran-Armitage test. The following does this in R, using functions from a couple of different packages.
Another option may be certain permutation tests.
if(!require(coin)){install.packages("coin")}
if(!require(multiCA)){install.packages("multiCA")}

Input =(
"Rating      1 2 3 4 5
Set
Set1         3 0 0 0 0
Set2         0 0 0 0 3
")

Table = as.table(read.ftable(textConnection(Input)))

library(coin)

chisq_test(Table,
           scores = list("Rating" = c(-2, -1, 0, 1, 2)))

   ### Asymptotic Linear-by-Linear Association Test
   ###
   ### data:  Rating (ordered) by Set (Set1, Set2)
   ### Z = -2.4495, p-value = 0.01431
   ### alternative hypothesis: two.sided

library(multiCA)

multiCA.test(Table)

   ### Multinomial Cochran-Armitage trend test
   ###
   ### data:  Table
   ### W = 6, df.Set = 1, p-value = 0.01431
   ### alternative hypothesis: true slope for outcomes 1:nrow(x) is not equal to 0

A: The short answer is that you cannot do a statistical test on this type of data. The reason is because there is no way to measure chance variation.
I don't remember where I heard this analogy, but this may be a case where you need to ask yourself if a statistical inference is necessary. The analogy is ¿What is the $P$-value to assess that chickens have fewer legs than cows? Of course, barring any anomalies, your data sets will be {2,2,2,...,2} and {4,4,4,...4} (not even sure a sample size for either needs to be provided).
Hope this helps.


text:
Q: dll auto image-base is there an equivalent option line --enable-auto-image-base (gcc/cygwin) in vc++ to automatically set a default image-base address of a DLL?
or does someone know the common practise to calculate unique base address and specify it with /BASE?
I'm compiling many simple DLLs from c source files inside an batch,
and all DLLs have the same base address of 0x1000...

A: You can use "editbin /rebase" or the rebase command to rebase a list of DLLs.


text:
Q: C++ Infinite looping I have a problem that my program just infinite loops.
After writing in console 'Ne' or 'Ja'
// Translating in English Ne would be No and Ja would be Yes.
// The thing is that I want exit program after writing Ne. And return again to start of program if I write Ja.
// I know my code is crap, but I'm here for help.
Anyways there is a code:
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;

int main()
{

    {
        while (true)
        {
        system("cls");
        cout << "Noteikt naturalo skaitlu summu intervala no A [1] lidz B   [N].\n\n";
        Sleep(850);
        cout << "Ludzu ievadiet naturalo skaitli: \n\n";
        int Naturalais, Summa = 0;
        cout << "--> "; cin >> Naturalais; cout << "\n";

        for (int i = 1; i <= Naturalais; ++i)
        {
            Summa += i;
        }
        Sleep(250);
        cout << "Summa = " << Summa; cout << "\n\n";

        char Atbilde;

        cout << "Atkartot Ievadi? (Ja = Ievadit naturalo skaitli velrezi / Ne = Ne uz Aizvert Programmu.\n\n";
        cout << "--> "; cin >> Atbilde; cout << "\n";

        if (Atbilde == 'Ne' || Atbilde == 'ne')
            return 0;
        if(Atbilde == 'Ja' || Atbilde == 'JA')
            break;
        }
    }
}

A: First off: Atbilde == 'Ne' Atbilde is a char. 'Ne' is 2 chars. I'm surprised this compiles. But I doubt it is ever going to match.
Then: No matter what your answer, you always exit the loop - either via return or break. Obviously you only want to exit the loop in one of the 2 conditions.

A: add header file cstring instead of string
Declare Atbilde as string
and apply
if (Atbilde.compare(0,2,"Ne") == 0 || Atbilde.compare(0,2,"ne") == 0)
        continue;
    if(Atbilde.compare(0,2,"Ja") == 0 || Atbilde.compare(0,2,"JA") == 0)
        break;


text:
Q: What are good/practical strategies for performing disk IO in a packet recorder application receiving several Gbit/s of traffic? Consider the following scenario:

A traffic generator generates 20 Gbit/s of network traffic and sends
it to a traffic recorder utilizing two 10 Gbit links. Inside the traffic
recorder all packets should be written to a single file.
That's what I'm trying to do from a higher level perspective. Now have a look
at the internal structure of the packet recorder:

Both NICs use Intel DPDK (http://dpdk.org/) for dealing with incoming packets.
Therefore all incoming traffic is stored in mbuf structs of a preallocated
pool of mbuf structs which lives in upserspace. So far everything's working
fine. All packets reach the application. It's even possible to memcpy each
packet to some bigger buffers, if there's a need to aggregate the data.
The difficulties I'm having are with writing the data to the file. I tried to
indicate that with the red flash between the application and the file.
None of the approaches I took so far has been working. Some of those are:

*

*Memcpy'ing packets into a bigger (preallocated) buffer and write to the file when the buffer is full.

*Same as 1. but with seperate threads for buffering and writing using multiple buffers.

*Similar to 2. but using a Threadpool

*Asynchronous writing with Linux AIO

*Memory mapping the file

During execution of the apps I used iostat for monitoring disk utilization. Most of the time disk utilization wasn't very high or the disk wasn't writing at all.
My thoughts are that it should continuously write data to disk as fast as
possible. With packets coming in at a speed of 20 Gbit/s the disk needs to
write 2.5 GByte/s (theoretical).
One important thing to note is that the disk needs to be fast enough to even
handle that amount of data. I measured the IO performance using fio
(https://github.com/axboe/fio) and it should be no problem, if done right, to achieve enough speed. Doing it right is the problem though.
What are good strategies/solutions for maximizing disk IO in such a scenario?
How can disk utilization be increased?
Any source (literature, blog, ...) which is related to this topic would be
very welcome as well.
Thank you.
Edit 1:
This is some example code for approach #1. I stripped the code down a little bit, but there really isn't going on much more. I tried running it on a different number of threads, with different buffer sizes, fwrite instead of
write etc.
 1 static int32_t store_data(struct storage_config *config)
 2 {
 3   sturct pkt *pkts[MAX_RECV];
 4   char *buf = malloc(BUF_SIZE);
 5   uint32_t bytes_total = 0;
 6
 7   while (config->running) {
 8      uint32_t nb_recv = receive_pkts(pkts);
 9      for (uint32_t i = 0; i < nb_recv; ++i) {
10         if (bytes_total + pkts[i]->len > BUF_SIZE) {
11            write(config->fd, buf, bytes_total);
12            bytes_total = 0;
13         }
14         memcpy(buf + bytes_total, pkts[i]->data, pkts[i]->len);
15         bytes_total += pkts[i]->len;
16      }
17   }
18   return 0;
19 }

The other approaches write in a similar fashion. The thread pool variation for example uses multiple buffers instead of one and passes that buffer to another thread. So the call to write in line 11 is extracted into it's own function, a thread would be tasked with IO instead on that line and the store_data() function would use one of the additional buffers.
Edit 2: In reference to Andriy Berestovskyy's answer I incorporated his
suggestion and used writev. The application now looks like this:

On each of the two rx cores, which are DPDK-lcores, runs the following code:
while (quit_signal == false) {
    nb_rx = rte_eth_rx_burst(conf->port, 0, pkts, RX_RING_BURST_SIZE);
    if (nb_rx == 0) { continue; }

    for (i = nb_enq; i < nb_rx; ++i) {
        len = rte_pktmbuf_pkt_len(pkts[i]);
        nb_bytes_total += len;
        iov[iov_index].iov_len = len;
        iov[iov_index].iov_base = rte_pktmbuf_mtod(pkts[i], char *);
        rte_pktmbuf_free(pkts[i]);
        ++iov_index;
        if (iov_index >= IOV_MAX) {
            if (writev(conf->fd, iov, IOV_MAX) != nb_bytes_total) {
                printf("Couldn't write all data\n");
            }
            iov_index = 0;
            nb_bytes_total = 0;
        }
    }
}

(RX_RING_BURST_SIZE is 32 because by default thats the maximum value DPDK enforces and I don't know how to change it. I don't know if that would make a difference though)
When both NICs receive about 10 Gbit/s (1.25 GByte/s) of traffic about half the data is lost, when packet size is 1024 byte. If packet size is 64 byte performance is even worse and about 80% of the data is lost. Which makes kind of sense, because smaller packets means more syscalls and the rx ring gets filled faster. What doesn't make sense is, that the drives don't write at full speed most of the time, according to iostat.

A: The question is too broad, but overall:

*

*Avoid file system, i.e. use raw partitions/devices.

*Have a look at SPDK. It is like DPDK, but for the storage (NVMe):
http://www.spdk.io/
EDIT 1:
In the code snippet you have provided, you should use single writev() call instead of loop + memcpy + write(). Also it is not clear from the snippet what is the actual burst size. It is better to consolidate few small bursts and write them at a single syscall.
EDIT 2:

*

*There is a bug in the code: rte_pktmbuf_free() before the actual write.

*MAX_IOV is 1024 on my platform, so it is better to consolidate few bursts up to IOV_MAX before call the write.

*To avoid syscalls on the polling core, use another lcore to do the write. Use a single producer single consumer ring buffer between the cores.

*Since you already familiar with fio and its performance is ok for you, use the same approach as fio does, i.e. same IO engine, type etc.

*Create a test app which writes the same buffers in a loop, i.e. eliminate the RX part of your code and measure just the writing performance.

A: *

*Don't memcpy() - build IOV from pkt mbuf data and defer pkt mbuf free after it is written to disk.

*Don't use read()/write() in DPDK polling core. You can use aio or better (but harder to code but all packets mught be queued for write with only one syscall) IO_LISTIO. All the data (IO vectors or aiocb_lis) can be embedded in pktmbuf itself using priv_size argument of rte_pktmbuf_pool_create() so no additional allocation is needed.

Use SPDK as last resort. It is great library but also very demanding.


text:
Q: Ubuntu Stuck on Loading Screen I prepared a Bootable USB drive (64GB) to install Ubuntu, but then I accidentally formatted my hard disk (with windows 10 on it) so I wanted to try to restore that, but after few commands in the terminal I got error "No more space left on device" or something like "No more space on disk" and I dont had another USB to temporally install Ubuntu to free up space on because I wanted to restore the hard drive, but as I came back to the laptop, The other day, The Ubuntu loading screen got stuck at loading, and is loading forever, not matter if I started Ubuntu as live or the setup installer. Does the "No more space on disk is somehow connected to that problem, and does someone knows how to fix that problem of Ubuntu stuck at loading?
Few Erorrs that popped out in startup:
Start Up Errors: Couldn't get size: 0x800000000000000e
MODSIGN: Couldn't get UEFI db list Couldn't get size: 0x800000000000000e nouveau 0000:01:00.0:
DRM: failed to create kernel channel, -22


text:
Q: How to embed a form view into Django's function-based detail view It should be a common situation, but I cannot find the right approach in the Django documentation or in numerous Django-related tutorials on the internet. So probably I just don't know what to look for, or there is no special approach. I am a hobby programmer and have just started with Django, so definitely lack a lot of knowledge but I am also looking for the best practices, not just workarounds.
I have a function-based detail view which displays a photo and comments. So urls.py contains:
app_name = 'photos'
urlpatterns = [url(r'^(?P<photo_id>\d+?)', views.single_photo_page, name="single-photo"),]

In views.py:
@login_required
def single_photo_page(request, photo_id: str):
    photo = get_photo_by_id(photo_id)
    if photo:
        return render(request, 'photos/single_photo.html', {'photo': photo})
    else:
        return HttpResponseNotFound('Photo %d not found' % photo_id)

single_photo.html:

{{ photo.id }}

{% for comment in photo.comment_set.all|dictsort:"creation_timestamp" %}

{{ comment.signature }}

{{ comment.body|linebreaksbr|urlize }}

{% endfor %}

To accept user comments, I wanted to use Django's form functionality, but couldn't find how to embed a form into an existing view. So I've done it by hand:
view.py:
@login_required
def single_photo_page(request, photo_id: str):
    photo = get_photo_by_id(photo_id)
    try:
        new_comment_body = request.POST['comment-body']
        if new_comment_body:
            comment = Comment.objects.create(
                author=request.user,
                body=new_comment_body,
                photo=photo
            )
            comment.save()
        else:
            messages.add_message(request, messages.ERROR, 'Empty comment')
    except KeyError:
        # no comment body in the request, so it's not a request from the form
        pass
    if photo:
        return render(request, 'photos/single_photo.html', {'photo': photo})
    else:
        return HttpResponseNotFound('Photo %d not found' % photo_id)

single_photo.html, after comment rendering:
<form action="{% url 'photos:single-photo' photo.id %}" method="post">
  {% csrf_token %}
  Add comment

  <textarea id="comment-body"></textarea>
  <input type="submit" value="Save" />
</form>

This approach works fine, but means that I do manually the stuff for which Django form functionality is designed. Am I missing something, or is the right way to do it?


text:
Q: How to group data by specific time window, where second time is next day I need to calculate sum of some events between 2015-01-01 and 2015-12-31 made every night between 21:30 and 04:30 next day?
How to made it by using Pandas in a most elegant but possible simple and efficient way?
Example results table should look similar to the following:
             count
2015-04-01      38   (events between 2015-03-31 21:30 and 2015-04-01 04:30)
2015-04-02      15   (events between 2015-04-01 21:30 and 2015-04-02 04:30)
2015-04-03      27   (events between 2015-04-02 21:30 and 2015-04-03 04:30)

Thanks for any help and suggestions.

A: You can use:
df = pd.DataFrame({'a':['2015-04-01 15:00','2015-04-01 23:00','2015-04-01 04:00','2015-04-02 03:00','2015-05-02 16:00','2015-04-03 02:00'],
                   'b':[2,4,3,1,7,10]})
df['a'] = pd.to_datetime(df.a)

print (df)
                    a   b
0 2015-04-01 15:00:00   2
1 2015-04-01 23:00:00   4
2 2015-04-01 04:00:00   3
3 2015-04-02 03:00:00   1
4 2015-05-02 16:00:00   7
5 2015-04-03 02:00:00  10

Create DatetimeIndex:
start = pd.to_datetime('2015-04-01')
d = pd.date_range(start, periods=3)
print (d)
DatetimeIndex(['2015-04-01', '2015-04-02', '2015-04-03'], dtype='datetime64[ns]', freq='D')

Loop by DatetimeIndex, select all rows by boolean indexing and get len:
for dat in d:
    date_sum = len(df.ix[(df.a >= dat.date()+pd.offsets.DateOffset(hours=21, minutes=30)) &
                (df.a <= dat.date()+pd.offsets.DateOffset(days=1, hours=4, minutes=30)),'b'])
    print (date_sum)
    print (dat.date())
2
2015-04-01
1
2015-04-02
0

Create new Series by dict comprehension:
out = { dat.date(): len(df.ix[(df.a >= dat.date() + pd.offsets.DateOffset(hours=21, minutes=30)) & (df.a <= dat.date() + pd.offsets.DateOffset(days=1, hours=4, minutes=30)), 'b']) for dat in d}
s = pd.Series(out)
print (s)
2015-04-01    2
2015-04-02    1
2015-04-03    0
dtype: int64


text: Q: Monitor total internet used via router I have a TP-Link TD-W8951ND ADSL router and I have a limited broadband plan and my ISP does not have an option to monitor how much data I have used. I have some 5-6 devices that I use internet on and I want to monitor the total internet used by all my devices. Now I also use my router for streaming videos using a SMB share and I don't want that to get into the readings. Is there any way to measure the total amount of internet data used by my router?


text:
Q: Jetty, where are my five threads? I'm using spring+jetty. I'm configuring jetty:
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
    final JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory(port);
    factory.addServerCustomizers((Server server) -> {
        final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
        threadPool.setMinThreads(minThreads);
        threadPool.setMaxThreads(maxThreads);
        threadPool.setIdleTimeout(1000);
    });
    return factory;
}

It works, but strange.

*

*Set minThreads=1, maxThreads=5, and it doesn't processing connections.

*Set minThreads=1, maxThreads=6, and it processing only one connection

*Set minThreads=1, maxThreads=7, and it processing only two connections.
When I say processing, I mean, that it accepts connections, but do nothing. Doesn't reply, doesn't abort them. (I think they are in a queue)

So, where are my 5 threads?

A: You are not accounting for how each of your connectors allocates selectors and acceptors into the same threadpool.
You are also not taking into account the system/hardware effects into the thread pool (how many cpu cores do you have? yes it matters).
You are also defining a rediculously tiny threadpool.  Do you plan on only serving 1 http connection in a row? on 1 connector, using HTTP/1.0, with keep-alive, and no compression, with perfect network conditions that never fail or timeout?
Are you 100% sure that your user-agents (clients) will follow those rules?
Hint: the web page you are looking at right now, on stackoverflow, using a modern web browser, would have used from 9 to 18 active threads from the thread pool, grown the thread pool maximum to about 35, and would have been done with them all in 399ms.
Consider that any of the following future decisions would increase your thread pool pressures.

*

*Use jetty-proxy: AsyncProxyServlet, AsyncMiddlemanServlet

*Use WebSockets on the server side.

*Use WebSocket clients

*Use Http Clients

*Enable HTTP/2

Your settings should have thrown an IllegalStateException indicating your very low configuration.
java.lang.IllegalStateException: Insufficient threads: max=8 < needed(acceptors=1 + selectors=8 + request=1)
Since you said you are using Spring, consider following the open issue about this at
https://github.com/spring-projects/spring-boot/issues/8917
Here's some general (large hand waving) advice about tuning for maximum threads ...

*

*number of active, in flight, connections is your baseline, start with that as your maximum thread count and move up from there.

*HTTP/1.x uses less threads then HTTP/2

*small web resource sizes lean towards lower maximum threads

*large or long duration web resources lean towards larger maximum threads

*use of Servlet 3.1+ async I/O means less maximum threads (only uses threads if there is actual read and/or write needed)

*use of Servlet 3.0 (or older) blocking I/O means more maximum threads (must dedicate thread to each connection read/write)

*200 to 500 maximum threads for an average web site, with average load, and average web resource sizes, and average web resource timing, using HTTP/1.x

*for a heavy web site, using many features (proxy, websockets, httpclient, http/2) a maximum threads configuration of 3,000 to 5,000 is typical.

*for extreme web sites, dedicate as many CPU cores as you can, use Servlet 3.1 Async I/O exclusively, crank your threads maximum to 9,000 on up to 20,000 (depending on the load profile you have)

The smallest web site we know of using Jetty uses 19MB of memory, and has a configured 8 maximum threads in its thread pool. (its a weather station in a remote part of Norway)
The largest single machine web site we know of using Jetty uses 189GB of memory, on a 30 core machine, with 30,000 thread maximum configured, with 8 network interfaces, HTTP/1.x and HTTP/2 enabled on each, doing SSL + Gzip + WebSockets, with an average of 280,000 active connections at any one moment (peaks at just shy of 800,000 active connections at certain times of day, every day)


text:
Q: Why I am getting Can't resolve 'jQuery=jquery' on assets install? When running php bin/console oro:assets:build, I have 11 errors like this one :
ERROR in ../node_modules/jquery-form/src/jquery.form.js 2:20-44
  Module not found: Error: Can't resolve 'jQuery=jquery' in '/var/www/node_modules/jquery-form/src'
   @ ./bundles/oroui/js/widget/abstract-widget.js 26:2-24
   @ ./bundles/oroui/js/widget/block-widget.js
   @ ./build/admin/dynamic-imports.js 63:11-65:23
   @ ./bundles/oroui/js/app/services/load-modules.js 1:16-42
   @ ./bundles/oroui/js/polyfills.js 1:0-61 5:17-28
   @ ./bundles/oroui/js/app.js 8:29-59

Do you know what is the problem?
Thanks for helping.

A: It looks like you have installed the application from the master branch that is unstable and should never be used in production.
Instead, you can install the latest stable long term support version, which is 4.2 LTS. To do this, please follow the official documentation:
https://doc.oroinc.com/backend/setup/installation/#install-oro-application
The important step in your case is the first command, that downloads the latest stable version of the application:
# OroCRM Community Edition
composer create-project oro/crm-application my_project_name --repository=https://satis.oroinc.com

Alternatively, if you want to clone it using git, you can run
git clone -b 4.2.3 https://github.com/oroinc/crm-application my_project_name

It's important to clone tag 4.2.3 that is the latest stable.


text:
Q: Setting up JSP Server? OK so at work I've been working with Java to start migrating our legacy database and in-house systems to something more modern. Well today I was asked if there was a way to use HTML/CSS as a front end to the java programs I've made. So my coworker and I have set up Tomcat on our Ubuntu 12.04 server in hopes of using jsp. Now we don't know where to go. I've been using Netbeans for my java development and all the tutorials and articles I've found has been about installing the server on my PC and I think that can't be right. Are there any good, semi-current (as in not from 2003) tutorials or articles for setting this up? Both my coworker and I have experience with PHP and it's not this difficult to set up.

A: It doesn't matter where you install Tomcat, your computer or a separate server. Create your web application, drop the war into tomcat/webapps and you're ready to go (to http://yourservername.com:8080/nameofwar/). Of course if you've never actually created a web application, there's some additional complications.
If you're familiar with Netbeans, you probably want to create a Dynamic Web Project. Plenty of resources to be found with all this info I've given you.


text:
Q: Add a node in xml using java only if the node has an attribute I have the following xml code and I want to add a note in node manufacturedMaterial only if it has the attribute determinerCode.
<manufacturedProduct classCode="MANU">
   <manufacturedMaterial classCode="MMAT" determinerCode="KIND">

      </epsos:code>
   </manufacturedMaterial>
   <manufacturedMaterial classCode="MMAT">

      </epsos:code>
   </manufacturedMaterial>
   </manufacturedProduct>

Currently, my code is the following, but add a new child in both manufacturedMaterial nodes. Is there a way to check whether it has the attribute determinerCode or not?
NodeList nodes = dom.getElementsByTagName("manufacturedMaterial");

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        NodeList childNodes = node.getChildNodes();
        Element formCodeEl = dom.createElement("epsos:formCode");
        formCodeEl.setAttribute("code", myCode.get(i));
        node.appendChild(formCodeEl);
    }

A: Can you check the list of attributes in the node?
if(node.getAttributes().getNamedItem("determinerCode") != null)
{
    // Add your node here...
}


text:
Q: Преобразование строки в UTF-8 Считываю почту из ящика с помощью гема "mail". Возникает затык при считывании тела письма:
mail.body.decoded

Падает с ошибкой:
Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ASCII-8BIT

Добавляю:
mail.body.decoded.force_encoding("UTF-8")

Получаю:
ArgumentError: invalid byte sequence in UTF-8

Можно ли каким-то образом вырезать с этой строки ни читаемые символы и/или как то преобразовать ее в UTF-8?
Таким образом работает, но весь текст заменяется вопросами (?):
 mail.body.decoded.encode("UTF-16be", :invalid => :replace, :replace => "?").encode('UTF-8')

Хотелось бы удалить только не читаемые символы.
UPDATE
Кодировка письма при этом UTF-8:
{"charset"=>"utf-8", "format"=>"fixed"}
{"charset"=>"utf-8"}

UPDATE2
mail.body.decoded.bytes:
228
207
194
210
217
202
32
196
197
206
216
46
13
10
13
10
13
10
243
208
193
211
201
194
207
46
32
238
197
212
44
32
206
197
32
203
210
201
212
201
222
206
207
46
32
235
193
203
32
212
207
204
216
203
207
32
196
207
208
201
219
213
32
207
212
208
210
193
215
203
213
32
45
32
211
207
207
194
221
213
46
13
10
13
10
13
10
13
10
13
10


text:
Q: How to add insert query in spring mvc + hibernate project My hibernate configuration class include following code
@Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

My package structures like this enter code here

My daoImpl class like this.
@Repository("passArrayDao")
public class PassArrayDaoImpl extends AbstractDao<Integer, Arr> implements PassArrayDao {

    @Override
    public void passarray(Arr arr) {
  }
}

normally we user hibernate for insert update delete data no.
@Override
    public Book findBookById(int id) {
        return bookDao.findBookById(id);
    }
    @Override
    public List<Book> getAllBooks() {
        return bookDao.getAllBooks();
    }
    @Override
    public List<Book> findBooksByTitle(String title) {
        return bookDao.findBooksByTitle(title);
    }
    @Override
    public void deleteBookById(int id) {
        bookDao.deleteBookById(id);
    }
    @Override
    public void updateBook(Book book) {
        bookDao.updateBook(book);
    }

bus now i want write insert query into daoImpl class. How I create it.


text:
Q: Possible reading of a visually obscured word used in Indian newspaper from 1876 I am going through old English speaking newspapers and found the following from a newspaper called "THE PIONEER" that was published in Allahabad, India on August the 11th, 1876:

From what I can tell it reads:

We have just learnt that a [?] took place in the Central Jail, Lahore, on the 6th instant, afternoon : one prisoner has been severely injured.

I have no idea what word [?] could be, any idea what it could be?

A: Thought I would tidy up this question with a self answer thanks to the comments to my question.
Thanks for @KillingTime for the suggestion of Fracas which was upvoted multiple times and I am happy to accept as the answer. It makes sense in the context of the sentence and the end of the word matches with the more visible characters.
Also thanks to @Weather-Vane for pointing out the reason why the word was italicised was because it was a loan word. This also fit with the suggested word since its etymology appears to be Italian and may not be well known in India.


text:
Q: Run ruby script with tracing output like set -x in bash Does ruby have some way to execute a ruby script in tracing mode?
For example: If we execute a bash script with set -x it shows input and output of the command being executed. Is there a way to accomplish this in ruby?

A: Built-In Debugger
Step through your code with the built-in debugger. Invoke your script with:
ruby -rdebug /path/to/script

and step through it with s or n. See the DEBUGGER_ class for details.

A: If you want to run arbitrary scripts, then you can use irb.
$ irb
2.3.0 :001 > tmp = 'test'
 => "test"
2.3.0 :002 > class Tmp
2.3.0 :003?>   end
 => nil
2.3.0 :004 > Tmp
 => Tmp

Every time you run a command, you get the expression's result.

A: Since set -x is by no means "debugging," here goes the implementation of the same functionality in pure ruby:
ruby -e '
  code = File.readlines("/path/to/file.rb")
  eval code.map { |c| %Q|puts "+ #{c.strip}"| }.zip(code).join($/)
'


text:
Q: In ROBOT Framework, Using user defined Java Library instead of it's own :FOR LOOP Im having a situation on how to bring the user defined java library keywords rather than using ROBOT framework's own for loop. i.e. im writing a common code through which i store a list of elements and clicking a specific element which contains a specific text.
As a first step I'm trying to just display the text of elements in the list. It worked using :FOR LOOP of RF. Its shown below
@{customers}  get webelements  ${customer_list}
:FOR  ${items}    IN    @{customers}
\    ${customer_names}=    Get Text    ${items}
\    click element  ${items}
\    sleep  2s
\    Log    ${items}

Now i need to replace this FOR by the below keyword called "Store Names",
@{customers}  get webelements  ${customer_list}
${items}  Store Names  @{customers}
get text  ${items}
Log  ${items}

OUTPUT: 20170302 09:35:26.404 : FAIL : ValueError: Element locator '{items}' did not match any elements.

Below is the JAVA code for your reference, the below variable 'text' has no link with variable 'iterator'. I don't know how to bring this. I badly need of someone's help since i went through several blogs of conversation but none having situation like this.
public class StoreElements {
public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL";

public void storeNames(List<String> text){
     // Print the name from the list....
List<String> list = new ArrayList<String>();

//add elements to list
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
    @SuppressWarnings("unused")
    Object eleNames = iterator.next();

  }
 }
}

I have corrected the code and but when executed, i got the below error. Please help me.
Corrected code:
public class StoreElements<WebElement> {
public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL";
public void storeNamesofElements(WebElement text){
     // Print the name from the list....
List<WebElement> list = new ArrayList<WebElement>();
//add elements to list
Iterator<WebElement> iterator = list.iterator();
while(iterator.hasNext()) {
    text=iterator.next();
}}}

Error:
UnboundLocalError: local variable 'elements' referenced before assignment


text:
Q: how do I stop a function to iterate through all items in a list I am writing a simple word guessing game in python. Instead of using a list, I have all the words for the game in a .txt file called as the parameter of a function. The list itself is fine.
The game requires the user to enter a letter. Once the letter is entered, if it matched one of the words that is randomly selected by the random function, it gives points accordingly.
The problem is that when the function runs, the entered letter by the user iterates through all the words in the list. How do I fix this issue?
def guess_game(data):

   word = random.choice(data)

   print("alright, guess the first letter:")
   ans = input("Enter a letter to guess: ")
   print(ans)

   counter = 0
   tries = 15 #how many tries a user is allowed to make

   for match in word:
      if ans in match:
         counter += 10
         tries -= 1

         print("That's right, 10 points added")
         print(f"You have {tries} tries left. ")

      elif ans not in match:
         counter -= 10
         tries -= 1

         print("That's wrong, 10 points deducted")
         print(f"You have {tries} tries left. ")

A: few ideas:

*

*make a loop over your "tries" - the player can play until that is 0

*the player has to provide the letter inside this loop

*check for the letter provided by the player using

if ans in word

Here is my suggestion:
import random
print('Hi, welcome to the guessing game, wanna play?')
answer = input('Enter yes or no: ')

#just added a list to test
data = ['hello', 'coffee', 'tea']

word = random.choice(data)

if answer == "yes".lower():
    print("OK, let's play")
    print("alright, guess the first letter:")

    counter = 0
    tries = 15  # how many tries a user is allowed to make

    while tries > 0:
        ans = input("Enter a letter to guess: ")
        print(ans)
        if ans in word:
            counter += 10
            tries -= 1

            print("That's right, 10 points added")
            print(f"You have {tries} tries left. ")

        elif ans not in word:
            counter -= 10
            tries -= 1

            print("That's wrong, 10 points deducted")
            print(f"You have {tries} tries left. ")

elif answer == "no".lower():
    print("OK, have a good day")

else:
    print('Please enter yes or no')

You could also make a list of letter that were already guessed so you can give the player feedback as soon as they found all the needed letters.

A: Not sure if I understand this completely, but if word is just a word like "apple" or "cat", then your function shouldn't be iterating through your entire list (your list being data). This function iterates through each letter of the randomized word (like "apple") and checks if the inputted letter is equal to any of the letters in that word.

A: The 'in' keyword itself checks only the first occurrence of a variable in a collection.
However if you want to be more specific, assign your entered word to a variable and then use break keyword after it matches under the if statement while iterating through the list.


text:
Q: Matching the result from an array All,
Been trying to fix this issue for some time without any progress... Any feedback is more than welcome.
We are using simple auth based on users caller id and YoB - if he has unique YoB, he can access the service, if there's another user under that caller id with the same YoB: he gets a message that additional info is required.
The goal of a function is to return a record of a matching user - at the moment, it returns always the last record.
PHP Code:
// $response -> XML record with firstName, lastName and dob (dd/mm/yyyy)
// $yob -> YoB user has entered for authentication

function parseResponseYOB($response, $yob)
{
    $duplicates = 0; // If there are users with same YoB, display message that additional info is required

    if(empty($response->CallerMembers->CallerMemberDetails->dob))
    {
        $iterateArr = $response->CallerMembers->CallerMemberDetails;
    }else{
        $iterateArr[] = $response->CallerMembers->CallerMemberDetails;
    }

    foreach($iterateArr as $result)
    {
        $parseResult['firstName'] = $result->firstName;
        $parseResult['lastName'] = $result->lastName;
        $parseResult['yob'] = substr($result->dob, -4);

        if($parseResult['yob'] == $yob)
        {
            $duplicates++;
        }else{
            continue;
        }
     }
// Check for duplicate YoBs

    if($duplicates > 1)
    {
        return "Multiple members with the same YOB";
    }elseif($duplicates < 1){
        return "No members with the specified YOB found";
    }

    return $parseResult; // No duplicates, return the record of the matching user
    // PROBLEM: Always the last record is returned... not the one with matching YOB?
    }
}

A: That would be because that's exactly what you told it to do. You're currently writing every result into $parseResult - and overwriting the last result in the process - before you even check if it's the right one. You're also making the return call (as well as the checks) from within the foreach loop, which would actually terminate the loop after the first iteration. What you want is probably more like this:
function something ($arg1, $arg2) {
$parseResult;
//...
foreach ($iterateArr as $result) {
    if (substr($result->dob, -4) == $yob) {
        $parseResult['firstName'] = $result->firstName;
        $parseResult['lastName'] = $result->lastName;
        $parseResult['yob'] = substr($result->dob, -4);
        $duplicates++;
    }
}
// Check for duplicate YoBs

if($duplicates > 1)
{
    return "Multiple members with the same YOB";
}elseif($duplicates < 1){
    return "No members with the specified YOB found";
}

return $parseResult; // No duplicates, return the record of the matching user
}

A: Your return statement is within the foreach block.  Basically, the foreach loop will run once and output parseResult as soon as $parseResult['yob'] == $yob.  I think you may have forgotten a closing brace before checking for duplicate yobs.  Hope this helps.


text:
Q: Getting IPN notification with Txn_Type="recurring_payment_profile_cancel" when User has not cancelled his profile on paypal Using ManageRecurringPaymentsProfileStatus API, I changed the user profile status to cancel. It worked Fine. But I am also getting IPN notification with Txn_Type="recurring_payment_profile_cancel". User has not cancelled his profile. Did changing the status created this notification?

A: Yes changing the status of the profile has generated that IPN . As long as the IPN is turn on on the PayPal account or if you had passed the IPN url while creating the recurring profile , PayPal will send you the IPN for any changes on the profiles regardless of how the changes were made ( cancelled by user or by API) .


text:
Q: How to manage memory error in python? This is  the code I have, to count the frequency
import collections
import codecs
import io
from collections import Counter
with io.open('Combine.txt', 'r', encoding='utf8') as infh:
    words =infh.read().split()
    with open('Counts2.txt', 'wb') as f:
        for word, count in Counter(words).most_common(100000000):
            f.write(u'{} {}\n'.format(word, count).encode('utf-8'))

When I try to  read a big file( 4 GB)  I am getting error
Traceback (most recent call last):
  File "counter.py", line 7, in <module>
    words =infh.read().split()
  File "/usr/lib/python2.7/codecs.py", line 296, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError

I am using Ubuntu 12.4,  8 GB RAM  Intel Core i7
How to fix this error ?
/
usr/lib/python2.7/codecs.py", line 296, in decode
        (result, consumed) = self._buffer_decode(data, self.errors, final)
    MemoryError

A: This is the pythonic way to process a file line-by-line:
with open(...) as fh:
    for line in fh:
        pass

This will take care of opening and closing the file, including if an exception is raised in the inner block, plus it treats the file object fh as an iterable, which automatically uses buffered I/O and manages memory so you don't have to worry about large files.

A: How about readline instead of read()
http://docs.python.org/2/tutorial/inputoutput.html


text:
Q: function arguments loading to registers on x64 I have this little C code
void decode(int *xp,int *yp,int *zp)
{
      int a,b,c;
      a=*yp;
      b=*zp;
      c=*xp;
      *yp=c;
      *zp=a;
      *xp=b;
}

Then I compiled it to object file using gcc -c -O1 decode.c, and then dumped the object with objdump -M intel -d decode.o and the equivalent assembly code for this is
mov ecx,DWORD PTR [rsi]
mov eax,DWORD PTR [rdx]
mov r8d,DWORD PTR [rdi]
mov DWORD PTR [rsi],r8d
mov DWORD PTR [rdx],ecx
mov DWORD PTR [rdi],eax
ret

And I noticed that it doesnt use stack at all.But firstly values still need to be loaded to the registers. So my question is how do the arguments get loaded into the registers? does the compiler automatically loads the arguments to the registers behind the scenes? or something else happens? because there is no instructions that would load the arguments into the registers.

And a little off topic. When you increase optimization for compiling the relationship between original source code and machine code decreases,imposing dificulties to relate the machine code back to the source code. By default if you dont specify the optimization flag to the GCC it doesnt optimize the code. So I tried to compile without any optimizations to get expected results from the source, but what I got was 4-5 times bigger machine code that wasnt related to the source and understandable. But when I applied Level 1 optimization the code appeared understandable and related to the source. But why?

A: The arguments are loaded to registers in the caller. Example:
int a;
int b;

int f(int, int);

int g(void) {
  return f(a, b);
}

Look at the code generated for g:
$ gcc -O1 -S t.c
$ cat t.s
…
movl    b(%rip), %esi
movl    a(%rip), %edi
call    f

Second question:

So I tried to compile without any optimizations to get expected results from the source, but what I got was 4-5 times bigger machine code that wasnt related to the source and understandable.

This happens because unoptimized code is stupid. It is a straight translation of an intermediate representation in which each variable is stored in the stack even if it doesn't need to, each conversion is represented by an explicit operation even if one isn't needed, and so on. -O1 is the best level of optimization for reading the generated assembly. It is also possible to disable the frame pointer, which keeps the overhead to the minimum for simple functions.


text:
Q: Convert ArrayList to Array I'm having a little trouble converting an array list to an array in java.
I have a class called Table which contains an array list called applicants which takes Strings. When I use my toArray() function it doesn't seem to convert the array list into an array.
I know this because when i run the listArray() function it gives the error:
java.lang.NullPointerException.
Here is the code. Any help would be greatly appreciated.
public class Table {
    public ArrayList<String> applicants;
    public String appArray[];

    public Table() {
        applicants = new ArrayList<String>();
    }

    public void addApplicant(String app) {
        applicants.add(app);
    }

    public void toArray() {
        int x = applicants.size();
        String[] appArray = new String[x];
        appArray = applicants.toArray(appArray);
    }

    public void list() {
        for (int i = 0; i < applicants.size(); i++) {
            System.out.println(applicants.get(i));
        }
    }

    public void listArray() {
        for (int i = appArray.length; i > 0; i--) {
            System.out.println(appArray[i]);
        }
    }
}

A: This is because you are shadowing the appArray field in your method here:
 int x = applicants.size();
 String[] appArray = new String[x];
 appArray = applicants.toArray(appArray);

You create a new local variable called appArray when you should be using the appArray field you already have declared in your class.
You should do
public void toArray()
{
    appArray = applicants.toArray(new String[0]);
}

A: appArray = new String[applicants.size()];
int index = 0;
for(String app:applicants){
    appArray [index] = app;
    index++;
}

A: Because both your ArrayList and Array should only have strings you can do this.
appArray = applicants.toArray(new String[0]);

More information in the javadoc.


text:
Q: Difference between "hypnotic" and "hypnotizing" Is there a difference between hypnotic and hypnotizing? I believe they are synonyms but I think of hypnotic as being more metaphorical, and hypnotizing as being used, at least sometimes, as a clinical (or at least factual, non-metaphorical) term.

A: "Hypnotic" is a standard adjective, while "hypnotizing" is an adjective that has been created out of a verb, which is called a "participle adjective".
What that means, is that something that has the potential to induce hypnosis (literal or figurative) would be considered "hypnotic", whereas something that is "hypnotizing" is currently in the process of hypnotizing (in the verb sense, figuratively or literally) something.

His gaze was hypnotic.

The above phrase indicates a quality in a person's gaze, in that it has the potential to entrance someone.

His gaze was hypnotizing.

This phrase, on the other hand, indicates that the narrator (or the character in context) is actually caught in the trap, entranced by the hypnotic gaze — or rather, that the gaze is in the process of entrancing the narrator.
There is no real reason why one should be considered more metaphorical than the other, although it could be argued that "hypnotizing" is the more common term in the literal sense, simply because it is easier to factually identify an action, rather than a vague property. Whether or not that is the case, I do not know — in truth, I always thought that "hypnotic" was the more common word.


text:
Q: Comparing cells with similar/different values I have problem in comparing cells with different value but it is working if the value compared is the same. The problem that i am facing is to compare between cell A1:A100 in worksheet1 and cell B3:B1000 in worksheet 2. If the value in worksheet1 and worksheet2 is equal it will be pasted to cell A in worksheet3 which i am able to do. If the value is not equal it will be pasted to cell B in worksheet3 this is the problem that I am facing.This is my code.
Private Sub CommandButton1_Click()
Dim val1, val2 As String
For i = 1 To 100
val1 = Worksheets("Sheet1").Cells(i, 1)
 For j = 3 To 1000
 val2 = Worksheets("Sheet2").Cells(j, 2)

  If (val1 = val2) Then
   Worksheets("Sheet3").Cells(i, 1) = val2

  ElseIf (val1 <> val2) Then
   Worksheets("Sheet3").Cells(i, 2) = val2

  End If

  Next

Next
End Sub

A: You actually mean ....."for every value in Column B in Sheet 2, if this is found within the range A1:A100"...
Finally got you. See if this helps.
Sub test()
    Dim val As Variant
    Dim found As Integer, notFound As Integer

    found = 0
    notFound = 0

    For j = 3 To 1000
        val = Worksheets("Sheet2").Cells(j, 2).Value
        If Not IsError(Application.Match(val, Worksheets("Sheet1").Range("A1:A100"), 0)) Then
            'Comment this line if you don't want to paste the values that are the same
            'Worksheets("Sheet3").Range("A1").Offset(found) = val
            found = found + 1
        Else
            Worksheets("Sheet3").Range("B1").Offset(notFound) = val
            notFound = notFound + 1
        End If
    Next
End Sub


text:
Q: sqldeveloper wont open I've just installed Oracle 11g express on Windows 10, but I can't seem to launch SQLDeveloper.
i'm double clicking the sqldeveloper but nothing happens, no error , nothing.
sqldeveloper version: 20.2.0.175.1842-x64
I've also tried to run from sqldeveloper/bin/sqldeveloper.exe
and I've tried launching sqldeveloper.exe from the console, but I'm not getting error messages in the console.

how should i check what is the problem?
i have install java and java jdk8u271
this is my set:
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\snirbenyosef\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=SNIRBENYOSEC8E4
ComSpec=C:\Windows\system32\cmd.exe
DriverData=C:\Windows\System32\Drivers\DriverData
FPS_BROWSER_APP_PROFILE_STRING=Internet Explorer
FPS_BROWSER_USER_PROFILE_STRING=Default
HOMEDRIVE=C:
HOMEPATH=\Users\snirbenyosef
LOCALAPPDATA=C:\Users\snirbenyosef\AppData\Local
LOGONSERVER=\\SNIRBENYOSEC8E4
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\oraclexe\app\oracle\product\11.2.0\server\bin;;C:\Program Files (x86)\Parallels\Parallels Tools\Applications;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Users\snirbenyosef\AppData\Local\Microsoft\WindowsApps;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 142 Stepping 10, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=8e0a
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\SNIRBE~1\AppData\Local\Temp
TMP=C:\Users\SNIRBE~1\AppData\Local\Temp
USERDOMAIN=SNIRBENYOSEC8E4
USERDOMAIN_ROAMINGPROFILE=SNIRBENYOSEC8E4
USERNAME=snirbenyosef
USERPROFILE=C:\Users\snirbenyosef
windir=C:\Windows

A: just move the sql developer to desktop of windows and not the linked to mac. solved it.


text:
Q: SubsamplingScaleImageView initial zoom and position I am using Dave Morrissey's gorgeous library https://github.com/davemorrissey/subsampling-scale-image-view , especially SubsamplingScaleImageView and I want image inside this view initialised with scale 100% and centered. There is method setScaleAndCenter(float, PointF), first parameter is scale, I set it to 1f, the second is point describing center but I don't know which values it should have.
My image has 2000x3000 px, I was trying set x and y of center point to 1000 and 1500, also I was trying something like 0.5f, 50 (percents) but it doesn't work.
How to calculate values for setScaleAndCenter(float, PointF) in order to center image?


text:
Q: Bluedroid AV connection fails (BTAV_CONNECTION_STATE_DISCONNECTED state) I am using Bluedroid stack for developiong my bluetooth apllication.
I am using A2DP src profile to make connection between Mobile and my device.
I have issue in following scenario:
When i switch from A2DP SINK profile to A2DP Source profile, the first connection request from Mobile site is always failure.
And after first connection request its always success.
I found the reason for fail is:
AV connection state is changing from
BTAV_CONNECTION_STATE_CONNECTING
...
...
BTAV_CONNECTION_STATE_DISCONNECTED
I have checked the flow in Bluedrod Stack, and found that streamming open is failed and due to this i gets BTAV_CONNECTION_STATE_DISCONNECTED event to my app.
Any help would be appreciated.
For more information please comment.
The fail status is BTA_AV_FAIL_STREAM in bluedroid stack

A: I got the answer/solution of this problem.
Qualcomm engineer has provided a patch to solve the issue.
Whenever there were switch between A2DP sync to A2DP src profile the SDP records is not set properly due to that the first connection request is rejected.
When the rejection happens on first time it sets the value of A2DP SRC in SDP records properly and due to that further connection request is accepted.


text:
Q: How to use css shaders with google chrome canary I wish to use css shaders with Chrome Canary.
However I could not find #enable-css-shaders in chrome://flags in Version 37.0.2035.2 canary.
is css shaders removed from flags?
Thank you for your help.


text:
Q: Replace strings that contain random numbers from a file I am looking for code to replace effectively, a string which contains numbers. However, the numbers can be either or in-between 0.50 and 2.20 with increments of 2. So 0.50, 0.52, 0.62.... etc
To explain it better, my program is replacing lines in a config (text) file. Here is an example of how I used it for other parts of my program. Since this is linked to a trackbar control, it would mean searching for hundreds of different values with the single selected value, which of course, is very inefficient. I am just looking for a more efficient way of replacing values. Here is a previous example which inserts one of 3 possible values:
ReWriteFile = ReWriteFile
   .Replace("  clipmapScale:r=0.5", "  clipmapScale:r=1.5")
   .Replace("  clipmapScale:r=1", "  clipmapScale:r=1.5");

This control had only 3 possible values (0.5, 1.0, 1.5), but my other control has 85 possible values.
If there was a way to grab numbers from a string and replace them and write them back. I'm not so fluent in C# as I've just started to learn it (Uni student here).
Maybe catching it as a string with specified characters like [0-9,.,].

A: If you just want to replace every decimal number inside a string with a new number (no calculation on the found value) then it is a simple Regex expression and just one call to Replace
string newValue = "1.5";
// Matches any number followed by a dot and then another number
string pattern = @"\d+\.\d+";
string search = "..... clipmapScale:r=0.5 clipmapScale:r=1.0 .....";
var m = Regex.Replace(search, pattern, newValue);
Console.WriteLine(m);

Of course, if you want to restrict the matched parts to only the numbers after the clipmapScale text you can change to
string newValue = "clipmapScale:r=1.5";
string pattern = @"clipmapScale:r=\d+\.\d+";

A: You can use Regular Expression for that purpose. Imagine you want to replace all decimal numbers with # characters. You can use the following code snippets for that.
        string input = "this0.4is7.8some0.89input";
        Regex regex = new Regex(@"\d+\.\d+");
        var s =regex.Replace(input, "#");
        Console.WriteLine(s);


text:
Q: Threads and Array of pointers? I have a problem with code below, after threads finish working, the output of the array is a rabish data, while it's working correctly without threads, any one can help me and explain why !!!!!
#include<iostream>
#include <thread>

using namespace std;

class Case1{

public:
 int *pplAges[5];
 Case1(){
 *pplAges= new int[5];
 }

 void addToAges(int Age, int index){
 pplAges[index] = new int;
 *pplAges[index] = Age;
 cout<< *pplAges[index] <<endl;

 }

};

void f1(Case1 passedObj,int age,int index)
{

passedObj.addToAges(age,index);

}

void main(){

 Case1 C;

thread t1(f1,C,13,0);
t1.join();

thread t2(f1,C,14,2);
t2.join();

cout<<*C.pplAges[0]<<endl;
cout<<*C.pplAges[2]<<endl;
}

A: Threads copy their arguments, so your threads never change the C. If you want a reference explicitly, you have to wrap it with std::ref (or std::cref for constant references):
void f1(Case1& passedObj, int age, int index)
{

    passedObj.addToAges(age, index);

}

void main(){

    Case1 C;

    thread t1(f1, std::ref(C), 13, 0);
    t1.join();

    thread t2(f1, std::ref(C), 14, 2);
    t2.join();

    cout << *C.pplAges[0] << endl;
    cout << *C.pplAges[2] << endl;
}

A: try to change
void f1(Case1 passedObj,int age,int index)

to
void f1(Case1* passedObj,int age,int index)

and pass the thread &C


text:
Q: Проблема с SQL-запросом. CREATE TABLE course (
    course_id INT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    lecturer_id INT NOT NULL,
    start_date DATE NOT NULL,
    hours INT NOT NULL,
    status VARCHAR(10) NOT NULL,
    cost INT NOT NULL,
    CONSTRAINT FOREIGN KEY (lecturer_id) REFERENCES lecturer(lecturer_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE course_student (
    course_id INT NOT NULL,
    student_id INT NOT NULL,
    mark INT NULL,
    review VARCHAR(255) NULL,
    PRIMARY KEY(course_id, student_id),
    CONSTRAINT FOREIGN KEY (course_id) REFERENCES course(course_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    CONSTRAINT FOREIGN KEY (student_id) REFERENCES student(student_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

Здравствуйте всем! Выше представлены две таблицы. У меня возникла проблема: не могу написать SELECT-запрос, который помог бы мне, имея student_id, вывести все курсы co статусом 'enrollment', на которые студент с данным student_id не записан, т.е. нет записей в таблице course_student, связывающей student_id с искомыми курсами.
Спасибо огромное заранее!
A: select * from course c where status = 'enrollment' and not exists(select cs.course_id from course_student cs where cs.course_id = c.course_id and cs.student_id = ?);

или
select c.* from course c left join course_student cs on c.course_id = cs.course_id and cs.student_id = ? where c.status = 'enrollment' and cs.course_id is null;


text:
Q: Subsetting a list of data frames by condition Sorry I can't embed pictures yet
I have 21 data frames in a list (listb), all with the same headings of Timestamp, Rainfall
I would like to sort them by Rainfall (descending) and then subset the top 30 (to include the corresponding Timestamp) of each of the 21 data frames. Then put them back into a single dataframe with the name of the initial data frame as a heading?
Please find the list of data frames below, and a small cut from the b1 dataframe
Would I need to create a new dataframe for each of the new subsets then combine them into a list later?
Descending_b1 <- listb$b1[order(-Rainfall),]

b1_30 <- Descending_b1[1:30,1:2]

From that, I produce the following
b1_30 <- structure(list(Timestamp = c("25/1/2013", "24/1/2013", "2/2/2004",
                             "21/3/2010", "16/7/2016", "1/2/2010", "26/1/2007", "29/12/1998",
                             "24/2/2008", "5/2/2003", "6/2/2003", "11/11/2001", "3/12/2010",
                             "8/3/2020", "27/12/2010", "29/1/1998", "18/10/2017", "13/3/2007",
                             "5/4/2006", "10/6/2006", "19/11/2008", "20/2/2015", "26/3/2014",
                             "15/3/2017", "27/8/2011", "1/3/2013", "27/8/1998", "11/2/2012",
                             "11/2/2008", "26/1/2013"),
                        Rainfall = c(238L, 158L, 131L, 131L,129L, 122L, 112L, 109L, 101L, 94L,
                                     92L, 88L, 82L, 81L, 78L, 74L, 71L, 69L, 65L, 64L, 64L,
                                     64L, 63L, 63L, 62L, 61L, 60L, 60L, 58L,57L)),
                   row.names = c(5915L, 5914L, 2640L, 4874L, 7183L, 4826L, 3725L, 939L, 4118L, 2278L, 2279L, 1827L, 5131L, 8514L, 5155L,
                              605L, 7642L, 3771L, 3429L, 3495L, 4387L, 6671L, 6340L, 7425L,
                              5398L, 5950L, 815L, 5566L, 4105L, 5916L), class = "data.frame")
b1_30
#>       Timestamp Rainfall
#> 5915  25/1/2013      238
#> 5914  24/1/2013      158
#> 2640   2/2/2004      131
#> 4874  21/3/2010      131
#> 7183  16/7/2016      129
#> 4826   1/2/2010      122
#> 3725  26/1/2007      112
#> 939  29/12/1998      109
#> 4118  24/2/2008      101
#> 2278   5/2/2003       94
#> 2279   6/2/2003       92
#> 1827 11/11/2001       88
#> 5131  3/12/2010       82
#> 8514   8/3/2020       81
#> 5155 27/12/2010       78
#> 605   29/1/1998       74
#> 7642 18/10/2017       71
#> 3771  13/3/2007       69
#> 3429   5/4/2006       65
#> 3495  10/6/2006       64
#> 4387 19/11/2008       64
#> 6671  20/2/2015       64
#> 6340  26/3/2014       63
#> 7425  15/3/2017       63
#> 5398  27/8/2011       62
#> 5950   1/3/2013       61
#> 815   27/8/1998       60
#> 5566  11/2/2012       60
#> 4105  11/2/2008       58
#> 5916  26/1/2013       57

So yeah I hope to do that with the rest of the data frames within the list to create a new data frame whilst keeping the initial data frame name, and then combine them into a new list

A: Suppose you have a list like this
set.seed(2021)
listb <- list(b1 = data.frame(Timestamp = as.Date("2010-01-01") + days(sample(1:100, 10)),
              Rainfall = sample(200:300, 10)),
b2 = data.frame(Timestamp = as.Date("2010-01-01") + days(sample(1:100, 10)),
                Rainfall = sample(200:300, 10)),
b3 = data.frame(Timestamp = as.Date("2010-01-01") + days(sample(1:100, 10)),
                Rainfall = sample(200:300, 10)))

> listb
$b1
    Timestamp Rainfall
1  2010-01-08      275
2  2010-02-08      250
3  2010-02-16      259
4  2010-02-28      217
5  2010-01-13      298
6  2010-03-12      202
7  2010-03-06      245
8  2010-04-10      225
9  2010-03-11      235
10 2010-01-24      285

$b2
    Timestamp Rainfall
1  2010-02-01      242
2  2010-04-09      258
3  2010-01-20      269
4  2010-03-10      285
5  2010-03-28      298
6  2010-01-06      262
7  2010-03-15      278
8  2010-03-05      233
9  2010-02-08      221
10 2010-01-19      215

$b3
    Timestamp Rainfall
1  2010-03-21      216
2  2010-03-30      240
3  2010-01-18      230
4  2010-01-21      272
5  2010-03-10      292
6  2010-04-05      226
7  2010-03-14      210
8  2010-03-25      235
9  2010-03-09      237
10 2010-01-03      278

Now you need to do this only (Needless to say replace n argument in slice_max with your desired n=30)
purrr::map2_dfr(listb, names(listb), ~ .x %>%
          mutate(list_name = .y) %>%
           slice_max(Rainfall, n=5))

    Timestamp Rainfall list_name
1  2010-01-13      298        b1
2  2010-01-24      285        b1
3  2010-01-08      275        b1
4  2010-02-16      259        b1
5  2010-02-08      250        b1
6  2010-03-28      298        b2
7  2010-03-10      285        b2
8  2010-03-15      278        b2
9  2010-01-20      269        b2
10 2010-01-06      262        b2
11 2010-03-10      292        b3
12 2010-01-03      278        b3
13 2010-01-21      272        b3
14 2010-03-30      240        b3
15 2010-03-09      237        b3

If you want to return the output back into a similar list
purrr::map(listb,  ~ .x %>%
               slice_max(Rainfall, n=5))

$b1
   Timestamp Rainfall
1 2010-01-13      298
2 2010-01-24      285
3 2010-01-08      275
4 2010-02-16      259
5 2010-02-08      250

$b2
   Timestamp Rainfall
1 2010-03-28      298
2 2010-03-10      285
3 2010-03-15      278
4 2010-01-20      269
5 2010-01-06      262

$b3
   Timestamp Rainfall
1 2010-03-10      292
2 2010-01-03      278
3 2010-01-21      272
4 2010-03-30      240
5 2010-03-09      237


text:
Q: setting up react navigation for WEB failed to compile I want to use React Navigation 3.x in combination with react-native-web.
By going through the "getting started"-steps,
simply importing:
import { createStackNavigator, createAppContainer } from "react-navigation";

and updating the babel configurations, I end up receiving this error:

./node_modules/@react-navigation/native/node_modules/react-native-gesture-handler/Swipeable.js
  Module not found: Can't resolve 'react-native/Libraries/Animated/src/AnimatedEvent' in 'D:\react_native\App\app\node_modules@react-navigation\native\node_modules\react-native-gesture-handler'

In my research I found some topics on github which could have a relation to that error:
https://github.com/kmagiera/react-native-gesture-handler/pull/406
https://github.com/react-navigation/react-navigation/issues/5632
I already used this "fix" (from the github pull above) as a dependecy:
"react-native-gesture-handler": "jaulz/react-native-gesture-handler#fix/web-compatibility"

but again a similar error:

./node_modules/@react-navigation/native/node_modules/react-native-gesture-handler/DrawerLayout.js
  Module not found: Can't resolve
  'react-native/Libraries/Animated/src/AnimatedEvent' in
  'D:\react_native\App\app\node_modules@react-navigation\native\node_modules\react-native-gesture-handler'

How can I implement a working navigation on the web with react navigation?
maybe using other dependecy versions?
or should I use react router after all?

A: here are some instruction for setting up
react-navigation for web apps.
https://reactnavigation.org/docs/en/web-support.html
in short:
yarn add @react-navigation/core
yarn add @react-navigation/web
then
import { createSwitchNavigator } from "@react-navigation/core";
import { createBrowserApp, Link } from "@react-navigation/web";
finally replace createAppContainer wIth createBrowserApp


text:
Q: XML -> Dataset - temp-table - recid field issue A follow up from a question from March.
Summary (will post details below): 10.1c version (old) Reading in XML to Dataset with multiple temp-tables (multi table relations) but the "parentid" fields in the temp-table are not populated. Only have ? (null) so I can't properly join the parent / child relation on "parentid".
Main question: How do I get the parentid field to populate properly? Any help is greatly appreciated.
I will do my best to paste all relevant code below:
'''
define temp-table ga_export NO-UNDO
   FIELD parentid AS RECID
.

define temp-table ga_journal
   field parentid as recid
   field ga_journal_id as int
   field ga_journal_type_ind as character
   field ga_unapplied_cash_ind as logical
   field ga_named_user as character
   field ga_action as character
   field ga_amount as decimal
   field ga_amount_allowed as decimal
   field ga_amount_over as decimal
   field ga_currency as character
   field ga_operation as character
   field ga_custno as character
   field ga_invno as character
   field ga_batchnum as int
.

 define temp-table ga_receipt
   field parentid as recid
   field ga_receiptnum as int
   field ga_checknum as int
   field ga_amount as decimal
.

 define temp-table ga_posting
   field parentid as recid
   field ga_gl_code as character
   field ga_gl_name as character
   field ga_gl_category as character
   field ga_artarget_desc as character
   field ga_artarget_id as character
   field ga_fr_unit as character /* level="Division" */
   field ga_fr_unit2 as character /* level="Sales Area" */
.

define temp-table ga_deposit
   field parentid as recid
   field ga_deposit_id as int
   field ga_date as date
   field ga_amount as decimal
   field ga_currency as character
.

define temp-table ga_bank
   field parentid as recid
   field ga_name as character
   field ga_micr_routing as int
   field ga_micr_account as int
.

DEFINE DATASET dsGAExport FOR ga_export, ga_journal, ga_receipt, ga_posting, ga_deposit, ga_bank
   DATA-RELATION drexju FOR ga_export, ga_journal RELATION-FIELDS (parentid, parentid)
   DATA-RELATION drjure FOR ga_journal, ga_receipt RELATION-FIELDS (parentid, parentid)
   DATA-RELATION drjupoe FOR ga_journal, ga_posting RELATION-FIELDS (parentid, parentid)
   DATA-RELATION drjude FOR ga_journal, ga_deposit RELATION-FIELDS (parentid, parentid)
   DATA-RELATION drdeba FOR ga_deposit, ga_bank RELATION-FIELDS (parentid, parentid)
.

lRetOK = DATASET dsGAExport:READ-XML(cSourceType, outFileName, cReadMode, cSchemaLocation,
        lOverrideDefaultMapping, cFieldTypeMapping, cVerifySchemaMode).

'''
Then when I try to display the parentid (recid) from each table it is just null. XML data is in the table as I would expect, except without parentid (recid) I can't seem to be able to join / display the data in a relationship fashion.
Again, any help is appreciated.
XML EXAMPLE CODE BELOW:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ga_export>
    <ga_journal>
        <ga_journal_id>29</ga_journal_id>
        <ga_journal_type_ind>C</ga_journal_type_ind>
        <ga_unapplied_cash_ind>false</ga_unapplied_cash_ind>
        <ga_named_user>GET</ga_named_user>
        <ga_action>C</ga_action>
        <ga_amount>52071.83</ga_amount>
        <ga_amount_allowed>0.00</ga_amount_allowed>
        <ga_amount_over>0.00</ga_amount_over>
        <ga_currency>USD</ga_currency>
        <ga_operation>TR_POST</ga_operation>
        <ga_custno>1006</ga_custno>
        <ga_invno>12093</ga_invno>
        <ga_batchnum>1001</ga_batchnum>
        <ga_receipt>
            <ga_receiptnum>1001</ga_receiptnum>
            <ga_checknum>1001</ga_checknum>
            <ga_amount>52071.83</ga_amount>
        </ga_receipt>
        <ga_posting>
            <ga_gl_code>2000</ga_gl_code>
            <ga_gl_name>TAR</ga_gl_name>
            <ga_gl_category>TRADE_RECEIVABLE</ga_gl_category>
            <ga_artarget_desc>DEFAULT</ga_artarget_desc>
            <ga_artarget_id>DEFAULT</ga_artarget_id>
            <ga_fr_unit level="Division">DIV01</ga_fr_unit>
            <ga_fr_unit level="Sales Area">Template</ga_fr_unit>
        </ga_posting>
        <ga_deposit>
            <ga_deposit_id>6</ga_deposit_id>
            <ga_date>2017-04-26</ga_date>
            <ga_amount>57871.83</ga_amount>
            <ga_currency>USD</ga_currency>
            <ga_bank>
                <ga_name>Bobs Bank</ga_name>
                <ga_micr_routing>987654321</ga_micr_routing>
                <ga_micr_account>123456789</ga_micr_account>
            </ga_bank>
        </ga_deposit>
        <ga_exportTimestamp>20170426163505</ga_exportTimestamp>
    </ga_journal>
</ga_export>