text:
Q: Hibernate Search (Lucene) near-real-time indexmanager and Tomcat parallel deployments A bit of background first: I'm currently using Hibernate Search 4.2 in my Java web application and I deal with write heavy Lucene Indexes in which I store quite a bit of data. An indexing operation of single object stored in my biggest index takes around 1 second when using the directory-based indexmanager.
To improve performance, I switched the indexmanager to near-real-time and the performance improved leaps and bounds, but now I would like to implement zero downtime deployments using Tomcat Parallel Deployments (which allows me to have 2 different versions of the same application side-by-side in a single Tomcat) and I have found out that I can't use the near-real-time indexmanager anymore because it buffers the modifications in memory and avoids flushing to disk until the buffer ram is full or the application shuts down.
My question is: what alternative solutions do I have in this situation? I would like to keep the indexing process as synchronous as possible.
I have taken a look at the code of Hibernate Search and I have seen that the there are different commit policies and a class called IndexWriterHolder that allows me to commit and flush writes, but I'm not sure if or how those APIs are publicly exposed.
I've also seen that Lucene 4 implements concurrent flushing and I've discovered the max_thread_states flag in Hibernate Search 5 that allows me to specify the number of concurrent writer threads per IndexWriter, but I've never used it before and I'm not sure if concurrent flushing would help in my situation.
Any help is greatly appreciated. Thank you.

A: Great question. The short answer is that this is currently not possible.
The IndexWriterHolder is indeed not public API and would be tricky to expose as it handles a queue in a background thread: invoking it directly rather than by scheduling events into the queue would be racy.
The concurrent flushing capabilities of Lucene are being used automatically, when safe; for example during MassIndexing; I don't expect the max_thread_states property would help you much, but it's worth trying the other tuning options.
I'm one of the Hibernate Search developers and wasn't aware of Tomcat's Parallel Deployments: it sounds like an interesting feature which we could explore supporting. Please open a feature request on JIRA or start a conversation on the forums to better help us understand how this could work.


text:
Q: Plural of "Animus/Anima" What is the plural of the words "animus" and "anima"? In any context (literary, Jung psychology, apothecary etc.). Is there English v. Latin differences? Interwebs are no help: versions differ from "animuses", to "animi", to uncountable. "Animuses" is correct as native English plural, if I understand correctly (then "animas" for feminine?). If we take Latin route, would it be "animi" for masculine, and "animae" for feminine?

A: According to the OED, the Jungian terms anima and animus have no plural form in English.

animus /ˈænɪməs/.
No pl.
Etymology: a. L. animus (1) soul, (2) mind, (3) mental impulse, disposition, passion.

*

*Actuating feeling, disposition in a particular direction, animating spirit or temper, usually of a hostile character; hence, animosity.

*Psychol. Jung's term for the masculine component of a female personality. Cf. anima.

anima /ˈænɪmə/.
Psychol.
Etymology: L., 'mind, soul'.
Jung's term for the inner part of the personality or character, as opposed to the persona or outer part; also, the feminine component of a male personality. Cf. animus 2.

They are in essence mass nouns, not count nouns.
In English, that is.
In Latin, where they do not mean what they do per Jung, anima and animus are unremarkable nominative singulars of the first and second declensions, respectively. They therefore form their nominative plural and genitive singular as anima > animae and animus > animi, and genitive plurals as anima > animarum and animus > animorum.   So soul, souls/soul's,  and souls'.

*

*Nullum autem est, nisi quod animus ex se sibi invenit.   ― Seneca the Younger  [~ "There can be no good except for what the soul discovers for itself within itself."]

*Magnificat anima mea dominum.   ― J.S. Bach ☺   [traditionally translated as "My soul doth magnify the Lord."]

A: Merriam-Webster gives plurals when they form irregularly, as in louse, child, or sheep. M-W doesn't comment at all when a noun has no plural, like mathematics or information.  In the case of animus/anima, M-W doesn't list a plural, which to my mind indicates the M-W considers it either (a) without plural; or (b) with a plural formed along standard lines.
In English, often a Latin ending is used for one meaning, and the anglicized ending is used in another related, but different way. Index is a good example. In technical writing, index can be either a measurement or a table of references at the back of a book. The former is pluralized indices and the latter is pluralized indexes (anglicized). This precise usage is common, but not entirely standardized, I should think.
All this is to say that if you find yourself in a situation that requires a plural for animus or anima, you might use something of the same approach: -es/-s for general, and -i/-ae for technical (like Jung's use), or vice versa.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting same unix time stamp for two different times in javascript I had two ical format timestamps and I want to convert them to normal time first and then to unix time.
Here this is the function I've been using to convert normal time to unix timestamp:
var normal_to_unix = function (date_string) {
    var date = new Date(date_string);
    return date.getTime() / 1000;
}

This function is fine since date is already in UTC and I need not do any conversions.
Now this is the function I've been using to convert ical time to unix time. The ical time in my case is like "20180603T150000Z".
var ics_to_unix = function (ics_string) {
    var year = ics_string.slice(0, 4);
    var month = ics_string.slice(4, 6);
    var date = ics_string.slice(6, 8);
    var hours = ics_string.slice(9, 11);
    var minutes = ics_string.slice(11, 13);
    var seconds = ics_string.slice(13, 15);
    var milliseconds = 0;
    console.log(year, month, date, hours, minutes, seconds, milliseconds); // This is example output 2018 06 03 15 00 00 0
    return normal_to_unix((new Date(year, month, date, hours, minutes, seconds, milliseconds)).toDateString())
}

Now the problem is I'm getting the same unix time for "20180603T150000Z" and "20180603T160000Z" which are supposed to give different timestamps and it is 1530576000 for both of them.
Is there anything that I'm missing ? Thanks in advance.
Please have a look at this for live example

A: Several points here:
The toDateString() method returns the date portion of a Date object in human readable form in American English. For your example it is `Tue Jul 03 2018', perhaps that is not what you want.
new Date creates date in your local timezone, which could play well if you use it together with toString(), which will also return the string for date in your local timezone. But it will be subject to daylight saving changes, so I'd avoid using that method.
Another thing I'd like to avoid converting back and forth between strings and dates, since it does a lot of unnecessary computations.
I'd suggest to use the following:
var ics_to_unix = function (ics_string) {
  var year = parseInt(ics_string.slice(0, 4));
  var month = parseInt(ics_string.slice(4, 6)) - 1; // Jan is 0
  var date = parseInt(ics_string.slice(6, 8));
  var hours = parseInt(ics_string.slice(9, 11));
  var minutes = parseInt(ics_string.slice(11, 13));
  var seconds = parseInt(ics_string.slice(13, 15));

  return Date.UTC(year, month, date, hours, minutes, seconds) / 1000;
}

I have added explicit conversion of strings to numbers, adjusted the month to match what is used in javascript and also removed the extra call.


text:
Q: How to center a single colum in semantic-ui grid I want to center a login form, in a login page. the form be centered on desktop and full width on mobile. I tried this, but it does not work. I have this instead.

Your username and password didn't match. Please try again.

        <form method="post" class="ui large form error">

                {% for field in form %}

                        {{ field }}

                {% endfor %}
                <button type="submit" value="Send" class="ui primary button">Log in</button>

        </form>

A: Try setting your column with these classes: "sixteen wide tablet twelve wide computer column"... tablet applies to mobile as well.

Your username and password didn't match. Please try again.

            <form method="post" class="ui large form error">

                    {% for field in form %}

                            {{ field }}

                    {% endfor %}
                    <button type="submit" value="Send" class="ui primary button">Log in</button>

            </form>

```


text:
Q: HTML-теги работают неправильно Значение переменной не записывается в value , но в поле для заполнения появляется ошибка:

Notice:  Undefined variable: name in D:\xampp\htdocs\trening\index.php on line 20

Вот так написано, не могу понять что такое:
<?php
  $db = new PDO('mysql:host=localhost; dbname=mdb','root','');
  $db->exec("SET NAMES UTF8");
  if(count($_POST)>0){
    $name = trim($_POST['name']);
    $text = trim($_POST['text']);
      if($name!=''&&$text!=''){
        $query=$db->prepare("INSERT INTO coments SET name='$name' text='$text'");
        $query->execute();
        header("Location: index.php");
        exit();
      }
  }
  $query=$db->prepare("SELECT * FROM coments ORDER BY dt DESC");
  $query->execute();
  $arr=$query->fetchAll();
?>
<form method="post";>
  Имя

  <input type="text" name="name" value="<?php echo $name;?>">

  Коментарий

  <textarea name="text"></textarea>

  <input type="submit" value="отправить">
</form>

A: Условие if(count($_POST)>0) не выполняется, поэтому переменная считается не объявленной.
Можно сделать значение по умолчанию в else:
 if(count($_POST)>0){
$name = trim($_POST['name']);
$text = trim($_POST['text']);
  if($name!=''&&$text!=''){
    $query=$db->prepare("INSERT INTO coments SET name='$name' text='$text'");
    $query->execute();
    header("Location: index.php");
    exit();
  }
} else {
 $name = 'значение по умолчанию';
}


text:
Q: VBA-Powerpoint Is the position of shapes in groups mistaken? I create a group with shape "A" (let's say a rectangle) and shape "B".
It happens that bot A.Left\Top and B.Left\Top are equal to Group.Left\top.
It correctly happens that A.Name = "A", B.Name = "B", Group.Name = "GroupName".
The bahavior is very strange. I would even say that back to 1 month ago, it did not behave like that.
I realised because I used a macro that stopped working, and that was the only possible reason. Notice: I do not even know how to solve that! It seems to me that it is impossible to get left,top of a grouped shape O.o
Any clue?
Tnx


text:
Q: SQL query needs optimization SELECT LM.user_id,LM.users_lineup_id, min( LM.total_score ) AS total_score
FROM vi_lineup_master LM JOIN
     vi_contest AS C
     ON C.contest_unique_id = LM.contest_unique_id join
     (SELECT min( total_score ) as total_score
      FROM vi_lineup_master
      GROUP BY group_unique_id
     ) as preq
     ON LM.total_score = preq.total_score
 WHERE LM.contest_unique_id = 'iledhSBDO' AND
       C.league_contest_type = 1
 GROUP BY group_unique_id

Above query is to find the loser per group of game, query return accurate result but its not responding with large data. How can I optimize this?

A: You can try to move your JOINs to subqueries. Also, you should pay attention on your "wrong" GROUP BY usage on the outer query. In Mysql you can group by some columns and select others not specified in the group clause without any aggregation function, but the database can't ensure what data it will return to you. For the sake of consistency of your application, wrap them in an aggregation function.
Check if this one helps:
SELECT
  MIN(LM.user_id) AS user_id,
  MIN(LM.users_lineup_id) AS users_lineup_id,
  MIN(LM.total_score) AS total_score
FROM vi_lineup_master LM
WHERE 1=1
  -- check if this "contest_unique_id" is equals
  -- to 'iledhSBDO' for a "league_contest_type" valued 1
  AND LM.contest_unique_id IN
  (
    SELECT C.contest_unique_id
    FROM vi_contest AS C
    WHERE 1=1
      AND C.contest_unique_id = 'iledhSBDO'
      AND C.league_contest_type = 1
  )
  -- check if this "total_score" is one of the
  -- "min(total_score)" from each "group_unique_id"
  AND LM.total_score IN
  (
    SELECT MIN(total_score)
    FROM vi_lineup_master
    GROUP BY group_unique_id
  )
GROUP BY LM.group_unique_id
;

Also, some pieces of this query may seem redundant, but it's because I did not want to change the filters you wrote, just moved them.
Also, your query logic seems a bit strange to me, based on the tables/columns names and how you wrote it... please, check the comments in my query which reflects what I understood of your implementation.
Hope it helps.


text:
Q: how to wait for all requests to complete before doing the next action (fetch) I go through all the elements of the array and form a request for each, how can I display a success message only after all requests have been completed?
  saveAllPages() {
    const allStagesData = JSON.parse(JSON.stringify(this.data.pages)).map(el => {
        const id = el.id
        apiService.postCurrentScript(el, id)

      ??? alert('success')
}

Maybe I should use Promise all, but how implement it here?

A: I would suggest using async-await as it makes code cleaner. Async-await is just an alternaitive to using promises and is many times considered a better choice. I have converted your function into arrow function. The implementation is given below:

saveAllPages = async () => {
    const allStagesData = await (function which returns promise);
    if(allStagesData){
        alert("success");
    }
}

saveAllPages();


text:
Q: Prove that the sequence defined recursively converges. statement of the problem:
Given a positive number b and a set $E \subseteq  R$, let us say that a function $f : E \rightarrow R$ has property $X(b)$ on $E$ provided that for each pair $x, y \in E$ , $ |f(y) - f(x)| \leq  b|y-x|  $
Suppose $f$ maps the open interval $E$ into itself, $0 < b < 1$, $f$ has property $X(b)$, and
$x_0 \in E$ Prove that the sequence $\{ x_k \}$ defined recursively by $x_k = f(x_{k−1})$ for $k \geq 1$
converges.
This is the work I have written attempting the proof so far:
Given: $x_0 \in E$ $f(x_{k-1}) = x_k$ $0 < b <1$, $f$ has the property $X(b) \in E$, $|f'(x)| \leq b$, $x_0 \in E$
from $|f'(x)| \leq b$
$f(x_0) - f(x) \leq y+x_1$ becomes $f(x_0) = x_1$
$x_k = f(x_{k-1})$. for $ K\geq 1$
then $x_k = x_0 \forall k$ and the sequence converges.
is this right?


text:
Q: Limits under integrals and uniform convergence. I'm asked to discuss uniform and pointwise convergence of this sequence:
$$f_n(x)=\frac{1+nx}{2+nx^2}$$
It's easy to see that
$$\lim_{n \to \infty}f_n(x)=\frac{1}{x} \qquad \forall x \in \mathbb{R}\setminus\{0\}$$
and that $f_n(0)=\frac{1}{2}$ so we have that:
$$f_n \to f(x)=\begin{cases}\frac{1}{2} \qquad x=0 \\
\frac{1}{x} \qquad x \neq 0 \end{cases}$$
and clearly the convergence can't be uniform on $\mathbb{R}$ as $f_n(x)$ is continuous for all $n \in \mathbb{N}$ and $f(x)$ is not.
Now I try to study where it converges uniformely.  We can easily note that $f_n(x) \geq f_{n+1}(x)$ if $x\in (-\infty,0] \cup[2,+\infty) = A$ so the function converges uniformely in every compact contained A. As converse, $f_n(x) \leq f_{n+1}(x) \ \forall x \in A^C$ so we can declare that $f_n$ converges uniformely to $f$ in $\mathbb{R}\setminus\{0\}$.

*

*First question: Until now is everything true and correct? I am not convinced about the last part.

Now I am asked to evaluate
$$\lim_{n\to \infty} \int_0^{\infty} \frac{1+nx}{2+nx^3}$$
as before, we have uniform convergence at $f=\frac{1}{x^2}$ in $\mathbb{R} \setminus \{0\}$ (if my previous solution was correct) and so we can divide the integral into two pieces: the one in $[a,+\infty)$ and the other one in (0,a]. As we can't talk about uniform convergence in $0$, how am I supposed to act? I intuitively think that as $f$ is $\frac{1}{x^2}$ that I'm expected to find that the limit does not exist but I'm not sure about it (the first piece, $[a,+\infty)$ is convergent, the other one I don't know).
Thanks in advance!
Thanks in advance.

A: You are correct that $f_n(x)=\frac{1+nx}{2+nx^2}$ does not converge uniformly on $\mathbb{R}$.  But, the convergence is not uniform on $\mathbb{R}\setminus\{0\}$, as you have asserted.
Rather, $f_n(x)$ converges uniformly on all compact sets that do not contain $\{0\}$.  So, for all $\varepsilon_1>0$ and $\varepsilon_2>0$, we have uniform convergence on compact subsets of $(-\infty,-\epsilon_1]\cup [\varepsilon_2,\infty)$.
The reason that the convergence fails to be uniform on, say $(0,2]$ is that for $x\in (0,2]$
$$\limsup_{n\to \infty}\left|\frac{1+nx}{2+nx^2}-\frac1x\right|\ne 0$$
Note that for $x\in [\varepsilon_2,2]$ we have
$$\limsup_{n\to \infty}\left|\frac{1+nx}{2+nx^2}-\frac1x\right|=0$$
and the convergence is uniform on $[\varepsilon_2,2]$.

Now, let's have a look at the limit
$$\lim_{n\to\infty}\int_0^\infty \frac{1+nx}{2+nx^3}\,dx$$
The integral converges for any $n\in \mathbb{N}$, $n>0$.  Furthermore, we can write
$$\begin{align}
\int_1^\infty \frac{1+nx}{2+nx^3}\,dx&=\int_1^\infty \frac1{x^2}\,dx+\int_1^\infty \frac{x^2-2}{x^2(2+nx^3)}\,dx\\\\
&=1+\int_1^\infty \frac{x^2-2}{x^2(2+nx^3)}\,dx\\\\
\end{align}$$
It is easy to see that
$$\lim_{n\to \infty}\left|\int_1^L \frac{x^2-2}{x^2(2+nx^3)}\,dx\right|\le \lim_{n\to \infty}\frac1n \int_1^L \frac{|x^2-2|}{x^5}\,dx=0$$
So that we assert
$$\lim_{n\to\infty}\int_1^\infty \frac{1+nx}{2+nx^3}\,dx=1$$
However, note that
$$\int_0^1 \frac{1+nx}{2+nx^3}\,dx\ge \frac12+\frac14n$$
And so, $\lim_{n\to \infty}\int_0^1 \frac{1+nx}{2+nx^3}\,dx=\infty$


text:
Q: Nginx: 2 servers on same root, different index. Server 2 getting 403 forbidden I have two servers that have the same root but different indexes. The second server is a subdomain of the first server, so I want to serve all the same files except the only thing I want different is the index.
Everything works fine except for the second location part on the second server giving me 403 forbidden error on every page I visit, yet it works just fine on the first server.
If I go to domain.com/foo/ then I get the 403 forbidden. If I go to domain.com/foo/index.html, then I don't get the 403 forbidden and get served the correct files.
Any help would be appreciated.
Here is my nginx.conf:
server {
    listen 80;
    listen       443 ssl;

    root C:\Users\Lansana\Documents\Github\foo;
    index index.html;

    server_name   domain.org;

    location ~ /.+ {
        try_files $uri $uri/ /app.html =404;
    }

    location / {
        try_files $uri $uri/ /index.html =404;
    }
}

server {
    listen 80;
    listen       443 ssl;

    root C:\Users\Lansana\Documents\Github\foo;
    index subdomain.html;

    server_name   subdomain.domain.org;

    location ~ /.+ {
        try_files $uri $uri/ /app.html =404;
    }

    location / {
        try_files $uri $uri/ /index.html =404;
    }
}

A: The solution to this was to add a second file for the index on my second server.
Replace:
index subdomain.html

with:
index subdomain.html index.html


text:
Q: How can I Upgrade ODoo Module V12 to V13? I want to upgrade my Odoo module V12 to V13 Please guide me how can I do that. And can I upgrade just single module in ODOO 12? Please guide me step by step.

A: You can try Tasks to do in the migration listed above.

*

*Bump module version to 13.0.1.0.0.

*Remove any possible migration script from previous version.

*Squash administrative commits (if any) with the previous commit for reducing commit noise. They are named as "[UPD] README.rst", "[UPD] Update $MODULE.pot", "Update translation files" and similar names, and comes from OCA-git-bot, oca-travis or oca-transbot.

*Remove all the decorators @api.multi, @api.returns, @api.one, @api.cr, @api.model_cr from the code. Now they are all multi-record by default. In case of the last ones, you will need to adapt the code to the behavior change.

*Check that all "compute" methods of non-stored computed fields assign a value in any case to the field, even if it is a falsy one. (https://github.com/odoo/odoo/pull/36743/commits/2e43bfc1c4b2f61e0459614f61f90a77dc3b7233).

*Computed stored fields will keep their previous value if not assigned during the compute method, so don't rely on any expected default value.

*Replace sudo(user): "deprecated use of sudo(user), use with_user(user) instead"

*Some of the Font Awesome (FA) icons have changed their name as now Odoo uses FA v5, so you might need to change them in your module views. Check the changed names in https://fontawesome.com/how-to-use/on-the-web/setup/upgrading-from-version-4#name-changes.

*Remove all the oldname field attributes in the code. If they were added in previous version, they have served their function any way, and now in this version it's not supported, so if you have the need, create a migration script and use openupgradelib's rename_fields method.

*Remove view_type tag on action window XML definition. It's now always form (tree is not supported since 11.0 any way).

*Remove multi field from ir.actions.act_window models. Now you have binding_view_types field for indicating in which view the action will be available: list, form or empty for both. If declaring the action through the accelerator tag <act_window>, then use the attribute binding_views. More reference in https://github.com/odoo/odoo/pull/24738/commits/33d51480688065e367eb646f12b89d721749cac9.

*If having an smart-button for active field, with widget toggle_button, the archive/unarchive actions are available without doing anything more, so you can remove it. And the new paradigm is to put instead a ribbon when archived with the code <widget name="web_ribbon" text="Archived" bg_color="bg-danger" attrs="{'invisible': [('active', '=', True)]}"/>.

*If using any decimal precision in float fields (example: import odoo.addons.decimal_precision as dp; x = fields.Float(digits=dp.get_precision("Account"))), now the qualifier is put directly without the need of importing anything and simplifying syntax: x = fields.Float(digits="Account").

*In the manifest, rename python dependencies to use the PyPI distribution name instead of the import name (see https://github.com/odoo/odoo/pull/25549 for more information)

*If the module is touching Accounting part, see https://github.com/OCA/maintainer-tools/issues/430 for the structural changes detected in it.

*Add tests to increase code coverage.

*Check tasks of previous versions if you are migrating from lower versions than v12. It's also recommended to check for things not done in previous migrations.

*Do the rest of the changes you need to do for making the module works on new version.

Regex which can help to find the things to remove/change:
grep -nri 'oldname\|sudo([^\)]\+)\|api.multi\|api.returns\|api.one\|api.cr\|api.model_cr\|12.0\|compute=' $MODULE


text:
Q: Setting up a globally available web app on amazon web services First of all, I am pretty new to AWS, so my question might seem very amateur.
I am a developing a web application which needs to available globally and currently am hosting it on amazon. Since the application is still under development, i have set it up in the Singapore region. However, when i test the application, i get good response times from locations on the the east side of the globe(~50ms). However, when i test the response times from the US, it's ~550ms. So we decided to have 2 instances one in Singapore and one in the US. But i'm not able to figure out a way to handle data replication and load balancing across regions. Elastic Beanstalk only allows me to do this in a particular region. Can somebody please explain how i can achieve global availability for my web app. The following are the services i currently use.
1. Amazon EC2
2. Amazon S3
I need both database replication and S3 file replication. Also it would be great if there was a way where i just need to deploy my application on one place and the changes are reflected across all the instances we would have on the globe.

A: Before you spend a lot of time and money setting up redundant servers in different regions, you may want to make sure that you can't get the performance improvement you need simply by implementing AWS Cloudfront:

Amazon CloudFront employs a network of edge locations that cache
  copies of popular files close to your viewers. Amazon CloudFront
  ensures that end-user requests are served by the closest edge
  location. As a result, requests travel shorter distances to request
  objects, improving performance. For files not cached at the edge
  locations, Amazon CloudFront keeps persistent connections with your
  origin servers so that those files can be fetched from the origin
  servers as quickly as possible. Finally, Amazon CloudFront uses
  additional optimizations – e.g. wider TCP initial congestion window –
  to provide higher performance while delivering your content to
  viewers.

http://aws.amazon.com/cloudfront/faqs/
The nice thing is, you can set this up and test it out in very little time and for very little money. Obviously this won't solve all performance problems, especially if you app is performance bound at the database, but this is a good way of taking care of that 'low hanging fruit' when trying to speed up your website in diverse locations around the world.


text:
Q: How to find an original text representation for lower precision float values in Python? I've run into an issue displaying float values in Python, loaded from an external data-source(they're 32bit floats, but this would apply to lower precision floats too).
(In case its important - These values were typed in by humans in C/C++, so unlike arbitrary calculated values, deviations from round numbers is likely not intended, though can't be ignored since the values may be constants such as M_PI or multiplied by constants).
Since CPython uses higher precision, (64bit typically), a value entered in as a lower precision float may repr() showing precision loss from being a 32bit-float, where the 64bit-float would show round values.
eg:
# Examples of 32bit float's displayed as 64bit floats in CPython.
0.0005 -> 0.0005000000237487257
0.025  -> 0.02500000037252903
0.04   -> 0.03999999910593033
0.05   -> 0.05000000074505806
0.3    -> 0.30000001192092896
0.98   -> 0.9800000190734863
1.2    -> 1.2000000476837158
4096.3 -> 4096.2998046875

Simply rounding the values to some arbitrary precision works in most cases, but may be incorrect since it could loose significant values with eg: 0.00000001.
An example of this can be shown by printing a float converted to a 32bit float.
def as_float_32(f):
    from struct import pack, unpack
    return unpack("f", pack("f", f))[0]

print(0.025)               #  --> 0.025
print(as_float_32(0.025))  #  --> 0.02500000037252903

So my question is:
Whats the most efficient & straightforward way to get the original representation for a 32bit float, without making assumptions or loosing precision?
Put differently, if I have a data-source containing of 32bit floats, These were originally entered in by a human as round values, (examples above), but having them represented as higher precision values exposes that the value as a 32bit float is an approximation of the original value.
I would like to reverse this process, and get the round number back from the 32bit float data, but without loosing the precision which a 32bit float gives us. (which is why simply rounding isn't a good option).

Examples of why you might want to do this:

*

*Generating API documentation where Python extracts values from a C-API that uses single precision floats internally.

*When people need to read/review values of data generated which happens to be provided as single precision floats.

In both cases it's important not to loose significant precision, or show values which can't be easily read by humans at a glance.

*

*Update, I've made a solution which I'll include as an answer (for reference and to show its possible), but highly doubt its an efficient or elegant solution.

*Of course you can't know the notation used: 0.1f, 0.1F or 1e-1f where entered, that's not the purpose of this question.

A: I think Decimal.quantize() (to round to a given number of decimal digits) and .normalize() (to strip trailing 0's) is what you need.
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from decimal import Decimal

data = (
    0.02500000037252903,
    0.03999999910593033,
    0.05000000074505806,
    0.30000001192092896,
    0.9800000190734863,
    )

for f in data:
    dec = Decimal(f).quantize(Decimal('1.0000000')).normalize()
    print("Original %s -> %s" % (f, dec))

Result:
Original 0.0250000003725 -> 0.025
Original 0.0399999991059 -> 0.04
Original 0.0500000007451 -> 0.05
Original 0.300000011921 -> 0.3
Original 0.980000019073 -> 0.98

A: You're looking to solve essentially the same problem that Python's repr solves, namely, finding the shortest decimal string that rounds to a given float. Except that in your case, the float isn't an IEEE 754 binary64 ("double precision") float, but an IEEE 754 binary32 ("single precision") float.
Just for the record, I should of course point out that retrieving the original string representation is impossible, since for example the strings '0.10', '0.1', '1e-1' and '10e-2' all get converted to the same float (or in this case float32). But under suitable conditions we can still hope to produce a string that has the same decimal value as the original string, and that's what I'll do below.
The approach you outline in your answer more-or-less works, but it can be streamlined a bit.
First, some bounds: when it comes to decimal representations of single-precision floats, there are two magic numbers: 6 and 9. The significance of 6 is that any (not-too-large, not-too-small) decimal numeric string with 6 or fewer significant decimal digits will round-trip correctly through a single-precision IEEE 754 float: that is, converting that string to the nearest float32, and then converting that value back to the nearest 6-digit decimal string, will produce a string with the same value as the original. For example:
>>> x = "634278e13"
>>> y = float(np.float32(x))
>>> y
6.342780214942106e+18
>>> "{:.6g}".format(y)
'6.34278e+18'

(Here, by "not-too-large, not-too-small" I just mean that the underflow and overflow ranges of float32 should be avoided. The property above applies for all normal values.)
This means that for your problem, if the original string had 6 or fewer digits, we can recover it by simply formatting the value to 6 significant digits. So if you only care about recovering strings that had 6 or fewer significant decimal digits in the first place, you can stop reading here: a simple '{:.6g}'.format(x) is enough. If you want to solve the problem more generally, read on.
For roundtripping in the other direction, we have the opposite property: given any single-precision float x, converting that float to a 9-digit decimal string (rounding to nearest, as always), and then converting that string back to a single-precision float, will always exactly recover the value of that float.
>>> x = np.float32(3.14159265358979)
>>> x
3.1415927
>>> np.float32('{:.9g}'.format(x)) == x
True

The relevance to your problem is there's always at least one 9-digit string that rounds to x, so we never have to look beyond 9 digits.
Now we can follow the same approach that you used in your answer: first try for a 6-digit string, then a 7-digit, then an 8-digit. If none of those work, the 9-digit string surely will, by the above. Here's some code.
def original_string(x):
    for places in range(6, 10):  # try 6, 7, 8, 9
        s = '{:.{}g}'.format(x, places)
        y = np.float32(s)
        if x == y:
            return s
    # If x was genuinely a float32, we should never get here.
    raise RuntimeError("We should never get here")

Example outputs:
>>> original_string(0.02500000037252903)
'0.025'
>>> original_string(0.03999999910593033)
'0.04'
>>> original_string(0.05000000074505806)
'0.05'
>>> original_string(0.30000001192092896)
'0.3'
>>> original_string(0.9800000190734863)
'0.98'

However, the above comes with several caveats.

*

*First, for the key properties we're using to be true, we have to assume that np.float32 always does correct rounding. That may or may not be the case, depending on the operating system. (Even in cases where the relevant operating system calls claim to be correctly rounded, there may still be corner cases where that claim fails to be true.) In practice, it's likely that np.float32 is close enough to correctly rounded not to cause issues, but for complete confidence you'd want to know that it was correctly rounded.

*Second, the above won't work for values in the subnormal range (so for float32, anything smaller than 2**-126). In the subnormal range, it's no longer true that a 6-digit decimal numeric string will roundtrip correctly through a single-precision float. If you care about subnormals, you'd need to do something more sophisticated there.

*Third, there's a really subtle (and interesting!) error in the above that almost doesn't matter at all. The string formatting we're using always rounds x to the nearest places-digit decimal string to the true value of x. However, we want to know simply whether there's any places-digit decimal string that rounds back to x. We're implicitly assuming the (seemingly obvious) fact that if there's any places-digit decimal string that rounds to x, then the closest places-digit decimal string rounds to x. And that's almost true: it follows from the property that the interval of all real numbers that rounds to x is symmetric around x. But that symmetry property fails in one particular case, namely when x is a power of 2.
So when x is an exact power of 2, it's possible (but fairly unlikely) that (for example) the closest 8-digit decimal string to x doesn't round to x, but nevertheless there is an 8-digit decimal string that does round to x. You can do an exhaustive search for cases where this happens within the range of a float32, and it turns out that there are exactly three values of x for which this occurs, namely x = 2**-96, x = 2**87 and x = 2**90. For 7 digits, there are no such values. (And for 6 and 9 digits, this can never happen.) Let's take a closer look at the case x = 2**87:
>>> x = 2.0**87
>>> x
1.5474250491067253e+26

Let's take the closest 8-digit decimal value to x:
>>> s = '{:.8g}'.format(x)
>>> s
'1.547425e+26'

It turns out that this value doesn't round back to x:
>>> np.float32(s) == x
False

But the next 8-digit decimal string up from it does:
>>> np.float32('1.5474251e+26') == x
True

Similarly, here's the case x = 2**-96:
>>> x = 2**-96.
>>> x
1.262177448353619e-29
>>> s = '{:.8g}'.format(x)
>>> s
'1.2621774e-29'
>>> np.float32(s) == x
False
>>> np.float32('1.2621775e-29') == x
True

So ignoring subnormals and overflows, out of all 2 billion or so positive normal single-precision values, there are precisely three values x for which the above code doesn't work. (Note: I originally thought there was just one; thanks to @RickRegan for pointing out the error in comments.) So here's our (slightly tongue-in-cheek) fixed code:
def original_string(x):
    """
    Given a single-precision positive normal value x,
    return the shortest decimal numeric string which produces x.
    """
    # Deal with the three awkward cases.
    if x == 2**-96.:
        return '1.2621775e-29'
    elif x == 2**87:
        return '1.5474251e+26'
    elif x == 2**90:
        return '1.2379401e+27'

    for places in range(6, 10):  # try 6, 7, 8, 9
        s = '{:.{}g}'.format(x, places)
        y = np.float32(s)
        if x == y:
            return s
    # If x was genuinely a float32, we should never get here.
    raise RuntimeError("We should never get here")

A: Heres a solution I've come up with which works (perfectly as far as I can tell) but isn't efficient.
It works by rounding at increasing decimal places, and returning the string when the rounded and non-rounded inputs match (when compared as values converted to lower precision).
Code:
def round_float_32(f):
    from struct import pack, unpack
    return unpack("f", pack("f", f))[0]

def as_float_low_precision_repr(f, round_fn):
    f_round = round_fn(f)
    f_str = repr(f)
    f_str_frac = f_str.partition(".")[2]
    if not f_str_frac:
        return f_str
    for i in range(1, len(f_str_frac)):
        f_test = round(f, i)
        f_test_round = round_fn(f_test)
        if f_test_round == f_round:
            return "%.*f" % (i, f_test)
    return f_str

# ----

data = (
    0.02500000037252903,
    0.03999999910593033,
    0.05000000074505806,
    0.30000001192092896,
    0.9800000190734863,
    1.2000000476837158,
    4096.2998046875,
    )

for f in data:
    f_as_float_32 = as_float_low_precision_repr(f, round_float_32)
    print("%s -> %s" % (f, f_as_float_32))

Outputs:
0.02500000037252903 -> 0.025
0.03999999910593033 -> 0.04
0.05000000074505806 -> 0.05
0.30000001192092896 -> 0.3
0.9800000190734863 -> 0.98
1.2000000476837158 -> 1.2
4096.2998046875 -> 4096.3

A: If you have at least NumPy 1.14.0, you can just use repr(numpy.float32(your_value)). Quoting the release notes:

Float printing now uses "dragon4" algorithm for shortest decimal representation
The str and repr of floating-point values (16, 32, 64 and 128 bit) are now printed to give the shortest decimal representation which uniquely identifies the value from others of the same type. Previously this was only true for float64 values. The remaining float types will now often be shorter than in numpy 1.13.

Here's a demo running against a few of your example values:
>>> repr(numpy.float32(0.0005000000237487257))
'0.0005'
>>> repr(numpy.float32(0.02500000037252903))
'0.025'
>>> repr(numpy.float32(0.03999999910593033))
'0.04'

A: At least in python3 you can use .as_integer_ratio. That's not exactly a string but the floating point definition as such is not really well suited for giving an exact representation in "finite" strings.
a = 0.1
a.as_integer_ratio()
(3602879701896397, 36028797018963968)

So by saving these two numbers you'll never lose precision because these two exactly represent the saved floating point number. (Just divide the first by the second to get the value).

As an example using numpy dtypes (very similar to c dtypes):
# A value in python floating point precision
a = 0.1
# The value as ratio of integers
b = a.as_integer_ratio()

import numpy as np
# Force the result to have some precision:
res = np.array([0], dtype=np.float16)
np.true_divide(b[0], b[1], res)
print(res)
# Compare that two the wanted result when inputting 0.01
np.true_divide(1, 10, res)
print(res)

# Other precisions:
res = np.array([0], dtype=np.float32)
np.true_divide(b[0], b[1], res)
print(res)
res = np.array([0], dtype=np.float64)
np.true_divide(b[0], b[1], res)
print(res)

The result of all these calculations is:
[ 0.09997559] # Float16 with integer-ratio
[ 0.09997559] # Float16 reference
[ 0.1] # Float32
[ 0.1] # Float64

A: Probably what you are looking for is decimal:

Decimal "is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school."


text:
Q: Make the UICollectionView scrollable even when its not full The UICollectionView disables scrolling by default when there is not enough cells in the view. When this occurs I need it to bounce back to position when pulled. Im am aware of a hack where I can fill the UICollectionView with empty tables to enable scrolling but I was hoping there would be a slightly more fluid example as
I don't want the view to scroll but instead to automatically bounce back to its position. This is because of the effect I have implemented below as can see below.
https://youtu.be/r75xB9-Mb4g
Is there a way to achieve this simply, when there is not enough cells in the UICollectionView the scroll is disabled.

A: For vertical scrolling:
self.collectionView.alwaysBounceVertical = true;

For horizontal scrolling:
self.collectionView.alwaysBounceHorizontal = true;


text:
Q: BackGround Worker in c# to Parse the File List Recursively avoiding Acces Denied Exception  I'm trying to list all the files from the a Folder/Drive including the Sub Directories while Ignoring the Access Denied Exception that arises when i use the Directory.GetFiles() method.
I have got the Method.The problem is that the Method involves recursive calls to itself, i cannot call the background worker recursively.How can i implement this method as a Background work.
 static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
    System.IO.FileInfo[] files = null;
    System.IO.DirectoryInfo[] subDirs = null;

    // First, process all the files directly under this folder
    try
    {
        files = root.GetFiles("*.*");
    }
    // This is thrown if even one of the files requires permissions greater
    // than the application provides.
    catch (UnauthorizedAccessException e)
    {
        // This code just writes out the message and continues to recurse.
        // You may decide to do something different here. For example, you
        // can try to elevate your privileges and access the file again.
        log.Add(e.Message);
    }

    catch (System.IO.DirectoryNotFoundException e)
    {
        Console.WriteLine(e.Message);
    }

    if (files != null)
    {
        foreach (System.IO.FileInfo fi in files)
        {
            // In this example, we only access the existing FileInfo object. If we
            // want to open, delete or modify the file, then
            // a try-catch block is required here to handle the case
            // where the file has been deleted since the call to TraverseTree().
            Console.WriteLine(fi.FullName);
        }

        // Now find all the subdirectories under this directory.
        subDirs = root.GetDirectories();

        foreach (System.IO.DirectoryInfo dirInfo in subDirs)
        {
            // Resursive call for each subdirectory.
            WalkDirectoryTree(dirInfo);
        }
    }
}

}

A: Very easy: just call this method inside your background-workers body-method.


text:
Q: When Grouping RadGridView Append header data and Row Data While grouping in the Telerik RadGridview , the group header has to be appended with column data. Like "Name : James", where "Name " is column header and "James " is column data. Kindly share your comments.

A: Not really clear what you asking but try this:
</Columns>
   <GroupByExpressions>
      <telerik:GridGroupByExpression>
        <SelectFields>
          <telerik:GridGroupByField FieldName="Name"/>
        </SelectFields>
     <GroupByFields>
      <telerik:GridGroupByField FieldName="Name"/>
     </GroupByFields>
      </telerik:GridGroupByExpression>
   </GroupByExpressions>


text:
Q: Moderation Log Message Discord JS Hello StackOverflow community, this is my first question in need help with for Discord, could someone please edit this code to made this command send a log to #logs channel with the following info
1) Title - Moderation Log
2) User the moderation action was performed on
3) What moderation action was performed (in this case ban)
4) Moderator
5) Footer - Proton Servers Bot©2020

const { client, config, functions } = require('../index.js');

module.exports.run = async (message, u) => {
  if (!message.member.hasPermission('BAN_MEMBERS')) return message.channel.send(functions.errorEmbed('You are not permitted to do this.'));

  if (!u) return message.channel.send(functions.usageEmbed(config.prefix + 'ban <user/id>'));

  const userID = u.match(/[0-9]+/) ? u.match(/([0-9]+)/)[0] : undefined;
  const user = message.guild.members.get(userID);

  if (!user) return message.channel.send(functions.errorEmbed('**' + u + '** is not a valid user.'));

  try {
    await user.ban();
    return message.channel.send(functions.successEmbed('Banned ' + user + ' successfully.'));
  } catch {
    return message.channel.send(functions.errorEmbed('Could not ban ' + user + '. Is their role higher than mine?'));
  }
}

module.exports.description = 'Ban a user.';```

A: This answer is for discord.js v11. If you want to do this using discord.js v12 then use MessageEmbed instead of RichEmbed and use cache to get the channels collection message.guild.channels.cache
You could use a RichEmbed to create the embed you want and then send it to the log channel.
First, though, you have to get the log channel, there are 2 ways of doing this:
By name: const logChannel = message.guild.channels.find(channel => channel.name === 'log')
Or by ID: const logChannel = message.guild.channels.get(CHANNEL_ID)
Then you could use that to send the following embed
const embed = new Discord.RichEmbed() // Or new RichEmbed depending on how you're importing things
  .setTitle('Moderation Log')
  .addField('Banned', user)
  .addField('Banned By', message.author)
  .setFooter('Proton Servers Bot©2020')

logChannel.send(embed)


text:
Q: Использование разных экшенов в Ajax.BeginForm в зависимости от условия Есть таблица на форме. В неё можно добавлять записи, редактировать или удалять. В зависимости от выбранного действия используются разные экшены контроллера. И если использовать jquery ajax я могу использовтаь например один и тот же ajax запрос передавая в него разные url адреса экшенов и функции успешного и не успешного выполнения. А можно ли при использовании Ajax.BeginForm так же использовать различные экшены в зависимости от ситуации?

A: да
вот разметка что создается
<form action="/Controller/Action" data-ajax="true" data-ajax-mode="replace" data-ajax-
   update="#results" id="form0" method="post">
    <input type="text" name="name" />
    <input type="submit" value="Поиск" />
</form>

просто менять атрибут action


text:
Q: Change value of text box using javascript (Jquery) before post back ASP.NET I am trying to change the value of a set of text boxes (that hold greyed out suggestions in them) when the user presses the submit form button. This button runs a server side method using OnClientClick that submits the data and does a whole slew of other things.
Now my problem is that i can't either: fit in a javascript function that will change the values before the server gets hit, OR call the server side method in the javascript instead of the button OnClientClick event.
Ive tried:
$(this.form).submit(function(){
//Change value here
});
//using OnClientClick to call function

and
$("#"+"<%=submitBtn.ClientID %>").click(function(){
    //Change values here
    __doPostBack("<%=submitBtn.ClientID %>");
});
//not using OnClientClick to call server method

(pretty sure that won't work)
and
$("#"+"<%=submitBtn.ClientID %>").click(function(){
    //Change values here
});
//using OnClientClick still to call function

Im stumped

Edit
Right I obviously didn't give enough info,
What happens when I use submit events is the server event fires before the JavaScript event, therefore when do a server side validation before I send the values away, I have the wrong values, there isn't any point in changing to client side validation because i will still have the same problem when I send the form data back to the db.

Update
So i still have a problem (both with this and mentally because of this).
Because of the idiots who worked on this before me (now i have to fix it) they removed the submit behaviour (asp.net) from the button at the bottom, because they use some server side trickery to figure out if some validators should be on or off (when really it should be client side that does that), hence they had to turn it off because it would fire validators if it didn't.
ANYWAY... So I'm still having trouble, the on click function for the button doesn't seem to fire in time or the scripts run simultaneously. I tested this by adding an alert and a breakpoint on the code behind, the breakpoint fires and the alert fires too. sooo..... yeah.
Is there any way i could maybe circumvent this by removing the "onclientclick" from the button and calling the function it calls in the CB?
Any ideas? (Please?)

Small update:
Still can't figure it out :(. Is anyone confused by the question?

A: Yup, this function should work
$(this.form).submit(function(){
//Change value here
});

But one culprit might be the commented part:  "// Change values here."  If you're using one of these,
$('#target').text('my new info');
$('#target').html('my new info');

...you will have trouble. You need to use .val()
$('#target').val('my new info');

A: Just stumbled across this.  It's been a month since you first posted the question so you may have fixed it already.  However, thought I'd add my thoughts anyway.
First, it's make sense your code is being ignored.  When you bind to the submit and onclick events you functions are added to the list of events handles.  Events handlers are processed from the first added to the last added.  So the postback is started before your jquery code is called.
To solve this you need to change the code in the function that OnClientClick calls or write a wrapper function that calls your code then calls what OnClientClick called and change OnClientClick to call your wrapper function.

A: The form is submitted before JS fires all events.
Have your button's onClientClick event change the values. You can call functions in sequence if you need to.
jQuery does some funky things with events and you can't be sure what order they will fire after they are attached. You must explicitly specify the functions to call.
<button id="some_button" onclick="SetValues(); SubmitForm();" />

A: this function should do the trick:
$(this.form).submit(function(){
//Change value here
});

just make sure you enable the text fields again before you send them to the server, otherwise the server won't pick them up

A: I have used id of submit button to check for a "click"
http://jsfiddle.net/sreeprasad/7urvg/


text:
Q: Randomly generate numbers based on stock in MySQL database I need a bit of help with a script I am making in Php. Currently it is setup as a slot style game, where users can pay a bit of money and 3 random number are generated, each number links up to a prize they can win. Match 3 and win said prize.
Unfortunately as I will not always have every item in stock to give away as a prize I need a way to check through each number and make sure it is in stock:
$stock = $conn -> query('SELECT DISTINCT ItemID FROM codes WHERE Available = 1');
And if it is in stock add it in an algorithm which will randomly pick the 3 numbers. Currently I have a setup like so:
function generate_numbers(){
global $numbers;
$numbers = array(
'0' => rand(1,2),
'1' => rand(1,2),
'2' => rand(1,2)
);
display_numbers();
}

Which generates numbers based upon two variables and each number links to a prize. Obviously it does not take into account which numbers are in stock, which will lead to me giving out prizes I dont have, and it does not allow for an edge.
I need a simple way to check if an item is in stock and if it is stocked it is added to a list of prizes that can be won, I need it to have an edge so some prizes will appear (a lot) more frequently than others based on simple values like code X has a 0.25% chance of appearing and cody Y has a 50% chance of appearing.
If I set it up with a larger range of numbers:
function generate_numbers(){
global $numbers;
$numbers = array(
'0' => rand(1,100),
'1' => rand(1,100),
'2' => rand(1,100)
);
display_numbers(); }

if (($numbers[0] > 0) && ($numbers[0] < 40)){
echo "you win prize x";
else if (($numbers[0] > 40) && ($number[0] < 50)){
echo "you win prize y";
else {
echo "you win prize z";
}

I am still left either giving out prizes I do not have - or I could add a embedded if else to check if a code is stocked, if it is give it out and if it isn't either give no prize or give a default prize.
But this will mean that the more codes I have in stock the higher chance they have of being given which I don't want to do I really want it to be completely fair with predefined odds.
So hopefully all that makes sense it's not an overly complex problem but I think quite an unusual one.

A: Scanning your question, I think you need to change your query
$stock = $conn -> query('SELECT DISTINCT ItemID FROM codes WHERE Available = 1 ORDER BY RAND()');

with this you pick the first 3 and you got 3 random prizes,
this is a quick solution. with chances its gonna be more complicated let me think...
EDIT
After some testing I think I got it,
You need top a add a column chance which is gonna be a number and the chance of that record appearing is then 1 on N,
The extra where code is:
0 = FLOOR(RAND()*chance)
so the final code is
$stock = $conn ->query(
    'SELECT DISTINCT ItemID FROM codes WHERE Available = 1 AND 0 = FLOOR(RAND()*chance) ORDER BY RAND()'
);

A: If I understand you right, you might begin with creating an array of available prizes with the query in beginning.
So the array would be:
{0 => prize1_id,
 1 => prize3_id,
 2 => prize4_id,
 // ...and so on
 }

Then you can take random numbers but not from the prizes ids, but array indices (keys).
If you want some items have more chance to be chosen, you can add them twice for example.

A: One way you could do this (if you don't have very many items) is to create an array of the ItemIDs and use shuffle() on the array.  Then select the first three elements ( or randomize this selection with rand() or mt_rand()) to be the numbers you display.  This way you can pick items that do not exist.  You can alter this algorithm to check stock levels so that it doesn't add an ItemID with no or low stock as you decide (may be via a new column in codes that defines the minimum stock required for the item to be chosen).
To get the edge you can add a number of duplicate ItemIDs for items that you want to be selected more often.  You can add another column to the codes table to indicate the number of times you want to include a particular item, so with a minimum of 3 (to match three numbers) you can assign an larger values for for ItemIDs that you want to be picked more often by the algorithm.  It also has the possibility of putting 0 for items you don't want to give away.


text:
Q: Sharing a variable between bootloader and application in C I want to share a variable (a boolean is enough) between bootloader and application.
Bootloader should write a boolean instead the application should read it.
I thought I can write 1 or a 0 to a certain address (0x40000100), like this:
uint8_t *microType = (uint8_t *)0x40000100;

microType = 1;

Is it right?
As microprocessor I'm using NXP MPC5645C
Thank you in advance.

A: *

*You need to create the section in the bootloader and application linker script. It is required compiler and linker do not place any other variables in this chunk of memory. The best place is the beginning or end of RAM as other sections cannot have "gaps". Section should have fixed address and to be the fist (or last if it is placed at the end of RAM) defined in the linker script.

Then you simply create the variable(s) and place them in those section.

A: To do this, you will need to set up and reserve a dedicated RAM segment at an absolute address. You obviously cannot use 0x40000100 because that points into the middle of the stack and the stack can't be used for this. You also can't just use any variable identifier to something located in .bss/.data, because that one may translate to a different physical address at any point, whenever the program is changed.
Also, you shouldn't rely on values in RAM getting preserved after reset, so if you execute the bootloader, then MCU reset and execute the application, that's not a good idea for the average kind of mission-/safety-critical applications MPC56 are usually used for. NXP microcontrollers have a tradition of well-defined value preservation of variables in RAM upon "soft reset" such as watchdog timeout, but I don't remember if this applies to MPC56.
Furthermore, if the value is to be preserved between resets, you have to consider how to initialize this custom RAM segment manually. Doing so means you'll have to tweak the CRT code, which isn't trivial. You'll want to zero-out the segment upon power-on reset and similar, but to leave it untouched upon watchdog reset etc.
As for how to make a custom memory segment, that depends on the tool chain. In Codewarrior you'd have to tweak the linker script (.lcf file), creating one memory range below MEMORY and add a GROUP below SECTIONS. Be careful with alignment; it will expect at least 32 bit alignment but there might be other considerations too (check the friendly manual). Then add some icky pragma to the actual variable declaration, along the lines of this:
#pragma section RW ".my_section"
__declspec(section ".my_section")
volatile uint32_t the_variable;

Once you've gotten that far, this variable should be accessible from both the bootloader and the application. It has to be volatile so that the compiler compiling the application doesn't make strange assumptions about the variable never getting written to.


text:
Q: File upload with Jersey - FormDataContentDisposition is null I am quite aware that there are a lot of questions same as this one, but none of them are helping me since my HTML file name is the same as the one in JavaScript and Java. Here is JavaScript code:
        var fd = new FormData();
        fd.append('firstName', $scope.user.firstName);
        fd.append('lastName', $scope.user.lastName);
        fd.append('phoneNumber', $scope.user.phoneNumber);
        fd.append('email', $scope.user.email);
        fd.append('username', $scope.user.username);
        fd.append('password', $scope.user.password);
        fd.append('file', $scope.user.profilePicture);
        fd.append('file', $scope.user.profilePicture.name);
        console.log("Image:" + $scope.user.profilePicture);
        console.log("Image name:" + $scope.user.profilePicture.name);

When i console.log("Image name:" + $scope.user.profilePicture.name); everything seems fine, but the moment i send request i get null. Here is Java code:
    @Path("/register")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response registerUser(
            @FormDataParam("firstName") String firstName,
            @FormDataParam("lastName") String lastName,
            @FormDataParam("phoneNumber") String phoneNumber,
            @FormDataParam("email") String email,
            @FormDataParam("username") String username,
            @FormDataParam("password") String password,
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDescription,
            @Context ServletContext servletContext) throws JsonGenerationException, JsonMappingException, IOException {

        String uploadedFileLocation = servletContext.getRealPath("/resources/images")+"/"+fileDescription.getFileName();

        writeToFile(uploadedInputStream, uploadedFileLocation);

        String imgPath = "http://localhost:8080/WebProjekat/resources/images/" + fileDescription.getFileName();
        User user = new User(username, password,firstName,lastName,phoneNumber,email,imgPath);

        if(userService.addUser(user)) {
            return Response.status(Status.CREATED)
                    .entity(user)
                    .build();
        }else
            return Response.status(Status.NOT_ACCEPTABLE)
                    .entity(user)
                    .build();

    }

somehow FormDataContentDisposition fileDescription is always null. Here is HTML code:

    <input type="button" class="btn btn-primary" style="width: 100%;height: 30px; display: flex;align-items: center;justify-content: center;" value="Load Image" onclick="$('#loadProfileImg').click();" />

    <input type="file" accept="image/*" class="form-control" id="loadProfileImg" ng-required="true" onchange="angular.element(this).scope().readURL(this);" style="display:none;" name="file" />

As you can see i have named
<input type='file'>

the same as i did the key back in JavaScript . I also included this inside my web.xml:
<init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>

ANY kind of help will be appreciated. Thank you guys in advance!
UPDATE: I have fixed the null problem, i accidently wrote:
fd.append('file', $scope.user.profilePicture);
        fd.append('file', $scope.user.profilePicture.name);

instead of:
fd.append('file', $scope.user.profilePicture, $scope.user.profilePicture.name);

But sadly i have another issue. Now my img path is correct but i am getting 404 NOT FOUND even though i see image name inside the folder it was meant to upload, but i cannot see the image itself. I am using this code on 2 more different objects and it works fine.  Any ideas?

A: Read the url append the form data .
<input type="file" class="form-control" id="file" ng-model="file"
       onchange="angular.element(this).scope().getTheFiles(this)" />

Controller
var formdata = new FormData();
$scope.getTheFiles = function(element) {
    $scope.$apply(function($scope) {
        $scope.files = element.files;
        for (var i = 0; i < element.files.length; i++) {
            formdata.append('files', element.files[i]);
        }
    });
};

Next send the URL
Java side get value like @FormDataParam("files") List<FormDataBodyPart> files.


text:
Q: PHP/My SQL Database -> to Arduino Serial Monitor I'm using this domain http://www.decathlon.commonarchitecture.ca/ to host my phpmyadmin database and php code. I would like to read a specific column of the database in the serial monitor, displaying each number one right after the other. I'm unsure of whether to work with a GSM shield, an Ethernet shield or an Arduino wifi shield. Here is my php code (indents are off I know):
<?php

 $dbhost = "mysql.commonarchitecture.ca";
 $username = "arduinodb";
 $password = "*******";
 $db = "arduinodb" ;

    mysql_connect("$dbhost" , "$username" , "$password");
     //echo "Connected" ;

    //select db
    mysql_select_db($db);
    //echo "Connected to db" ;

  $sql="SELECT * FROM data";

  $records=mysql_query($sql);

 ?>

 <!DOCTYPE html>

 <title> Consumption Data </title>

 Day
 Date
 Water Consumption (liters per person)

 <?php

    while($data=mysql_fetch_assoc($records)) {

         echo "
";

         echo "".$data['id']."	";

         echo "".$data['date']."	";

         echo "".$data['value']."	";

         echo "
";

     }//end while

     ?>

The code works, however I'm unsure of how to go about reading the data on an Arduino (very new to Arduino)
Here's my Arduino code paired with an ethernet shield
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192, 168, *, *);

EthernetClient client;

char server[] = "www.decathlon.commonarchitecture.ca";

void setup()
{
   Serial.begin(9600);

  // attempt a DHCP connection:
  Serial.println("Attempting to get an IP address using DHCP:");
  if (!Ethernet.begin(mac)) {
  // if DHCP fails, start with a hard-coded address:
  Serial.println("failed to get an IP address using DHCP, trying
  manually");
     Ethernet.begin(mac, ip);
  }

  Serial.print("My address:");
  Serial.println(Ethernet.localIP());
}

void loop()
{
    // connect to the server
    if (client.connect(server, 80))
    {
        // print to serial monitor
        Serial.println("connected...");
        Serial.println("ARDUINO: forming HTTP request message");

        // send data the server through GET request
        client.print("GET /index.php?value");
        client.println(" HTTP/1.1");
        client.print("HOST:  ");
        client.println(server);

        Serial.println("ARDUINO: HTTP message sent");

        // give server time to receive request
        delay(1000);

        // get the response from the page and print it to serial port
        // to ascertain that request was received properly
        if(client.available())
        {
            Serial.println("ARDUINO: HTTP message received");
            Serial.println("ARDUINO: printing received headers and
script response...\n");

            while(client.available())
            {
                char c = client.read();
                Serial.print(c);
            }
        }
        else
        {
            Serial.println("ARDUINO: no response received / no response
received in time");
        }

        client.stop();
    }
    // do nothing forever after:
    while(true);
}

My issue now is in getting the Arduino to read my php data, can I not use an http GET request to display data in my serial monitor? Am I using this function properly? There's a ton of documentation on posting Arduino sensor data to the web using php/my sql but not as much on retrieval of set data back into the serial monitor. Here's what the monitor reads currently...
Attempting to get an IP address using DHCP:
My address:192.168.*.*
connected...
ARDUINO: forming HTTP request message
ARDUINO: HTTP message sent
ARDUINO: no response received / no response received in time


text:
Q: Struts2 datepickers breaks into separate lines when used inside a table I am using struts2 datepicker and have a scenario in which I have to mention dates in the format of:
From: [Date] To: [Date]
but whenever I am using

      <sx:datetimepicker label= "From" />
      <sx:datetimepicker label= "To" />

this breaks the components into four separate lines. I want them to be in one line. I have also used styles like "inline" and "inline-block" but nothing works.
Expected Result:

From: [Date] To: [Date]

Current Result:
From: [Date]
To:   [Date]

A: In one line then use two columns in the table

  <sj:datetimepicker label= "From" />

  <sj:datetimepicker label= "To" />

A: use theme as simple instead of xhtml.By Default theme  is xhtml.
for example:
<s:div theme="simple" />


text:
Q: Searching for numeric values and conditions in text file (Python) I have a text file with the following format:
------------------------------------------------------------
Name=A     Run=true     Idle=15
Name=B     Run=true     Idle=10
Name=C     Run=false    Idle=75
Name=D     Run=true     Idle=92
Name=E     Run=false    Idle=6
Name=F     Run=false    Idle=21

-------------------------------------------------------------

I want to search this text file for a run condition of "true" AND an idle of greater than a set value (lets say 10 for example). Once this condition is met, I want to print the whole line. How can I obtain this? The current code is:
def main():
  with open('data.txt', 'r') as searchfile:
    for line in searchfile:
      if ("Run=true") in line:
        if ("Idle>=10") in line:
          print "\n"
          print line

if __name__ == '__main__':
  main()

A: This should do:
def main():
  with open('data.txt', 'r') as searchfile:
    for line in searchfile:
      line = line.strip()
      # This works because Python checks this substring in the line
      if ("Run=true") in line:
        firstSplit = line.split("Idle=")[1]
        # Splitting again to get the first element before the whitespace
        idleNum = int(firstSplit.split('\s')[0])
        # This had to be changed as you are comparing integers while
        # the data is still of type string
        if (idleNum >=10):
          print line

if __name__ == '__main__':
  main()

Result using data above:
Name=A     Run=true     Idle=15
Name=B     Run=true     Idle=10
Name=D     Run=true     Idle=92

A: Almost ... let's get to that innermost if ...
At this point, you need to extract the value:
field_list = line.split(' ')

field list is now a list of three strings, the space-separated fields.  Now, grab the last one and split on the equals sign:
idle_field = field_list[-1].split('=')

idle_field now contains two strings: "Idle" and the number.  Finally:
if int(idle_field) >= 10:
    print "\n", line

There's your required condition.
It is possible to fold all that processing into the if condition, but I recommend keeping the program readable.  :-)

A: You are trying to compare an integer by searching for it in a string. Try this
import re

def main():
    with open('data.txt', 'r') as searchfile:
            for line in searchfile:
                if ("Run=true") in line:
                    if int(re.findall(r"Idle=(.+)", line)[0]) >= 10:
                        print line

if __name__ == '__main__':
    main()


text:
Q: Nifi for database migration Why would nifi be a good use case for database migration if all it does is sending the same data over and over again?(I have tried to extract data from a database and putting them into a JSON file I was seeing multiple entries of the same tuple.) Wouldn't that be a waste of computing resources?
If I just want to migrate the database once and sometimes update the changed columns only, is nifi still a good tool to use?

A: It all depends on which database you want to migrate from/to which environments. Is it a large enterprise Oracle DB you want to migrate into Hadoop? Look into Sqoop https://sqoop.apache.org/. I would recommend Sqoop for doing one-time imports of large databases into Hadoop.
You can use NiFi to do an import as well, using processors such as ExecuteSQL, QueryDatabaseTable, GenerateTableFetch... They all work with JDBC connectors, so depending on if your database supports this, you could opt for this as well.
If you want to get incremental changes, you could use the QueryDatabaseTable processor and use it's Maximum-Value Column property, Matt Burgess has an article explaining how you can put this in place over at https://community.hortonworks.com/articles/51902/incremental-fetch-in-nifi-with-querydatabasetable.html.


text:
Q: Flatten works differently when directly called and when called in a method I'm trying to write a method that will take a string consisting of characters 0, 1, and ?, and return the set of strings represented by the original string, taking ? as a wildcard that can be either a 0 or 1. For example, if the input is "011?0", then the output should be ["01100", "01110"].
I've written the following code:
def zerone str, arr
  qs = str.count("?") - 1
  i = 0
  while i < str.length
    if str[i] != "?"
      arr << str[i]
      i += 1
    else
      arr1 = Array.new(arr)
      arr2 = Array.new(arr)
      arr1 << "1"
      arr2 << "0"
      arr = [arr1, arr2]
      arr.map! {|x| zerone(str[i+1..-1], x)}
      break
    end
  end
 arr.flatten(qs)
end

When I call zerone, I get a flat array:
b = zerone("10???", [])
# => ["1", "0", "1", "1", "1", "1", "0", "1", "1", "0", "1", "0", "1", "0", "1", "1", "0", "1", "0", "0", "1", "0", "0", "1", "1", "1", "0", "0", "1", "0", "1", ...]

If I change the last line so the method returns arr without calling flatten, then I get this:
b = zerone("10????", [])
# => [
  [
    [
      [["1", "0", "1", "1", "1", "1"], ["1", "0", "1", "1", "1", "0"]],
      [["1", "0", "1", "1", "0", "1"], ["1", "0", "1", "1", "0", "0"]]
    ],
    [
      [["1", "0", "1", "0", "1", "1"], ["1", "0", "1", "0", "1", "0"]],
      [["1", "0", "1", "0", "0", "1"], ["1", "0", "1", "0", "0", "0"]]
    ]
  ],
  [
    [
      [["1", "0", "0", "1", "1", "1"], ["1", "0", "0", "1", "1", "0"]],
      [["1", "0", "0", "1", "0", "1"], ["1", "0", "0", "1", "0", "0"]]
    ],
    [
      [["1", "0", "0", "0", "1", "1"], ["1", "0", "0", "0", "1", "0"]],
      [["1", "0", "0", "0", "0", "1"], ["1", "0", "0", "0", "0", "0"]]
    ]
  ]
]
b.flatten(3)
# => [
  ["1", "0", "1", "1", "1", "1"],
  ["1", "0", "1", "1", "1", "0"],
  ["1", "0", "1", "1", "0", "1"],
  ["1", "0", "1", "1", "0", "0"],
  ["1", "0", "1", "0", "1", "1"],
  ["1", "0", "1", "0", "1", "0"],
  ["1", "0", "1", "0", "0", "1"],
  ["1", "0", "1", "0", "0", "0"],
  ["1", "0", "0", "1", "1", "1"],
  ["1", "0", "0", "1", "1", "0"],
  ["1", "0", "0", "1", "0", "1"],
  ["1", "0", "0", "1", "0", "0"],
  ["1", "0", "0", "0", "1", "1"],
  ["1", "0", "0", "0", "1", "0"],
  ["1", "0", "0", "0", "0", "1"],
  ["1", "0", "0", "0", "0", "0"]
]

This is what I wanted. Can anyone tell what's going on?

A: You are calling zerone recursively and qs is updated and different each time. You are not comparing apples to apples with what the method is doing and what you're manually doing in pry (when removing the flatten).


text:
Q: Как импорт видео в группу вк php? Подскажите как реализовать загрузку видео в вк с youtube
Допустим есть список url и вcя инфа о видео в формате json
Каким запросом и т.д. через ВК API загрузить видео в видеозаписи группы (а если можно то и в альбом)
С ВК АПИ не работал так что нужен либо пример либо подробное объяснение, буду благодарен очень!
Заранее спасибо!

A: Все, разобрался, кому нужно:

*

*Сначала получаем токен.

*Далее подключаем библиотеку ВК.

*После чего используем ссылку в виде:
https://api.vk.com/method/video.save?is_private=0&wallpost=0&group_id=&link=https://www.youtube.com/&access_token=

*После чего получаем upload_url и выполняем его!


text:
Q: SAML - Service Provider in Java I have setup Shibboleth IDP and SP. They are configured properly and are working.
I now want to remove the SP and replace it with my own code. i.e.: I want my Java code to function as the SP (routing requests, host metadata and verify SAML assertions) without running shibd.exe and httpd.exe.
Is this possible using OpenSAML? Are there any examples I can use?

A: I did this using Shibboleth ECP extension.

A: ECP profile is indeed a good way to achieve this. If it's all working for you then you should stick to this, I only want to point you to another possible direction.
If you still need to use Web Browser Single Sign On profile you could try integrate your code with Guanxi (src, doc), a Shibboleth SP Java Implementation.
But of course if you only need some lightweight Java Code to access Shibboeleth IdP then ECP is completely fine.

A: Here is the documentation for the openSAML-java .Refer this

https://wiki.shibboleth.net/confluence/display/OpenSAML/OSTwoUserManual


text:
Q: Parse and convert JSON to CSV With the help of Parsing values from a JSON file using Python? I was able to read in the data using:
with open('data/data.json') as data_file:
    data_loaded = json.load(data_file)

However, I can't get to the next step where I want to convert this to a CSV file. Sample code:
import pandas as pd
import json
from io import StringIO
import io
import csv
import sys

sample = {'Table': [{'AA12_Requestor_0': 'John Doe',
   'AA28_Requestor Business Unit_0': 'Manchester United',
   'AA29_Target Remediation Date_0': '2017-07-01',
   'AA29_Exception Lead_0': 'Ji Sung Park',
   'AA29_Level 1 Approver_0': 'Phil Knight',
   'AA29_Date of last WF change_0': '2017-02-12',
   'AA29_Approval Cycles_0': '1',
   'AA29_Level 2 Approver_0': 'Jae In Moon',
   'AA29_Exception Submitted Date_0': '2015-10-12',
   'AA29_Days in Awaiting Assignment_0': '0',
   'AA29_Days in Awaiting Info Sec Review_0': '0',
   'AA29_Days in Awaiting Governance Management Review_0': '2',
   'AA29_Days in Awaiting Level 1 Review - No Level 2 Rev_0': '',
   'AA29_Days from Submitted to Approved_0': '5',
   'AA29_Days from Submitted to Rejected_0': '',
   'AA29_Geography_0': None,
   'AA29_Blood Type': 'Love',
   'AA32_EX: Area_0': None,
   'AA32_Impact_0': None,
   'AA32_Rating_0': None,
   'AA32_Rating (Number)_0': '',
   'AA32_Likelihood_0': None,
   'AA32_Risk Sensitivity_0': None,
   'AA3_Description_0': 'Title: Get your job done | Norm: Be happy.\xa0 Love OS. | Blood type: Z',
   'AA39_Record ID_0': '12345',
   'AA39_Escalation Flag_0': 'No',
   'AA39_Submitted Date_0': '2015-10-15',
   'AA40_ID_0': '123',
   'AF13_Record Workflow State': 'Canceled',
   'FINDING_ID': 12345}]}

There are many more iterations of above dictionary in my JSON file
I've tried:

*

*Referring to http://blog.appliedinformaticsinc.com/how-to-parse-and-convert-json-to-csv-using-python/
json_parsed = json.loads(sample)

Gives me a error saying JSON object must be string not dictionary.
TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

*Attempted to create csvwriter object
csvwriter = csv.writer(sample)

Gives me a error saying:
TypeError: argument 1 must have a "write" method

*I've also read  How can I convert JSON to CSV? but I cannot pass the first step, which is doing a json.loads(sample)

*According to Python - JSON to CSV table? DictWriter sounds interesting. But don't know how I could apply this to my task.

*pd.read_json(sample) is also expecting the string. Gives an error saying
TypeError: Expected String or Unicode

I want all the keys to be the headers (columns) and all the values of the keys in the rows.

A: sample is not a JSON object.
pd.read_json is going to fail.
pd.read_json takes a string that points to a JSON document. You're passing a dict object.
Try passing this:
sample = {'AA12_Requestor_0': 'John Doe',
   'AA28_Requestor Business Unit_0': 'Manchester United',
   'AA29_Target Remediation Date_0': '2017-07-01',
   'AA29_Exception Lead_0': 'Ji Sung Park',
   'AA29_Level 1 Approver_0': 'Phil Knight',
   'AA29_Date of last WF change_0': '2017-02-12',
   'AA29_Approval Cycles_0': '1',
   'AA29_Level 2 Approver_0': 'Jae In Moon',
   'AA29_Exception Submitted Date_0': '2015-10-12',
   'AA29_Days in Awaiting Assignment_0': '0',
   'AA29_Days in Awaiting Info Sec Review_0': '0',
   'AA29_Days in Awaiting Governance Management Review_0': '2',
   'AA29_Days in Awaiting Level 1 Review - No Level 2 Rev_0': '',
   'AA29_Days from Submitted to Approved_0': '5',
   'AA29_Days from Submitted to Rejected_0': '',
   'AA29_Geography_0': None,
   'AA29_Blood Type': 'Love',
   'AA32_EX: Area_0': None,
   'AA32_Impact_0': None,
   'AA32_Rating_0': None,
   'AA32_Rating (Number)_0': '',
   'AA32_Likelihood_0': None,
   'AA32_Risk Sensitivity_0': None,
   'AA3_Description_0': 'Title: Get your job done | Norm: Be happy.\xa0 Love OS. | Blood type: Z',
   'AA39_Record ID_0': '12345',
   'AA39_Escalation Flag_0': 'No',
   'AA39_Submitted Date_0': '2015-10-15',
   'AA40_ID_0': '123',
   'AF13_Record Workflow State': 'Canceled',
   'FINDING_ID': 12345}

data = pd.DataFrame(sample, index=[0]) # Only one row so index has a length of 1

From there you can do ```data.to_csv("path/to/out/file.csv")`` to pass out the JSON object to a csv.


text:
Q: WPF, UWP and Hardware I just got back from Microsoft Build 2018 where they announced .NET Core 3 support for WPF applications. This is great because I can finally start using some of those cool fluent design things that are available for UWP.  The only problem is, it's not getting released until next year.
I started looking into converting my app to a UWP app (because I'm impatient) but I'm running into some challenges.  Mainly hardware.  Talking with a few guys at Build, they made it seem like it was possible to write UWP apps that connect to low-level Win32 drivers for communicating with hardware (HID printers, card readers, bar code scanners, etc).  I'm not having any luck finding information about this.  Just to be clear, this is not an app I want to release to the Windows Store. This is a kiosk app that runs on our own hardware.
How does one access Win32 APIs for hardware integration in UWP?

A: Your best bet is likely to use P/Invoke, which is technology designed to allow .NET code to call unmanaged code. Assuming that your hardware is accessed through Win32 APIs in a DLL, this may be your best option.
The pinvoke.net Web site provides specific examples of the .NET code needed to call a specific Win32 API. Perhaps those examples can help you get started.

A: UWP app written in C++/CX has access to the Win32 and COM APIs that are part of the Universal Windows Platform (UWP).
The APIs in Win32 and COM APIs for UWP apps is only for C++, you can not use the C# to access it directly. Please see Visual C++ Language Reference (C++/CX) to get more details about C++/CX.
But, you can create a Windows Runtime component in C++/CX, then call it from C#, you can see the Walkthrough here:
https://learn.microsoft.com/en-us/windows/uwp/winrt-components/walkthrough-creating-a-basic-windows-runtime-component-in-cpp-and-calling-it-from-javascript-or-csharp


text:
Q: Extract part of a text with selenium IDE and put it into variable Could somebody tell me which command should I use to extract only the number(694575) from the text using Selenium Ide and to put it into a variable for further usage.
Here is the div with the text:

Edit Exhibition Centre - 694575, Exhibition Center1

May be commands like storeText,storeEval should work in this case ,but the part with the pasrsing is a mistery for me.

A: I have solution, tricky 1
store  | Edit Exhibition Centre - 694575, Exhibition Center1 | string
store  | 1 | delimiter
store  | javascript{storedVars['string'].split('- ')[storedVars['delimiter']]} | test
store  | 0 | delimiter1
store  | javascript{storedVars['test'].split(',')[storedVars['delimiter1']]} | output
echo   | ${output}

Try this 1, and let me know whether its working for you

A: I Have an easy answer to this  question. Try this code it will work.

    store
    Edit Exhibition Centre - 694575, Exhibition Center1
    string

    store
    javascript{storedVars['string'].substring(24)}
    string

    echo
    ${string}

    store
    javascript{storedVars['string'].substring(0,7)}
    string

    echo
    ${string}


text:
Q: keyCode and which are deprecated - so why is that not working? According to MDN Web Docs KeyboardEvent and Google Updates KeyboardEvent key and code are implemented while keyCode and which are deprecated.
With that in mind I should be able to dispatch keydown event as below:
document.dispatchEvent(
    new KeyboardEvent("keydown", {
        key: 'K',
        code: 'KeyK',
        shiftKey: false,
        ctrlKey: false,
        metaKey: false
    })
);

Unfortunately it doesn't work whilst if I add keyCode additionally this script works perfectly. Object with keyCode:
document.dispatchEvent(
    new KeyboardEvent("keydown", {
        key: 'K',
        code: 'KeyK',
        keyCode: 75,
        shiftKey: false,
        ctrlKey: false,
        metaKey: false
    })
);

Am I missing something? keyCode and which are deprecated so it should be possible to create working event without these elements. I cannot find anywhere answer for that.
I am using current version of Google Chrome (87). I test this script by sending k key to YouTube for play/pause video.

A: The "deprecated" status in the documentation is telling you that you shouldn't rely on those attributes being present in events which you receive, because the browser developers are planning to stop including them in events which they create.
However, in this case, you are simulating the part of the code that the browser would normally perform, in creating the event. Neither you nor the browser has any way to know what the code receiving that event is going to look for.
If you leave out the deprecated attributes, you are emulating a future browser, and the YouTube site you're testing on might not currently be ready to work with that future browser. You are better off setting all the attributes a current browser would set for that event.
Note that the developers of YouTube, while ultimately employed by the same company as the developers of Chrome, likely have very little connection. They will be updating their code to follow current best practices on a regular basis like any well-run development team, but that takes time, and has to be prioritised amongst everything else they're working on.


text:
Q: jquery insert div right inside a form If i have the code below and i want to insert a div with jquery as the first element inside the form tag what is the best way to do that?
<form>
    //i want to insert a div here with jquery
    ...
    <input>...</input>
    ...

    ...
    <input>...</input>
    ...

    ...
    <input>...</input>
    ...
</form>

A: $('#formID').prepend('
DIV CONTENT
');


text:
Q: How can I test a pure function does not exports from the other source with jest  // add.js
 const add = (a, b) => a +b;

How can I test the add function? I want to test add function logic. But I don't know how to test it. Because the function is not exported. I want this function to be called only on add.js.
Do I have to export this add function for testing with jest?

A: There's a lot of debate on this topic. If your add function is not exported, it is considered "private/internal" to your module and is not part of the public API. Many people argue that you should only test your public API, others argue that you will need to export your private functions if you wish to test them. Both sides make great points and it boils down to a matter of preference.
My preferred technique is to put these types of helper functions in a separate module which is tested separately and imported wherever you need it. These methods become "public", but in practice I have found that it doesn't hurt anything and you might actually end up reusing the code somewhere else without needing to refactor anything.
You can also try exporting your methods but mark them as @private using the popular JSDoc syntax. This is merely a hint to developers that they shouldn't import or use the method, and some editors/IDEs might even hide the method from intellisense.
/** @private */
export const add = (a, b) => a + b;

At the end of the day you can't really test private (non-exported) methods without using some tool like rewire. I used to use rewire a lot, however, I don't recommend it any more as it makes your tests more complex and brittle. I have found that good tests are simple and easy to read, which is not the case when you use things like rewire. Don't get caught in the trap of "developers shouldn't be able to see or use this private function" - it's a toxic way to think about your code IMO.


text:
Q: How to configure the default ObjectMapper used by Spring to use a custom deserializer when deserializing spring classes I want to use my own custom deserializer in Spring's default ObjectMapper whenever I have a class of type OAuth2AccessToken. The interface is annotated with
JsonDeserialize(using = OAuth2AccessTokenJackson2Deserializer.class)

and this is what it's using at the moment to deserialize but I want to use my own.
So far I have created my own custom deserializer
public class MyCustomDeserializer extends StdDeserializer<OAuth2AccessToken> {

    public MyCustomDeserializer() {
        super(OAuth2AccessToken.class);
    }

    @Override
    public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        String tokenValue = null;
        String tokenType = null;
        String refreshToken = null;
        Long expiresIn = null;
        Set<String> scope = null;
        Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();

        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String name = jp.getCurrentName();
            jp.nextToken();

            if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) {
                tokenValue = jp.getText();
            } else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) {
                tokenType = jp.getText();
            } else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) {
                refreshToken = jp.getText();
            } else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
                try {
                    expiresIn = jp.getLongValue();
                } catch (JsonParseException e) {
                    expiresIn = Long.valueOf(jp.getText());
                }
            } else if (OAuth2AccessToken.SCOPE.equals(name)) {
                scope = parseScope(jp);
            } else {
                additionalInformation.put(name, jp.readValueAs(Object.class));
            }
        }

        DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue);
        accessToken.setTokenType(tokenType);
        if (expiresIn != null) {
            accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
        }
        if (refreshToken != null) {
            accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
        }
        accessToken.setScope(scope);
        accessToken.setAdditionalInformation(additionalInformation);

        return accessToken;
    }

    private Set<String> parseScope(JsonParser jp) throws JsonParseException, IOException {
        Set<String> scope;
        if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
            scope = new TreeSet<String>();
            while (jp.nextToken() != JsonToken.END_ARRAY) {
                scope.add(jp.getValueAsString());
            }
        } else {
            String text = jp.getText();
            scope = OAuth2Utils.parseParameterList(text);
        }
        return scope;
    }
}

My own custom class by extending DefaultOAuth2AccessToken
@com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = MyCustomDeserializer.class)
public class MyCustomOAuth2AccessToken extends DefaultOAuth2AccessToken {

    public MyCustomOAuth2AccessToken(String value) {
        super(value);
    }

    public MyCustomOAuth2AccessToken(OAuth2AccessToken accessToken) {
        super(accessToken);
    }
}

and at the moment I am registering a bean of type Jackson2ObjectMapperBuilderCustomizer like this
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomDeserialization() {
    return new Jackson2ObjectMapperBuilderCustomizer() {

        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            SimpleModule m = new SimpleModule();
            m.addDeserializer(OAuth2AccessToken.class, new MyCustomDeserializer());
            jacksonObjectMapperBuilder.modules(m);
        }
    };
}

@Bean
public OAuth2ClientContext getOAuth2ClientContext() {
    DefaultOAuth2ClientContext defaultOAuth2ClientContext = new DefaultOAuth2ClientContext();
    defaultOAuth2ClientContext.setAccessToken(new MyCustomOAuth2AccessToken("test"));
    return defaultOAuth2ClientContext;
}

A: You can simply annotate your deserialization classes with @JsonComponent.
The annotation allows us to expose an annotated class to be a Jackson serializer and/or deserializer without the need to add it to the ObjectMapper manually.

A: To configure ObjectMapper globally just create a bean of type Jackson2ObjectMapperBuilder and use deserializerByType method :
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
  return new Jackson2ObjectMapperBuilder()
           .deserializerByType(OAuth2AccessToken.class, new MyCustomDeserializer());
}

Reference of configuring ObjectMapper in SpringBoot can be found here.


text:
Q: C++ strange behaviour with long doubles and optimized flag I'm developing a program in C++ with Visual Studio 2008.
Recently i started to test my program in release mode, and i started to get some weird errors in relations to some calculations, which always return 0 instead of the correct value (that in debug mode were correctly calculated).
I have done some research and finally i identify (or at least i believe) what the problem is. If i disable the optimization flags (/Od) when i'm in release mode, the programs behaves well like usual in debug mode. But, because i really need the speed of this optimizations (at least with the O2 flag), i started to test a lot of things in order to get correct results while keep a good execution time. I set the floating point model to pf:strict option, but still get the same errors (my long doubles values still are 0).
Tracking this odd behaviour i get to this example code (which is inside a loop) (demand is a long double var):
long double demand = 0;
vector<int> someArray = getSomeArray();
for (int i = 0; i < someArray.size(); i++) {

    if (someCondition(someArray[i])) {

        int someId = getSomeId(someArray[i]);
        long double d = getSomeLongDouble(someArray[i]); <--- correctly setted!
        demand = demand + d; <---- d=0.018182000000000000 demand = 0
        someLogic(someId); <--- at this point, demand is still 0!!!!
    }

}

No matter what, demand is always 0, even when i insert a breakpoint and manually check that the value of the variable d is > 0.
Please, i really need the boost of speed the optimization flags are giving, but i don't get how to keep this particular calculation correct...
Any help would be greatly appreciated :) And excuse my english!!


text:
Q: Is an automorphism a function or a group? this is my first time on the Stack Exchange so I apologize if I went about asking this improperly! I was working on a problem set that asked to compute Aut(S3). In class we've been thinking about automorphisms as a function that maps elements of one group to another. However it seems like an automorphism can be better thought of as a subgroup of S3. Could someone provide clarity about what it means to compute/find Aut(S3)?

A: The automorphism group $\operatorname{Aut} S_3$ is the group of automorphisms on $S_3$. So it's a group, but its elements are automorphisms of $S_3$,
$$\operatorname{Aut} S_3 = \{σ \colon S_3 → S_3;~σ~\text{is a group automorphism} \}.$$
Keep in mind that automorphisms are meant to be maps from a group to itself – and not to another group. It stems from the greek word αὐτóς, meaning "self" or "same", so its something that shapes (grk. "μορφóω") the group into itself, the same group.  Automobiles are things that movable (lat. "mobilis") by themselves. Most terms in mathematics actually have meaning.

A: I think   this

In class we've been thinking about automorphisms as a function that
maps elements of one group to another.

is not quite right. Homomorphisms are functions that map the elements of one group to another (and preserve the group multiplication).
When the domain and codomain of a homomorphism are the same group and the homomorphism is bijective (so an isomorphism) then you call that homomorphism an automorphism.
If you have a group $G$ (say, $S_3$) then you can consider all the automorphisms of that group. The set of those automorphisms is itself a group (under functional composition) called the automorphism group of $G$.
You have been asked to find that group - start by listing its elements.
.


text:
Q: What are the comparison operators in case statement formula? Working with Crystal Reports 2016.  My select case statement has 3 possible values, 0 through 2. I want to assign text labels for them in a chart. Crystal Reports says I can't use = as a comparison operator, which is weird because this page says it is a comparison operator (as opposed to an assignment operator). What operator should I use?
This code check out according to the formula Workshop:
select ({CRV_AttributeLog.AnalogValue})
  case is < 1: "Offline"
  case is <= 1: "Partially Online"
  case is > 1: "Online"
  default: "Unknown";

This is what i want to do:
select ({CRV_AttributeLog.AnalogValue})
  case is = 0: "Offline"
  case is = 1: "Partially Online"
  case is = 2: "Online"
  default: "Unknown";

== also does not work

A: You do not need the 'is =' portion in the select statement .. see below
select ({CRV_AttributeLog.AnalogValue})
  case 0: "Offline"
  case 1: "Partially Online"
  case 2: "Online"
  default: "Unknown";