text:
Q: Calculate how much of an asset can be purchased with a exponential model for value This is for a personal project of mine, and I am having a hard time conceptualizing this problem.
So let's say that I was able to quantify the price of an asset as the following:
$$P = (3.5 \cdot Q)^{1.3}$$
$P$ represents the price of the asset (in USD for this example's sake), $Q$ represents the current quantity of the asset that has been purchased.
So then let's say that I want to purchase $100 worth of the asset, and currently 5 assets have already been purchased, making the value of the asset currently be at:
$$(3.5 \cdot 5)^{1.3} \approx 41.30$$
But of course, me buying the asset is increasing the price of it, so I can't simply do something like this to get how much of the asset can be purchased:
$$Q = \frac{100}{41.30}$$
Which makes me think that maybe some calculus is required here? I took calculus in college but if I could get some help in explaining this in mathematical terms to get a start on it that would be very helpful.

A: We have $P = (3.5Q)^{1.3}$, and we want to find how many assets past $5$ we can purchase with $\$100$.  If we assume that fractional assets aren't possible, i.e. the number of assets has to be an integer, and that the price changes after each purchase of a single asset, then we can proceed one purchase at a time until we've run out of money:
\begin{array}{c|c|c|c}
\text{\$ Available} & \text{Current Assets} & \text{Current Price} & \text{\$ Remaining}\\
\hline
\$100 & 5 & (3.5(5))^{1.3} \approx \$41.3 & \$100 - \$41.3 = \$58.70\\
\hline
\$58.7 & 6 & (3.5(6))^{1.3}\approx \$52.35 & \$58.70 - \$52.35 = \$6.35\\
\hline
\$6.35 & 7 & (3.5(7))^{1.3} \approx \$63.96 & \$6.35 - \$63.96 = \color{red}{-\$57.61}
\end{array}
This tells us that the most we can purchase is two additional assets.
If, however, we want to consider the possibility that we can purchase infinitesimally small portions at a time, then we can proceed as follows.
Disclaimer: It's possible I'm 'reinventing the wheel' here, because while I've never seen this particular scenario, it's likely not original, so going through what I'm about to do may be overkill.
If we begin with $5$ assets, and only purchase $1$ asset at a time, then the total amount of money spent on $3$ additional assets can be expressed as follows:
$$(3.5(5))^{1.3} + (3.5(6))^{1.3} + (3.5(7))^{1.3}$$
If we only purchase $0.5$ of an asset at a time, the total amount of money spent on $3$ additional assets can be expressed as:
$$0.5(3.5(5))^{1.3} + 0.5(3.5(5.5))^{1.3} + \dotsb + 0.5(3.5(7))^{1.3} + 0.5(3.5(7.5))^{1.3}$$
We can rewrite this expression more compactly as
$$(3.5)^{1.3}\sum_{k = 0}^{5}(5+0.5k)^{1.3}(0.5).$$
Note here that we have $5$ as the upper limit on the sum because when purchasing $3$ additional assets, $0.5$ at a time, we need to calculate the price a total of $3/0.5 = 6$ times, but since the first calculation is based on the original price, we need the sum to stop at $\frac{3}{0.5} - 1 = 5$.
In general, then, for a purchase of $x$ additional assets, a fraction of $\Delta x$ at a time, our total expenses can be expressed as
$$(3.5)^{1.3}\sum_{k = 0}^{\frac{x}{\Delta x} - 1}(5+k\Delta x)^{1.3}\Delta x.$$
Now, shifting the indices by $n = k+1$, we get the expression
$$(3.5)^{1.3}\sum_{n = 1}^{\frac{x}{\Delta x}}(5+(n-1)\Delta x)^{1.3}\Delta x.$$
We can think of this sum as a Riemann sum, where the interval $[0,x]$ has been partitioned into $x/\Delta x$ sub-intervals, using the points $x_n = (n-1)\Delta x$ in each sub-interval (these corresponding to the left endpoints of each sub-interval here).  So, for the function $f(x) = (5+x)^{1.3}$, our expression looks like
$$(3.5)^{1.3}\sum_{n = 1}^{\frac{x}{\Delta x}}f(x_{n})\Delta x.$$  Taking the limit as $\Delta x \to 0$, this converges to the limit $$(3.5)^{1.3}\int_{0}^{x}(5+t)^{1.3}\,dt.$$
Notice, however, that purchasing fractional assets continuously in this manner is actually more expensive than purchasing them one at a time as we initially did, because the price is constantly being recalculated.  For instance, we found initially that it would cost us $\$93.65$ to purchase two assets one at a time.  Using the integral, however, we would calculate $$(3.5)^{1.3}\int_{0}^{2}(5+t)^{1.3}\,dt \approx \$104.88.$$


text:
Q: max-height for read more is not respecting 0px from css I am trying to write a read more. It is working for the most part, except that the Divs that are supposed to be completely closed, are still showing the first line of text.
I made a codepen
https://codepen.io/justinblayney/pen/JjpZeJK
It is a bit complicated, in mobile view 5  divs need to be hidden behind a read more toggle, it desktop view they are always visible with a completely different layout which I use css grid to accomplish (which is why i don't wrap them into one div).
if you view my link above, make sure you are under 768px you will see at the bottom
Read More
Device compatibility
Country available
Year established
Licensed in
Support
Only "Read more" should be showing, the rest should open on the toggle, but instead the title(strong) is showing and only the content(span) is hidden. I want both and title and content hidden until it toggles.
They all have the code below, but it is not 0px
max-height: 0px;
overflow: hidden;
transition: max-height 0.2s ease-out;

A: The issue is that overflow: hidden isn't hiding your padding - you need to remove the padding from your divs when hidden, and add it back in when they are rendered
You can do this like so (ln 121 of your demo):
&__desktop, &__mobile, &__payout, &__currency, &__banking, &__platforms, &__countries, &__established, &__licensed, &__support, &__readmore {
        //...

        &.active {
                padding: 0px 40px 20px 40px;
        }

        // ....
}

Aside: if you want to simplify your JS, here's a starting point:
const accordionEls = document.getElementsByClassName("accordion");

// add an event listener to each element, using a named function definition
Array.from(accordionEls).map(element => {
  element.addEventListener("click", toggleVisibility)
});

function toggleVisibility(event) {
  // get the element that the event was attached to out of the event object
  const { currentTarget } = event;
  // generate .review_page__ classnames
  const classNames = [
    "platforms",
    "countries",
    "licensed",
    "support",
    "established"
  ].map(name => `.review_page__${name}`);
  // get the elements with those class names, filtering any null
  // values out of the list
  const toggleElements = classNames
    .map(className => document.querySelector(className))
    .filter(Boolean);

  // set the .active class on the read more button
  currentTarget.classList.toggle("active");

  // loop over each element, switching its max height
  toggleElements.map(el => {
    const currentMaxHeight = el.style.maxHeight;
    const maxHeight = currentMaxHeight ? null : `${el.scrollHeight}px`;

    el.style.maxHeight = maxHeight;
  });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to trigger MathJax? I included MathJax with the script

This automatically replaces all math codes with the formatted tags.

*

*How can I trigger MathJax by a javascript click only, instead of upon load.

*How can I tell MathJax to put the formatted element at the end of the page instead of replacing the original code?

A: 1. How can I trigger MathJax by a javascript click only, instead of upon load.
From docs:
skipStartupTypeset: false

Normally MathJax will typeset the mathematics on the page as soon as the page is loaded. If you want to delay that process, in which case you will need to call MathJax.Hub.Typeset() yourself by hand, set this value to true.

Starting typeset

The MathJax.Hub.Typeset() command also accepts a parameter that is a
  DOM element whose content is to be typeset. That could be a paragraph,
  or a  element, or even a MathJax math  tag. It could also
  be the DOM id of such an object, in which case, MathJax will look up
  the DOM element for you. So
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"MathExample"]);

would typeset the mathematics contained in the element whose id is
  MathExample. This is equivalent to
var math = document.getElementById("MathExample");
MathJax.Hub.Queue(["Typeset",MathJax.Hub,math]);

If no element or element id is provided, the whole document is
  typeset.

MathJax.Hub.Config({
    skipStartupTypeset: true,
    extensions: ["tex2jax.js", "TeX/AMSmath.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
        inlineMath: [["$", "$"]],
        processEscapes: true
    }
});

function startTypeSetting() {
  var HUB = MathJax.Hub;
  HUB.Queue(["Typeset", HUB, "render-me"]);
}

$a+b=c$

<button onClick="startTypeSetting()">Start typesetting</button>

2. How can I tell MathJax to put the formatted element at the end of the page instead of replacing the original code?
It would be better to know what are you trying to achieve, but here are 2 ways to skip typesetting for certain tags or classes, from tex2jax preprocessors configs:
MathJax.Hub.Config({
     tex2jax: {
         skipTags: ["script","noscript","style","textarea","pre","code"],
         ignoreClass: "tex2jax_ignore_1|tex2jax_ignore_2"
    }
}

You can copy the content of element you want to render to another element and start typesetting there:

MathJax.Hub.Config({
    skipStartupTypeset: true,
    extensions: ["tex2jax.js", "TeX/AMSmath.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
        inlineMath: [["$", "$"]],
        processEscapes: true
    }
});

function startTypeSetting() {
  //copy content from '#code-to-render' to '#render-point'
  var text = $('#code-to-render').val()
  $('#render-point').text(text)

  //Start typesetting
  var HUB = MathJax.Hub;
  HUB.Queue(["Typeset", HUB, "render-point"]);
}

<textarea id="code-to-render">$a+b=c$</textarea>

<button onClick="startTypeSetting()">Start typesetting</button>

A: For MathJax 3, it is:
MathJax.typeset()


text:
Q: Zurb Foundation Mobile Menu Does Not Work with Wordpress I tried a lot, but I can't figure out, why Wordpress does not let my Menu work.
In the static version everything works perfectly fine. But implemented in Wordpress, for some reason, the files are loaded but not executed. Without an error message.
I uploaded my local theme and the static version here:
wordpresstest <-- Not working dynamic Wordpress version
wordpresstest2 <-- Working static version
I read somewhere, that wordpress, loads jQuery in noConflict mode, and that I should modify my foundation.js in a way, that it is compatible with wordpress. But I have no idea, what exactly to do right now.

A: add this js
jQuery(".has-dropdown").hover(function(){
   jquery(".top-bar-section .dropdown").css("display","block");
});


text:
Q: How to access a child of a widget in Kivy? I'm a newbie using Kivy. I defined a FloatLayout object with a Button child. Is there anyway to access the Button on_press event and background images?
Here is the code I tried:
<Tecla2@FloatLayout>:
    Button:
        size_hint: (0.95,1.05)
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        text: ""

Tecla2:
    self.Button.background_normal: "images/tecla_normal1.png"
    self.Button.background_down: "images/tecla_down1.png"
    self.Button.on_press: if(len(texto.text)<text_len): texto.text+="1"

An alternate solution (the one I currently implemented) is defining a Button and using a new FloatLayout for every instance, but it lacks elegance:
<Tecla@Button>:
    size_hint: (0.95,1.05)
    pos_hint: {"center_x": 0.5, "center_y": 0.5}
    text: ""

FloatLayout:
    Tecla:
        background_normal: "images/tecla_normal2.png"
        background_down: "images/tecla_down2.png"
        on_press: if(len(texto.text)<text_len): texto.text+="2"

Is there anyway to do this using kivy language? This is the simplest example, but I've already needed to do the same in other situations.

A:
Is there anyway to access the Button on_press event and background images?

Well, you can use the relevant properties of the button you create:
<Tecla2@FloatLayout>:
    Button:
        size_hint: (0.95,1.05)
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        text: ""
        background_normal: "images/tecla_normal1.png"
        background_down: "images/tecla_down1.png"
        on_press: if(len(texto.text)<text_len): texto.text+="1"

Maybe there is something else you're looking for?


text:
Q: How to properly display the contents of the utmp,wtmp, and btmp files? How can I display the /var/run/utmp ,/var/log/wtmp ,/var/log/btmp by using cat?
While I am trying to display them , I am getting some other characters too.
Here is the output I get when trying to read the files:
jai@frank-Jai:~$ cat /var/run/utmp
~~~reboot3.8.0-26-genericf�Q%p  2~~~runlevel3.8.0-26-genericf�Q
�   �tty44LOGIN�f�Q�tty55LOGIN�f�Q�tty22LOGIN�f�Q�tty33LOGIN�f�Q�tty66LOGIN�f�Q�tty11LOGIN�k�Qtty7:0jai:0y�Q
                                                       ��pts/0/0jai:0.0�{�QFQjai@frank-Jai:~$ cat /var/log/wtmp
~~~reboot3.8.0-19-generic��Q�b
2~~~runlevel3.8.0-19-generic��Q�c
*tty44LOGIN*��Q0tty55LOGIN0��Q:tty22LOGIN:��Q;tty33LOGIN;��Q=tty66LOGIN=��Q"tty11LOGIN"��Q�pts/1/1jai:0.0��Q�D       pts/1/1jai��Q���   pts/1/1jai:0.0t��Q��    pts/2/2jai:0.0���Q
�   pts/3/3jai:0.0`��Qpts/3/3jaib��Qpts/1/1jai"��Q
                                                        pts/2/2jai"��Q62~~~ru*tty44*;��Q�0tty550;��Q�:tty22:;��Q�;tty33;;��QM=tty66=;��Q�
                                                                       "tty11";��Ql,~~~shutdown3.8.0-19-genericH��Qz�~~~reboot3.8.0-26-generic���Q-�2~~~runlevel3.8.0-26-generic���Q�ctty44LOGINc���Qjtty55LOGINj���Qutty22LOGINu���Qvtty33LOGINv���Qytty66LOGINy���Q?tty11LOGIN?���Q02~~~runlevel3.8.0-26-generic���Q.
                 ctty44c���Qjtty55j���Qutty22u���Qvtty33v���Qytty66y���Q?tty11?���Q�~~~shutdown3.8.0-26-generic���Q�~~~reboot3.8.0-26-genericʩ�stty44LOGINsʩ�Qztty55LOGINzʩ�Q�tty22LOGIN�˩�Qtty33LOGIN˩�Q�tty66LOGIN�˩�QCtty11LOGINC˩�Qpts/0/0jai:0.0B��Qp�
                                            pts/1/1jai:0.0��QOpts/1/1jai��Q(C
                                                                             ptspts/1/1jai��Q"pts/0/0jai;�Q�
stty44s�A�Q��ztty55z�A�Q��i�tty22��A�Q��ntty33�A�QZ�26-ge�tty66��A�Qmn
Ctty11C�A�Qz
~~~shutdown3.8.0-26-generic�A�Q
                                �~~~reboot3.8.0-26-generic e�Q�2~~~runlevel3.8.0-26-generic e�Q�iMtty44LOGINM e�QStty55LOGINS e�Q]tty22LOGIN] e�Q^tty33LOGIN^ e�Q`tty66LOGIN` e�Q�tty11LOGIN�#e�QL
pts/0/0jai:0.0l�Q�#
pts/0/0jai:0.0:t�Q#;pts/0/0jai߂�QO|02~~~runlevel3.8.0-26-generic߂�Qu�Mtty44M߂�QStty55S߂�Q]tty22]߂�Q^tty33^߂�Q`tty66`߂�Q�    �tty11�߂�Q�D    ~~~shutdown3.8.0-26-generic���Q
                        ~~~reboot3.8.0-26-generic���Q�2~~~runlevel3.8.0-26-generic���Q[�ktty44LOGINk���Qqtty55LOGINq���Q{tty22LOGIN{���Q|tty33LOpts/2/2jaiL��Q��62~~~runlevel3.8.0-26-genericL��Q��ktty44kL��Qqtty55qL��Q{tty22{L��QY   |tty33|L��Q@
                               �tty66�L��Q� �tty11�L��Q�M   ~~~shutdown3.8.utty44LOGINuW��Q}tty55LOGIN}W��Qtty22LOGINW��Q�tty33LOGIN�W��Q�tty66pts/0/0jai:0.0���Qpts/0/0jaiv��Ql�02~~~runlevel3.8.0-26-genericv��Q�butty44uv��Q1
    }tty55}v��Q4
                tty22v��Q*

                         �tty33�v��Q&
                                      �tty66�v��Q3
                                                    �tty11�v��Q�
                                                                   ~~~shutdown3.8.0-26-generic���QN%~~~reboot3.8.0-26-generic���Q
y2~~~runlevel3.8.0-26-generic���Q��tty44LOGIN���Q�tty55LOGIN����Q�tty22LOGIN����Q�tty33LOGIN����Q�tty66LOGIN����Q�tty11LOGIN����Q02~~~runleveltty44]��Q��tty55�]��Q��tty22�]��Q��tty33�]��Q��tty66�]��QE�tty11�]��Q��~~~shutdown3.8.0-26-genericj��Q�Q~~~reboot3.8.0-26-genericC��QQ�
                                                                    2~~~runleveltty44LOGINlC��Qptty55LOGINpC��Qvtty22LOGINvC��Qwtty33LOGINwD��Qytty66LOGINyD��Q�tty11LOGIN�E��Q62~~~runlevel3.8.0-26-generice��Qltty44lf��Q
)ptty55pf��Q4vtty22vf��Q�7wtty33wf��Q�=ytty66yf��Q�B�tty11�f��Q�^~~~shutdown3.8.0-26-generics��Q
~~~reboot3.8.0-26-genericZ?�Qغ2~~~runlevel3.8.0-26-genericZ?�Q��tty44LOGINZ?�Q�tty55LOGIN�Z?�Q�tty22LOGIN�Z?�Q�tty33LOGIN�Z?�Q�tty66LOGIN�Z?�Q�tty11LOGIN�[?�Q62~~~runlevel3.8.0-26-generich?�QCtty44h?�Q �tty55�h?�Qm�tty22�h?�Q9�tty33�h?�Q��tty66�h?�Q�tty11�h?�Q��~~~shutdown3.8.0-26-generick?�Q5~~~reboot3.8.0-26-generic��Q�>2~~~runlevel3.8.0-26-generic��Q�4utty44LOGINu��Q{tty55LOGIN{��Q�tty22LOGIN���Q�tty33LOGIN���Q�tty66LOGIN���Q�tty11LOGIN���Q02~~~runlevel3.8.0-26-generic���Q�utty44u���Q�{tty55{���Q��tty22����Q�tty33����Q��tty66����Q�tty11����Q"~~~shutdown3.8.0-26-generic���Q(
                   ~~~reboot3.8.0-26-generic���Q=2~~~runlevel3.8.0-26-generic���Q�;etty44LOGINe���Qjtty55LOGINj���Qttty22LOGINt���Qztty33LOGINz���Q�tty66LOGIN����Q�tty11LOGIN����Q�pts/0/0jai:0.0[j�QE5
                                                            pts/0/0jai�m�Q�pts/0/0jai:0.0�m�Q�pts/0/0jain�Q��62~~~runlevel3.8.0-26-generic0n�Q��etty44e0n�Qjtty55j0n�Q�       ttty22t0n�Q
                                    �  ztty33z0n�Q'� �tty66�0n�Q@� �tty11�0n�Qu�    ~~~shutdown3.8.0-26-generic>n�Q��~~~reboot3.8.0-26-generic�+�Q�S2~~~runlevel3.8.0-26-generic�+�Q�{tty44LOGIN{�+�Q�tty55LOGIN��+�Q�tty22LOGIN��+�Q�tty33LOGIN��+�Q�tty66LOGIN��+�Q�tty11LOGIN��+�Qk  pts/0/0jai:0.0<,�Qpts/0/0jaih��Qv�
                  62~~~runlevel3.8.0-26-generic��Q?�{tty44{��QT
�tty55���Q@U
              �tty22���QPW
                            �tty33���QIY
                                          �tty66���QV[
                                                        �tty11���Q�j
                                                                       ~~~shutdown3.8.0-26-generic�Q~~~reboot3.8.0-26-generic�_�Q��2~~~runlevel3.8.0-26-generic�_�Q9bhtty44LOGINh�_�Qltty55LOGINl�_�Qtty22LOGIN�_�Q�tty33LOGIN��_�Q�tty66LOGIN��_�Q�tty11LOGIN��_�Q02~~~runlevel3.8.0-26-generic�_�Q@htty44h�_�Q�ltty55l�_�QJtty22�_�Q+�tty33��_�Q��tty66��_�Q��tty11��_Y~~~shutdown3.8.0-26-generic�_�Qc�~~~reboot3.8.0-26-generic���Q�D2~~~runlevel3.8.0-26-generic���Q7yktty44LOGINk���Qstty55LOGINs���Q�tty22LOGIN����Q�tty33LOGIN����Q�tty66LOGIN����Q�tty11LOGIN����QG
                                                            pts/0/0jai:0.0�-�Q��ktty44k&D�Q�stty55s&D�Q��tty22�&D�Q��tty33�&D�Q<�tty66�&D�Q4�tty11�&D�Q`e~~~shutdown3.8.0-26-generic)D�Q�m
~~~reboot3.8.0-26-generic�Q&�2~~~runlevel3.8.0-26-generic�Q�4ktty44LOGINk�Qptty55LOGINp�Q{tty22LOGIN{�Q|tty33LOGIN|�Q~tty66LOGIN~�Q�tty11LOGIN��h�Q02~~~runlevel3.8.0-26-generic�k�Q�1
                                            ktty44k�k�Q�ptty55p�k�Q�{tty22{�k�Q�|tty33|�k�Q~tty66~�k�Q�tty11��k�Q�~~~shutdown3.8.0-26-generic�k�Q�~~~reboot3.8.0-26-generic���Q|2~~~runlevel3.8.0-26-generic���Q3�tty44LOGIN����Qtty55LOGIN���Q�tty22LOGIN����Q�tty33LOGIN����Q�tty66LOGIN����Q�tty11LOGIN����Qo
�tty44����Qtty55����tty22����Q��tty33����Q��tty66����Q��tty11����Q��~~~shutdown3.8.0-26-generic���Qm�
                                 ~~~reboot3.8.0-26-generic�Q�2~~~runlevel3.8.0-26-generic�Q*�ptty44LOGINp�Qvtty55LOGINv�Q�tty22LOGIN��Q�tty33LOG�tty44LOGIN�Qv�Q�tty55LOGIN�Qv�Q�tty22LOGIN�Qv�Q�tty33LOGIN�Qv�Q�t0#pts/4/4jai:0.0��Qt`�)pts/1/1root:0.0%��Qpts/1/1root~��Q'1pts/4/4jai���Q�02�tty44�i��Q?��tty55�i��Q�tty22�i��Q�tty33�i��Q�tty66�i��Q�tty11�i��Q~~~shutdown3.8.0-26-genericy��Q��~~~reboot3.8.0-26-generic���Q<2~~~runlevel3.8.0-26-generic���Q�Yotty44LOGINo���Qttty55LOGINt���Qztty22LOGINz���Q{tty33LOGIN{���Qtty66LOGIN���Q�tty11LOGIN����Q�
                                                          pts/0/0jai:0.0P(�QDhpts/0/0jaiN*�Q��
              02~~~runlevel3.8.0-26-generic7>�Q֯
                                               otty44o8>�Q�ttty55t8>�Q�ztty22z8>�Q�{tty33{8>�Q5tty668>�Q7�tty11�8>�Qk�~~~shutdown3.8.0-26-genericG>�Q�F~~~reboot3.8.0-26-generic���QZ<2~~~runlevel3.8.0-26-generic���Q�%Ptty44LOGINP���QTtty55LOGINT���QZtty22LOGINZ���Q[tty33LOGIN[���Q^tty66~~~shutdown3.8.0-26-generic��Q��~~~reboot3.8.0-26-generict��Q(sy44P��Q�%
2~~~runlevel3.8.0-26-generict��Q�3
                                   Ptty44LOGINPt��QTtty55LOGINTt��QZtty22LOGINZt��Q[tty33LOGIN[t��Q^tty66LOGIN^t��Q�tty11LOGIN�v��Q�pts/0/0jai:0.0���Qb�pts/1/1jai:0.0���Q��pts/0/0jai���Q��pts/1/1jai���Q�02~~~runlevel3.8.0-26-genericU��Q$:
                Ptty44PV��QTtty55TV��Q�Ztty22ZV��Q[tty33[V��^tty66^V��Q�tty11�V��Q��~~~shutdown3.8.0-26-generice��Q�&~~~reboot3.8.0-26-genericX �Q2~~~runlevel3.8.0-26-genericX �Qf�Ytty44LOGINYX   �Q]tty55LOGIN]X �Qctty22LOGINcX �Qetty33LOGINeX �Qitty66LOGINiX �Q�tty11LOGIN�Y �Qpts/0/0jai:0.0�
�QlU                                             �Q@�pts/1/1jai:0.0
   pts/1/1jaii�Q�L    pts/0/0jaik�Q��n(pts/0/0jai:0.0��Qpts/0/0jai�#�QB02~Ytty44Y�k�Q�(]tty55]�k�Q|1ctty22c�k�Q�Setty33e�k�Q�Witty66i�k�Q�[�tty11��k�Q7�~~~shutdown3.8.0-26-generic�k�QL�~~~reboot3.8.0-26-generic��QMG
2~~~runlevel3.8.0-26-generic��Q�
�tty44LOGIN���Q�tty55LOGIN���Q�tty22LOGIN���Q�tty33LOGIN���Q�tty66LOGIN���QEtty11LOGINE��Q� pts/1/1jai:0.0���Q�h   pts/1/1jaiW��Q.
                                                                              �tty55�^��Q�tty22�^��Q�tty33�^��Q�tty66�^��QEtty11E^��Q�~~~shutdown3.8.0-26-genericr��Q�t~~~reboot3.8.0-26-generic��Q!Q
2~~~runlevel3.8.0-26-generic��Qy
rtty44LOGINr��Qvtty55LOGINv��Q|tty22LOGIN|��Q}tty33LOGIN}��Q�tty66LOGIN���Qxtty11LOGINx��Q� pts/1/1jai:0.0�Q��  pts/2/2jai:0.0O&�QiO
    �   pts/3/3jai:0.0�'�Q~pts/2/2jai�,�Q/pts/3/3jai�,�Q��pts/1/1jai2�Qʸ%pts/�/2jai:0.0O;�Q͵pts/2/2jail<�Q
 7pts/2/2jai:0.0�P�Q(w
                      7pts/4/4jai:0.0�Q�Q'�
                                          pts/2/2jai�[�Qpts/4/4jai�[�Q�i02~~~runlevel3.8.0-26-generic�]�Q�rtty44r�]�Q�
vtty55v�]�Q��
|tty22|�]�Qպ
}tty33}�]�Q9�
�tty66��]�Q��
xtty11x�]�Q�
~~~shutdown3.8.0-26-generic�]�Q��~~~reboot3.8.0-26-generic^�Q|� 2~~~runlevel3.8.0-26-generic^�Q��   �tty44LOGIN�^�Q�tty55LOGIN�^�Q�tty22LOGIN�^�Q�tty33LOGIN�^�Q�tty66LOGIN�^�Q�tty11LOGIN�^�Q
                                                                pts/1/1jai:0.0�b�Qpts/1/1jai�c�Q΋
62~~~runlevel3.8.0-26-generic�c�Q��tty44��c�Q5�tty55��c�Q��tty22��c�Q��tty33��c�Q��tty66��c�Q�tty11��c�Q##~~~shutdown3.8.0-26-generic
                                                                   d�Q�~~~reboot3.8.0-26-genericI}�Q�
2~~~runlevel3.8.0-26-genericI}�Q5<
                                   �tty44LOGIN�I}�Q�tty55LOGIN�I}�Q�tty22LOGIN�I}�Q�tty33LOGIN�I}�Q�tty66LOGIN�I}�Q�tty11LOGIN�P}�Q~~~reboot3.8.0-26-generic1��Q�2~~~runlevel3.8.0-26-generic1��Q6�tty44LOGIN�1��Q�tty55LOGIN�1��Q�tty22LOGIN�1��Q�tty33LOGIN�1��Q�tty66LOGIN�1��Qtty11LOGIN6��QLpts/1/1jai:0.05*�Q��
                      pts/1/1jai�+�Q1m&pts/0/0jai:0.0�4�pts/0/0jai�5�Q��02~~~runlevel3.8.0-26-generic=�Qq#�tty44�=�Q�.
                                          �tty55�=�Q�1
                                                       �tty22�=�QD4
                                                                    �tty33�=�Q�6
 �tty66�=�9
            tty11=�Q$F
                      ~~~shutdown3.8.0-26-generic=�Q��~~~shutdown3.8.0-26-generic=�Q�%~~~reboot3.8.0-26-generic}��Q)|   2~~~runlevel3.8.0-26-generic}��Q4D
�tty44LOGIN�}��Q�tty55LOGIN�}��Q�tty22LOGIN�}��Q�tty33LOGIN�}��Q�tty66LOGIN�}��Qtty11LOGIN���Q� pts/1/1jai:0.0V��Qpts/1/1jai6��QT�~~~reboot3.8.0-26-generic=��Q2~~~runlevel3.8.0-26-generic=��Q:P   �tty44LOGIN�=��Q�tty55LOGIN�=��Qtty22LOGIN=��Qtty33LOGIN=��Q�tty66LOGIN�=��Q�tty11LOGIN�C��Q02~~~runlevel3.8.0-26-generic���Q��tty44����Q�tty55����Q>tty22���Qtty33���Q~~~shutdown3.8.0-26-generic���Ql�~~~reboot3.8.0-26-genericf�Q%p  2~~~runlevel3.8.0-26-genericf�Q
�   �tty44LOGIN�f�Q�tty55LOGIN�f�Q�tty22LOGIN�f�Q�tty33LOGIN�f�Q�tty66LOGIN�f�Q�tty11LOGIN�k�Q�pts/0/0jai:0.0�{�QFQjai@frank-Jai:~$

jai@frank-Jai:~$ sudo cat /var/log/btmp

A: All three of the files that you want to read are stored in binary format. They are not plain text files and cannot be read with a normal text editor, or by using the cat command. Doing so will result in garbled output as you have noted.
Below are the functions of each of the three files:

*

*The file /var/log/btmp records failed login attempts.

*The file /var/run/utmp allows one to discover information about who is currently using the system. This file will contain information on a user's logins: on which terminals, logouts, system events and the current status of the system, system boot time (used by uptime) etc.

*The file /var/log/wtmp provides an historical record of utmp data.

You can use the last command to read each of the files.
For example:
sudo last /var/log/btmp` (note: this command needs to be run using sudo)

johndoe@computer:~$ last -f /var/run/utmp
 johndoe   tty7                          Fri Jul 26 17:58   still logged in
 reboot   system boot  3.5.0-37-generic Fri Jul 26 17:57 - 20:10 (1+02:13)

johndoe@computer::~$ last -f /var/log/wtmp
 reboot   system boot  3.5.0-37-generic Fri Jul 26 17:57 - 20:16 (1+02:19)
 johndoe   pts/2        :0               Fri Jul 26 17:52 - 17:55  (00:03)
 johndoe   pts/5        :0               Fri Jul 26 12:00 - 17:55  (05:55)
 johndoe   pts/0        :0.0             Fri Jul 26 07:11 - 11:58  (04:46)
 <snip>...

For more information see: Linux Display Date And Time Of Login
and the man pages for the command "last".

A: Using Perl 5
#!/usr/bin/env perl
#
# ripped from https://www.hcidata.info/wtmp.htm

use warnings;

@type=("Empty","Run Lvl","Boot","New Time","Old Time","Init","Login","Normal","Term","Account");
$recs = "";

while (<>) {
    $recs .= $_
};

foreach (split(/(.{384})/s, $recs)) {
    next if length($_) == 0;
    my ($type, $pid, $line, $inittab, $user, $host, $t1, $t2, $t3, $t4, $t5) = $_ =~/(.{4})(.{4})(.{32})(.{4})(.{32})(.{256})(.{4})(.{4})(.{4})(.{4})(.{4})/s;
    if (defined $line && $line =~ /\w/) {
        $line =~ s/\x00+//g;
        $host =~ s/\x00+//g;
        $user =~ s/\x00+//g;
        printf("%s %-8s %-12s %10s %-45s\n",
            scalar(gmtime(unpack("I4", $t3))),
            $type[unpack("I4", $type)],
            $user,
            $line,
            $host,
        )
    };
};

Output will look something like
Tue Dec 20 08:08:25 2022 Term                       pts/0
Mon Dec 26 02:19:58 2022 Normal   root              pts/0 131.191.30.152
Mon Dec 26 17:27:51 2022 Term                       pts/0
Mon Dec 26 18:23:54 2022 Normal   root              pts/0 131.191.30.152
Mon Dec 26 20:06:19 2022 Term                       pts/0
Wed Dec 28 07:07:29 2022 Normal   root              pts/0 131.191.30.152

last is the canonical way to read wtmp files. But this perl script hints at the wtmp file format.
Ripped from here.


text:
Q: Sonarcloud coverage configuration after 18 dec 2020 I have Java/Maven Open source project with coverage on sonarcloud. My CI/CD is Travis-ci and my code source is Github.
https://github.com/NoraUi/NoraUi
Before 18 dec 2020, my surfire and jacoco configuration is OK, but after sonarcloud change and my code coverage for my project do not work.
My pom.xml: https://github.com/NoraUi/NoraUi/blob/master/pom.xml
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<jacoco-maven-plugin.version>0.8.5</jacoco-maven-plugin.version>
<sonar-maven-plugin.version>3.7.0.1746</sonar-maven-plugin.version>
<project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
<sonar.sources>${project.basedir}/src/main/java/</sonar.sources>
<sonar.junit.reportPaths>${project.build.directory}/surefire-reports/junit</sonar.junit.reportPaths>
<sonar.surefire.reportPaths>${project.build.directory}/surefire-reports</sonar.surefire.reportPaths>
<sonar.jacoco.directory>${project.testresult.directory}/coverage/jacoco</sonar.jacoco.directory>
<sonar.jacoco.reportPath>${sonar.jacoco.directory}/jacoco.exec</sonar.jacoco.reportPath>
<sonar.tests>${project.basedir}/src/test/</sonar.tests>
<sonar.sourceEncoding>UTF-8</sonar.sourceEncoding>
<sonar.exclusions>**/cucumber/**/*,**/*Exception.*,**/annotation/**/*,**/noraui/model/**/*,**/noraui/data/rest/Row.java,**/noraui/utils/Constants.java,**/noraui/application/steps/MailSteps.java</sonar.exclusions>
<sonar.test.exclusions>**/*.css</sonar.test.exclusions>

<profile>
        <id>unit-tests</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>${jacoco-maven-plugin.version}</version>
                    <executions>
                        <execution>
                            <id>pre-unit-tests</id>
                            <phase>compile</phase>
                            <goals>
                                <goal>prepare-agent</goal>
                            </goals>
                            <configuration>
                                <destFile>${sonar.jacoco.reportPath}</destFile>
                                <propertyName>surefireArgLine</propertyName>
                            </configuration>
                        </execution>
                        <execution>
                            <id>post-unit-test</id>
                            <phase>test</phase>
                            <goals>
                                <goal>report</goal>
                            </goals>
                            <configuration>
                                <dataFile>${sonar.jacoco.reportPath}</dataFile>
                                <outputDirectory>${sonar.jacoco.directory}</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${maven-surefire-plugin.version}</version>
                    <configuration>
                        <systemPropertyVariables>
                            <resourcespath>${ciToolResourcesPath}</resourcespath>
                            <cucumber.options>${cucumber.options}</cucumber.options>
                            <webdriver.ie.driver>src/test/resources/drivers/%s/internetexplorer/%s/IEDriverServer%s</webdriver.ie.driver>
                            <webdriver.chrome.driver>src/test/resources/drivers/%s/googlechrome/%s/chromedriver%s</webdriver.chrome.driver>
                            <webdriver.gecko.driver>src/test/resources/drivers/%s/firefox/%s/geckodriver%s</webdriver.gecko.driver>
                            <SpeedRegulator.annotation.enable>false</SpeedRegulator.annotation.enable>
                            <SpeedRegulators.annotation.enable>false</SpeedRegulators.annotation.enable>
                            <Time.annotation.enable>false</Time.annotation.enable>
                            <Times.annotation.enable>false</Times.annotation.enable>
                            <uid>${uid}</uid>
                            <password>${password}</password>
                            <cookie>${cookie}</cookie>
                            <role>${role}</role>
                        </systemPropertyVariables>
                        <includes>
                            <include>**/*UT.java</include>
                            <include>**/Runner.java</include>
                        </includes>
                        <argLine>-Dfile.encoding=UTF-8 ${surefireArgLine}</argLine>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>${sonar-maven-plugin.version}</version>
                </plugin>
            </plugins>
        </build>
    </profile>

I try multiple change but do not work again.
I try add this:
sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml


text:
Q: ViewErrorBag Empty - Validation is not passing errors Controller
    $validator = Validator::make($request->all(), [
        'prox_scan' => 'required',
        'full_name' => ['required', new ValidateFullName],
    ]);

    if ($validator->fails()) {
        return redirect('/prox_login')
                    ->withErrors($validator)
                    ->withInput();
    }

View
@if ($errors->any())

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif

I have test the Controller and the error messages are being generated properly. But when it redirects to the view, the ViewErrorBag is empty. Solutions I've tried:

*

*Checked Handler.php to make sure \Illuminate\Session\Middleware\StartSession::class, is in the middleware section, it does

*Updated composer

*Updated Laravel to Laravel 8

Here is the response when dd($errors):
Illuminate\Support\ViewErrorBag {#297 ▼
  #bags: []
}

A: In Laravel 7+ (at least), the Kernel.php file contained middleware and middlewareGroups. For both arrays, the following two classes are included:

*

*\Illuminate\Session\Middleware\StartSession::class,

*\Illuminate\View\Middleware\ShareErrorsFromSession::class,
You just need to remove these two lines from middlewareGroup but leave them in middleware. My assumption is that having the two lines in both causes the $errors variable to be reset to empty every time.


text:
Q: Red underline on few activities in manifest file As shown in the picture
I am getting red underline in some of the activities in manifest file. Due to this, my application's apk is crashing every time I am downloading it on my phone. If i am connecting the device directly using usb, app is running perfectly. But when i build it's apk, it crashes when I launch my second activity i.e. ApplicationSelection.java, I have no clue why is this happening. Please help. Thanks in advance!


text:
Q: distutils IndexError: tuple index out of range I was trying to upload my library to https://pypi.org when this happened:
Traceback (most recent call last):
  File "setup.py", line 44, in <module>
    keywords=['producti-gestio', 'python', 'api', 'rest'],
  File "/usr/lib/python3.6/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/usr/lib/python3.6/distutils/dist.py", line 955, in
run_commands
    self.run_command(cmd)
  File "/usr/lib/python3.6/distutils/dist.py", line 974, in
run_command
    cmd_obj.run()
  File "/usr/lib/python3.6/distutils/command/upload.py", line 64, in
run
    self.upload_file(command, pyversion, filename)
  File "/usr/lib/python3.6/distutils/command/upload.py", line 158, in
upload_file
    value = valve[1]
IndexError: tuple index out of range

I don't know exactly what happened, I checked all files of my library, but all is fine! (I hope)
setup.py:
from distutils.core import setup

url = 'https://github.com/pyTeens/producti-gestio/archive/v0.3.0.tar.gz',

setup(
    name='producti_gestio',
    packages=['producti_gestio',
              'producti_gestio.core',
              'producti_gestio.decorator',
              'producti_gestio.project',
              'producti_gestio.server',
              'producti_gestio.utils'],
    version='0.3.0',
    description='A new simple web server',
    author='Gabriel Hearot',
    author_email='gabriel@hearot.it',
    url='https://github.com/pyTeens/producti-gestio',
    download_url=url,
    scripts=['bin/producti-gestio'],
    keywords=['producti-gestio', 'python', 'api', 'rest'],
)

Can you help me? Thank you.

A: Remove the comma at the end, it make url tuple type.
download_url and url expects string
url = 'https://github.com/pyTeens/producti-gestio/archive/v0.3.0.tar.gz',

Example:
>>> url = 'http://abc',
>>> type(url)
<type 'tuple'>


text:
Q: Android : first listview item show 1dp border but other items shows border 2dp I create some listview item with an adapter from a item xml file.
I have added a thin border on the top of a layout.
In my listview, the first item is OK, with a border = 1dp, but for others items, the border is more big : 2p..
Where is the problem ?
Here is the code all_annonces_item.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="120dp"
    android:layout_margin="10dp"
    android:background="@color/bg_listview_all"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/allannonces_image"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:background="@drawable/bg_top_and_left"
        android:scaleType="centerCrop"
        android:src="@drawable/test2" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_toRightOf="@id/allannonces_image"
        android:background="@drawable/bg_top_and_right"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/allannonces_titre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="TextView"
            android:textColor="#666666"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/allannonces_categorie"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="10dp"
            android:text="TextView"
            android:textColor="#9A9A9A"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/allannonces_prix"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="5dp"
            android:layout_marginRight="10dp"
            android:text="TextView"
            android:textColor="#6EA601"
            android:textSize="12sp" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="33dp"
        android:layout_below="@id/allannonces_image"
        android:background="@drawable/bg_linearlayout" >

        <ImageView
            android:id="@+id/allannonces_imageuser"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:src="@drawable/avatar5" />

        <TextView
            android:id="@+id/allannonces_pseudo_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@id/allannonces_imageuser"
            android:text="TextView"
            android:textSize="10sp" />

        <TextView
            android:id="@+id/allannonces_ville"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:layout_marginRight="10dp"
            android:text="TextView"
            android:textSize="10sp" />

    </RelativeLayout>

</RelativeLayout>

And the code of the impacted xml file bg_top_and_right.xml :
<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
      <solid android:color="#E3E3E1" />
    </shape>
  </item>
    <item android:top="1dp"  android:right="1dp" >
     <shape android:shape="rectangle">
      <solid android:color="@color/blanc" />
    </shape>
   </item>
 </layer-list>

And finally, the code of my adapter :
public class AllAnnonces_custom_adapter extends ArrayAdapter<Annonce> {

    Typeface robotolight = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Light.ttf");
    Typeface robotoBold = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Bold.ttf");
    Typeface robotoRegular = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf");

    public AllAnnonces_custom_adapter(Activity activity, List<Annonce> annonces) {
        super(activity, 0, annonces);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolderItem viewHolder;

        if (convertView == null) {
            Activity activity = (Activity) getContext();
            // inflate the layout
            LayoutInflater inflater = activity.getLayoutInflater();
            convertView = inflater.inflate(R.layout.all_annonces_item, parent, false);
            // well set up the ViewHolder
            viewHolder = new ViewHolderItem();
            viewHolder.imageAnnonce = (ImageView) convertView.findViewById(R.id.allannonces_image) ;
            viewHolder.titre = (TextView) convertView.findViewById(R.id.allannonces_titre);
            viewHolder.villeObj = (TextView) convertView.findViewById(R.id.allannonces_ville);
            viewHolder.prix = (TextView) convertView.findViewById(R.id.allannonces_prix);
            viewHolder.pseudoUser = (TextView) convertView.findViewById(R.id.allannonces_pseudo_user);
            viewHolder.categorie = (TextView) convertView.findViewById(R.id.allannonces_categorie);
            viewHolder.imageUser = (ImageView) convertView.findViewById(R.id.allannonces_imageuser) ;

            // store the holder with the view.
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolderItem) convertView.getTag();
        }

        Annonce annonce = getItem(position);

        if (annonce != null) {

            DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .build();

            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext())
            .defaultDisplayImageOptions(options)
            .threadPriority(Thread.MAX_PRIORITY)
            .denyCacheImageMultipleSizesInMemory()
            .memoryCacheSize(2 * 1024 * 1024)
            .build();

            ImageLoader imageLoader = ImageLoader.getInstance();
            imageLoader.init(config);
            imageLoader.displayImage(annonce.getImage(), viewHolder.imageAnnonce);

            String imageUser = annonce.getImageUser();
            if (imageUser.equals("avatar1")) {
                viewHolder.imageUser.setImageResource(R.drawable.avatar1) ;
            }
            else if (imageUser.equals("avatar2")) {
                viewHolder.imageUser.setImageResource(R.drawable.avatar2) ;
            }
            else if (imageUser.equals("avatar3")) {
                viewHolder.imageUser.setImageResource(R.drawable.avatar3) ;
            }
            else if (imageUser.equals("avatar4")) {
                viewHolder.imageUser.setImageResource(R.drawable.avatar4) ;
            }
            else if (imageUser.equals("avatar5")) {
                viewHolder.imageUser.setImageResource(R.drawable.avatar5) ;
            }
            else if (imageUser.equals("avatar6")) {
                viewHolder.imageUser.setImageResource(R.drawable.avatar6) ;
            }
            else {
                viewHolder.imageUser.setImageResource(R.drawable.avatar1) ;
            }

            viewHolder.titre.setText(annonce.getTitle());
            viewHolder.titre.setTypeface(robotoRegular);

            viewHolder.pseudoUser.setText(annonce.getPseudoUser());
            viewHolder.pseudoUser.setTypeface(robotoRegular);

            viewHolder.categorie.setText(annonce.getCategorie());
            viewHolder.categorie.setTypeface(robotoRegular);

            viewHolder.villeObj.setText(annonce.getVilleObjet());
            viewHolder.villeObj.setTypeface(robotoRegular);

            viewHolder.prix.setText(annonce.getPrix());
            viewHolder.prix.setText("€" + annonce.getPrix() + ",00 EUR");
            viewHolder.prix.setTypeface(robotoRegular);
        }

        return convertView;

    }

    static class ViewHolderItem {
        ImageView imageAnnonce;
        ImageView imageUser;
        TextView titre;
        TextView villeObj;
        TextView pseudoUser;
        TextView prix;
        TextView categorie;
    }

}


text:
Q: QGIS model designer, get output value I am developing a model, will go through different steps of calculation to create new field using @field calculator algorithm which can generate a layer as output.
.
One of my calculations is to generate a serial number because this model will be running more than one time for each try, and i want to track my results. this value will by an input from another Expression  = rand( 100000000000,999999999999)

The issue is I can't get that value for the serial number produced by Expression and will create temporary layer named serial_number_layer, to use that value again in Atlas exporting filter.
I tried to use attribute, aggregate, use the output directly for both Expression  or field calculator.
.
How do I get that serial number attribute value?


text:
Q: How can I use Maven to specify which Junit @Category of tests to run without needing to specify the full path of each category? I'd like to use Maven to specify which tests to run using Junit @Category annotations, without needing to specify the full path of the categories.
Currently I specify which category of tests to run using the full path of the categories.
-Dgroups="com.example.categories.FastTests,com.example.categories.SlowTests"

I'm looking for a way to shorten that to:
-Dgroups="FastTests,SlowTests"

Is this possible?


text:
Q: multiple actions with curl I'm trying to do two actions with curl:
 1. Login into admin page
 2. Submit a form (add user)
The first one go fine but the second show error as not loged in.
Here is my code:
$ch1 = curl_init();
$ch2 = curl_init();

curl_setopt($ch1, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt($ch1, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch1, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch1, CURLOPT_URL, "http://admin.example.com/admin");
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, "user=admin&pass=password");
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch1, CURLOPT_RETURNTRANSFER,1); // return into a variable

curl_setopt($ch2, CURLOPT_URL, "http://admin.example.com/admin/adduser");
curl_setopt($ch2, CURLOPT_POST, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS, "newu=demo&pass=password");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, 1);

$mh = curl_multi_init();
    curl_multi_add_handle($mh, $ch1);
    curl_multi_add_handle($mh, $ch2);

    // execute all queries simultaneously, and continue when all are complete
    $running = null;
    do {
        curl_multi_exec($mh, $running);
    } while ($running);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

A: You can perform both of these requests using the same cURL handle.  The problem in using curl_multi_exec in this case is that each curl handle has different options and $ch2 does not reference any cookies.
Also, curl_multi_exec performs the requests in parallel which means you may try to add the user before the login request is completed or even started.
Try this instead, it illustrates logging in using $ch, and then using it again to add the user.  If the server supports keep-alive, then you can add a keep-alive header and the same socket connection is re-used for the second request.
$ch = curl_init();

curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL, "http://admin.example.com/admin");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=admin&pass=password");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable

$res = curl_exec($ch);

// check $res here to see if login was successful

curl_setopt($ch, CURLOPT_URL, "http://admin.example.com/admin/adduser");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "newu=demo&pass=password");

$res = curl_exec($ch);

// check $res to see that the user was successfully created

curl_close($ch);

Here are some other answers showing how to make multiple serial requests to the same site using cURL after logging in.
Login to Google with PHP and Curl, Cookie turned off?
Retrieve Android Market mylibrary with curl
PHP Curl - Cookies problem

A: The problem is that by using curl_multi, you are executing both requests at the same time. The form submitting request will be sent at the same time as the login request, so the login cookies will not be available yet.
Additionally, you're not passing the cookies to the form request at all. You forgot to do this:
curl_setopt($ch2, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch2, CURLOPT_COOKIEFILE, "cookie.txt");

You should do both requests separately to ensure that the proper login cookies are available for the form request.


text:
Q: Laravel 5.1. Token from and session token are different using mobile browser (login action) I have got this login form:
<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    ...

I login with no problem using a browser from a desktop (IE, Chrome, Firefox, ...), but the problem comes from mobile device (android platform).
I got this exceptión:
TokenMismatchException in VerifyCsrfToken.php line 53.

When I went to VerifyCsrfToken.php I discovered that the token passed from the form and the token taked from session object are different. But this only happens from my android phone.
On function called tokensMatch in the file VerifyCsrfToken.php (link to github) I add this code to see what was happening:
echo '
X-CSRF-TOKEN:'.$request->header('X-CSRF-TOKEN');
echo '
X-XSRF-TOKEN:'.$request->header('X-XSRF-TOKEN');
echo '
token:'.$request->input('_token');
echo '
sessionToken:'.$request->session()->token();

Token and sessionToken are different (the other two value are empty).
Any clues about this? This only happens using a mobile device (two android tested).
UPDATE: I set the token input to text to view the content from the browser. The thing is that in mobile devices when I refresh the url [domain.com]/auth/login, the token changes in every call, however, from desktop browser the token do not change. I think that in mobile devices the sessions is created and destroyed in every call.
UPDATE 2: I confirm that the problems comes by the changing of token in every request. I don't know that this happens only from mobile devices.

A: Solved.
The problem was a wrong value of 'domain' key in session.php. On mobile devices for any reason the cookies policies are more restricted.
I had got this value:
'domain' => env('SESSION_DOMAIN', 'www.[mydomain].com'),

I need to remove www., so this value must be like this:
'domain' => env('SESSION_DOMAIN', '[mydomain].com'),

For any reason from desktop browser with no special configuration the cookie works with no problem.


text:
Q: Trying to get iframe parent window element's data, and append to body of iframe I have a hidden element on my [parent] page:

Testing!

And now, I'm trying to get an iFrame embeded on the page to find the .output-data div, assign it's contents to a var, and then append it to itself as the document. So my iFrame markup is literally just this:

In other words, I'm trying to get my iFrame to assume and display the HTML contents of the .output-data div, but it's not working and I can't seem to figure out why? I can't find anything in my web inspector? Anyone know?

A: Use the selector context argument:
$('div.output-data',window.parent.document).html();

A: Define a JS method (GetData) in the parent that returns the content you want.
You can call this method from the iframe through the window.parent property.
function GetData(){
  return $(".output-data").html();
}

Ex: from the iframe: var content = window.parent.GetData()


text:
Q: Why can't I log into my Draw Something account after reinstalling it? Draw Something froze on me with the the screen being black: I exited the app and reopened it, but was still black.
I ended up deleting the app and reinstalling it to see if it would work, but now I can't log in into my account. How can I fix this?

A: One thing I've noticed is that you need to use your username, not your email address to log in sometimes, maybe that's the issue?


text:
Q: how to filter a getter in doctrine2 entity? I have an entity that has a one-to-many association (many-to-many with extra fields):
class Game {
    /**
    /* @OneToMany(targetEntity="GamePlayer", mappedBy="game", cascade={"persist"})
    /* @JoinColumn(name="id", referencedColumnName="game_id", onDelete="cascade")
     */
    private $gamePlayer;
}

The class has automated getter for all the authors: getGamePlayers()
I would like to add a filter to it, so it would query the database only for the relevant details in the most efficient way:
public function getGamePlayersWithScoreHigherThan($score){
    //what to write here? (return array)
}

What is the best way to achieve such a getter from within the entity (not using the repository)?
Thank you very much!

A: You could try creating a separate method on your entity that uses the Doctrine\Common\Collections\Criteria to filter the associated collection. See this link for details.


text:
Q: How to use config.yml for docker compose env As far as I know, to use the env variable in docker-compose we need to create a .env file
PORT=9000

And then use it like this in docker-compose.yml:
services:
  go:
    ports:
      - ${PORT}:${PORT}

But what if I have a config file in .yml file like this:
http:
  host: "0.0.0.0"
  port: "1020"
jwt_secret: "secret"

How to access it on the docker-compose? This doesn't work:
version: "3.8"
services:
    go:
        env_file: config.yml
        build:
            context: .
            dockerfile: Dockerfile
        command: /fetch-app
        ports:
            - ${http.port}:${http.port}
        environment:
            NODE_ENV: development

It is generates error:
invalid interpolation format for services.go.ports.[].
You may need to escape any $ with another $.
${http.port}:${http.port}


text:
Q: python change source code while running Simple questions for those who know, pretty hard for me, as I think that it is not pratically possible.
After making a simple python program, it is possible to run it on the computer's command prompt.
I was wondering or it is possible to allow someone who runs it that way, to add an element to a list (list.insert) and have it still there the next time the program is run?(thus editting the predefined list to a new list and saving it that way)
EDIT: just giving a bit more information:
All the program has to do is allow you to choose a list. From this list it returns a random item.
I was just hoping to allow to add items to this list while running the program, keeping the list updated afterwards.

A: The most basic way is to use the Pickle module to save and load your data to disk:
http://docs.python.org/2/library/pickle.html
http://docs.python.org/2/library/pickle.html#example
Here's how I would use it in a simple program
try:
    import cPickle as pickle
except ImportError:
    import pickle

class MyClass(object):

    def __init__(self, file_name):
        self.array = []
        self.file_name = file_name
        self.load_data()

    def add_element(self, element):
        self.array.append(element)
        self.save_data()

    def load_data(self):
        try:
            with open(self.file_name, "r") as f:
                self.array = pickle.load(f)
        except IOError:
            pass

    def save_data(self):
        with open(self.file_name, "w") as f:
            pickle.dump(self.array, f)

def main():
    FILE_NAME = "test.pkl"
    a = MyClass(FILE_NAME)
    print "elements in array are", a.array
    for i in range(5):
        a.add_element(i)

if __name__ == "__main__":
    main()


text:
Q: How to save radio button values to cookies in Javascript? I would post code showing exactly what I'm trying to accomplish but apparently that just starts arguments. So can anyone post the JavaScript syntax to save 2 different radio buttons from an HTML form into the browsers cookies? I cannot use JQuery, it has to be done with JavaScript.

A: Based on your code from https://stackoverflow.com/questions/37214000/javascript-how-to-save-gender-form-radio-buttons-to-browser-cookies
add this function to your page
 function GetGenderValue() {
  var genderRadio = document.getElementsByName('Gender');
  var genderValue;
  for(var i = 0; i < genderRadio.length; i++){
      if(genderRadio[i].checked){
          genderValue = genderRadio[i].value;
      }
  }
  return genderValue;

 }

then in your other function named SaveForm(), add this line:
setCookie("Gender", GetGenderValue());

to load the values add another function:
function SetGenderValue(genderValue) {
  var genderRadio = document.getElementsByName('Gender');
  for(var i = 0; i < genderRadio.length; i++){
      if(genderRadio[i].value == genderValue){
          genderRadio[i].checked = true;
      }
  }
}

and update your LoadForm(), add
SetGenderValue( getCookie("Gender") );

A: I am a noob too, however setCookie is php not javascript.
document.cookie= "cookiename" = "cookievalue"; should be right.
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie


text:
Q: Rewrite when name includes Question Mark (?) I have a re-write in place that is doing what I wish.
It's rewriting a URL as follows:
https://db.ygoprodeck.com/card/?search=kuriboh

To the following:
https://db.ygoprodeck.com/card/kuriboh/

I also have an additional rewrite to handle "/" in a name, such as:
https://db.ygoprodeck.com/card/D/D/D%20Destiny%20King%20Zero%20Laplace/

My htaccess is as follows:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?card/(.*?)/?$ /card/?search=$1 [L]

RewriteCond %{THE_REQUEST} \s/card(?:\.php)?/?\?search=([^\&\s]+) [NC]
RewriteRule ^ /card/%1? [L,R=301,NE]

Now I just discovered an issue that when  a ? is in the actual name of my item, only everything before the ? is taken.
https://db.ygoprodeck.com/card/Danger!?%20Tsuchinoko?

Is being read as:
https://db.ygoprodeck.com/card/Danger!

I'm still trying to learn rewrites so I'm not sure how to accomplish this. An explanation would be vastly appreciated.


text:
Q: To use nested genericized collections or custom intermediate classes? Before the introduction to generics to the Java language I would have written classes encapsulating collections-of-collections-of-collections. For example:
class Account {
   private Map tradesByRegion; //KEY=Region, VALUE=TradeCollection
}

class TradeCollection {
   private Map tradesByInstrument; //KEY=Instrument, Value=Trade
}

Of course, with generics, I can just do:
class Account {
   private Map<Region, Map<Instrument, Trade>> trades;
}

I tend to now opt for option #2 (over a generified version of option #1) because this means I don't end up with a proliferation of classes that exist solely for the purpose of wrapping a collection. But I have a nagging feeling that this is bad design (e.g. how many nested collections should I use before declaring new classes). Opinions?

A: 2 is better because:

*

*Less code accomplishes the same
effect (better, actually, as in #1
some of your type information exists
only in comments)

*It's completely clear what's going
on.

*Your type errors will be caught at compile time.

What is there to recommend 1? admittedly the Map< Integer , < Map < String, < Map< ... generics are a bit hard to get used to, but to my eye it's much easier to understand than code with maps, and lists of maps, and maps of lists of maps, and custom objects full of lists of maps.

A: Combination of the two.  While you can use generics to replace custom classes, you still will want to use a class to encapsulate your concepts.  If you're just passing maps of maps of maps of lists to everything, who controls what you can add?  who controls what you can remove?
For holding the data, generics is a great thing.  But you still want methods to validate when you add a trade, or add an account, and without some kind of class wrapping your collections, nobody controls that.

A: I have made this simple rule for me: Never more than two <'s and two commas in a generics declaration and preferably only one comma. After that I introduce custom types. I think this is the point where the readability suffers enough to warrant additional concepts.
There is a real good reason to avoid too deep generics: The complexity is not only in the actual declaration but usually tends to be equally visible in the construction logic. So a lot of code has a tendency to become convoluted if you nest these declarations too deeply. Creating intermediate classes can help a lot. The trick is often to find the proper intermediate classes.
I definitely think you should go a slight bit back towards your old standard. Actually your second sample is the exact pain-point where I'd still accept generics-only.

A: Normally there will also be some code to operate on the collections. When this becomes nontrivial I package up the collection with the behavior in a new class. The deeper the nesting is the more likely this will be the case.

A: I think it's better to keep objects in mind and emphasize the collections a bit less.  Reification is your friend.
For example, it's natural to have Student and Course objects if you're modeling a system for a school.  Where should grades be captured?  I'd argue that they belong in an object where Student and Course meet - a ReportCard.  I wouldn't have a GradeCollection.  Give it some real behavior.

A: I prefer #2.  It is clearer what is going on, and is typesafe at compile time (I prefer having as many things go wrong at compile time as possible, as opposed to having them happen at runtime... in general I like it when nothing goes wrong).
Edit:
Well there are two ways that I can see... I guess it depends on which you would use:
class Account
{
   private Map<Region, TradeCollection> tradesByRegion;
}

class TradeCollection
{
   private Map<Instrument, Trade> tradesByInstrument;
}

or
class Account<R extends Region, I extends Instrument, T extends Trade, C extends TradeCollection<I, T>>
{
   private Map<R, C> tradesByRegion;
}

class TradeCollection<I extends Instrument, T extends Trade>
{
   private Map<I, T> tradesByInstrument;
}

A: I think the answer to this is that it depends on the situation.  Generally, introducing a type is useful if that also introduces methods related to the type, if those intermediate types are passed around independently, etc.
You might find this bit of advice from Rich Hickey (the creator of Clojure) about creating interoperable libraries kind of interesting:

*

*http://groups.google.com/group/clojure/browse_thread/thread/e0823e1caaff3eed
It's intended as specific advice to Clojure library writers but I think is interesting food for thought even in Java.


text:
Q: How to create a matrix with floats in C I'm reading a text file which contains a matrix, and trying to save said matrix in a matrix, but I believe I'm not doing it correctly since when I compile the program I get the error subscripted value is neither array nor pointer nor vector. Here's the code (n_rows and n_cols is the number of columns and rows of the matrix):
float kernel[n_rows];
float aux;
for (int i = 0; i < n_rows; i++){
    float row[n_cols];
    for (int j = 0; j < n_cols; j++){
        fscanf(f, "%f", &aux);
        row[j] = aux;
    kernel[i] = *row;
    }
}
for (int i = 0; i < n_rows; i++){
    for (int j = 0; j < n_cols; j++){
        printf("%f ", kernel[i][j]);
    }
    printf("\n");
}

The problem it's in the printf part, so my matrix it's not correctly arranged. What's the correct way of doing it?

A: You need to modify your code as follows:

*

*Make kernel an array of pointers - this will fix the compile problem you see

*Allocate each row dynamically - this will fix the problem with using temporary memory for your rows

*Make the assignment outside the nested loop - this will address a small efficiency issue.

Here is one way to fix it:
float *kernel[n_rows];
for (int i = 0; i < n_rows; i++){
    float *row = malloc(sizeof(float)*n_cols);
    for (int j = 0; j < n_cols; j++){
        fscanf(f, "%f", &row[j]);
    }
    kernel[i] = row;
}

A: You create your matrix kernel as a 1-dimensional array. You actually want a 2D array (float kernel[n_rows][n_cols]).
Note you'd still have to change your row-fill code to make it work:
float *row = kernel[i];
for (int j = 0; j < n_cols; j++){
    fscanf(f, "%f", &aux);
    row[j] = aux;
}

A: If you know n_rows and n_cols ahead of time, then define kernel as:
    kernel[n_rows][n_cols];
As written, your row[n_cols] definition is on the stack, so while you can populate a row, the value of kernel[i] will be set to point to this stack-based array, and it will get clobbered each time through the loop.
By defining a two-dimensional kernel, you avoid this.
float kernel[n_rows][n_cols];
for (int i = 0; i < n_rows; i++){
    for (int j = 0; j < n_cols; j++){
        fscanf(f, "%f", &kernel[i][j]);
    }
}
for (int i = 0; i < n_rows; i++){
    for (int j = 0; j < n_cols; j++){
        printf("%f ", kernel[i][j]);
    }
    printf("\n");
}

If you do not know n_rows and n_cols up front, then you need to malloc an array of n_rows row pointers once you determine n_rows. Then loop for each row and malloc a float array for each row and point to it as shown by @dasblinkenlight


text:
Q: Automatically starting a child process with 'High' priority? My computer running Windows 7 is getting old, and Flash content stutters a bit too much. I am finding that elevating the priority of the plugin process helps a lot.
I know of the /high switch to start an executable with 'High' priority, but I don't know how to raise the priority of a child process (plugin executable kicked off by a (parent) browser process) automatically.
I'd like to do this without installing any additional software on the machine. If there's a way to do this from the browser itself (I use Firefox and Chrome), it'd be even better.
Also, FMI: Are there any possible unintended consequences that I may be overlooking?

A: Whenever I play a Flash video in Firefox a couple of instances of FlashPlayerPlugin_11_7_700_224.exe start up (version number will obviously change over time). You can run the following command to set the priority of a process from the command line:
wmic process where name="FlashPlayerPlugin_11_7_700_224.exe" setpriority 32768

However, doing this when you start Firefox will not work since the FlashPlayerPlugin process is started on-demand, and killed once it is no longer required. So you can create a batch file that you can run as and when required, or perhaps schedule the file to be executed every say 10 mins. or so.

A: There are tools outside which can adjust the priority to what you want.
One of them is Prio. Here you can save the priority in taskmgr:

Each time you run the Program now, it will be started with the saved priority.

A: Open your Firefox shortcut icon properties, and paste %comspec% /c start /HIGH FireFox.exe into the Target Location box.
Click Apply
That is all.
This particular shortcut will now always start Firefox at a HIGH priority,
and you can make other icons for NORMAL priority, if you want, too.


text:
Q: How do you find the coordinates of the cursor in Python 3? I found this code to be the most helpful to other people:
x, y = win32api.GetCursorPos()

When I run this code, I get an error "NameError: name 'win32gui' is not defined on line ##".
When trying to import the module:
import win32gui

I get an error "ImportError: No module named win32gui on line ##".
I tried running:
pip install win32gui

But it doesn't seem to work. How can I use win32gui?

A: win32gui comes as a part of the external package PyWin32. You may download this package to install this module.
Note that this is not a part of the standart library (a third party library, proceed with caution).

A: You can use a third party module pyautogui, which is installed by: pip install pyautogui
Code for mouse position:
import pyautogui
print pyautogui.position()

It will return a tuple with your x, y coordinate position


text:
Q: Show that $C$ is a chain complex I suppose it's a common exam question to show that a certain sequence actually is a chain complex. What is it that has be shown, minimally? A chain complex is a sequence of modules and module maps, and any two maps succeeding each other must compose to the zero map. So, do I have to show that the sets in the sequence are modules, and that the maps are module maps, and the final condition on composition?

A: A $\mathbb Z$-graded  chain complex $(C_{\bullet},d_{\bullet})$ of $R$-modules is a collection
$$C_{\bullet}=\{C_i\}_{i\in\mathbb Z} $$
of $R$-modules and $R$-module morphisms
$$d_i: C_i\rightarrow C_{i-1}$$
s.t. $d_i\circ d_{i-1}=0_{C_{i+1}}$, for all $i\in\mathbb Z$.
You can similalry introduce chain complexes of vector spaces etc...
Dually (in some sense) one can define the cochain complexes: one inverts arrows considering "+1-degree" morphisms. A small $caveat$: in some references you can find as chain complex the direct sum
$$C_{\bullet}=\bigoplus_i C_i $$
with the aforementioned morphisms $d_i$; this is a bit "dangerous" definition due to completion issues that can arise in applications (I mean "direct sum vs. direct product").
Using the word "collection" is sufficient to bypass most of these technicalities.
$$d_i: C_i\rightarrow C_{i+1}$$


text:
Q: How to add HttpClientHandler to url? I have this request handler:
var httpClientHandler = new HttpClientHandler
{
    Proxy = new WebProxy(proxy.Address, proxy.Port),
    UseProxy = true
};

And:
var url = new Url(hostUrl)
    .AppendPathSegment(pathSegment);

How do I add the request handler to the FlurlClient?

A: Create your own ProxiedHttpClientFactory that overrides the CreateMessageHandler() method:
public class ProxiedHttpClientFactory : DefaultHttpClientFactory
{
    private readonly string _proxyAddress;
    private readonly int _proxyPort;

    public ProxiedHttpClientFactory(string proxyAddress, int proxyPort)
    {
        this._proxyAddress = proxyAddress;
        this._proxyPort = proxyPort;
    }

    public override HttpMessageHandler CreateMessageHandler()
    {
        return new HttpClientHandler
        {
            Proxy = new WebProxy(this._proxyAddress, this._proxyPort),
            UseProxy = true
        };
    }
}

Then use it:
var settings = new FlurlHttpSettings
{
    HttpClientFactory = new ProxiedHttpClientFactory("my.proxy.com", 8080)
};

var client = new FlurlClient(settings);

And on an existing Url instance:
var url = new Url(hostUrl)
               .AppendPathSegment(pathSegment)
               .ConfigureClient(settings => settings.HttpClientFactory = new ProxiedHttpClientFactory("my.proxy.com", 8080));


text:
Q: Can't Grab Query String in JavaScript We were provided function getQueryStringVariableByItemID for our project and are using function getData to use a web service for a game's details from a games table. We believe the getData part is working fine since we use a similar POST on another page. Is getQueryStringVariableByItemID not properly grabbing the query string?
We call getData with the body tag of html as onload="getData()". Many thanks in advance!
Code:

A: The ItemID you are passing in the getData(while calling inside the getData) should be undefined because the function doesnt have that variable.Pass a valid id and it will work fine


text:
Q: VB.Net Use string to construct name of array for use in function? I have two sets of jagged arrays, named P1 through P6 and Z1 through Z6, the contents of which are fruit in the P arrays and cars in the Z arrays. I also have a function that will obtain a value from one of these arrays:
Public Function retL(ByVal L As Array)
    Dim maxL As Integer = L.GetUpperBound(0)
    Dim numL As Integer = randomizer(maxL)
    Dim resL As String = L.GetValue(numL - 1)
    Return resL
End Function

L, in the above, is constructed by the following piece of code:
 Dim L As String = "P" & randomizer(6)
       or
 Dim L As String = "Z" & randomizer(6)

So, my issue is that none of this is working. Because L is constructed as a string, but then called by retL as an array, it fails. If I attempt to construct L as an array to begin with, it fails. If I attempt to call it as a string, it fails. I'm lost and confused as to where to proceed from here. Obviously what I'm trying to do is possible, but I've also obviously either missed an important step or I'm not grasping some basic concept.
Any suggestions?

A: What you really want here is an array of arrays. Instead of:
Dim P1(n) As String
Dim P2(n) As String
'...
Dim P6(n) As String
'...
Dim Z6(n) As String

... where 'n' is the size of your array, you should have something more like this:
Dim P(5, n) As String
Dim Z(5, n) As String

Note that I used a 5 instead of a 6, because in VB.Net arrays are zero indexed, rather than one indexed, and the subscript is the index of the last item, rather than the number of items. So Dim P(5, n) As String gives you a two-dimensional string array with six items on the first dimension.
Now your function should look like this:
Public Function retL(ByVal L() As String) As String
    Return L(randomizer(L.Length)-1)
End Function

And you could call the function from your current code like this:
Dim result As String = retL(P(randomizer(6) - 1)

A: Here is a litle test class that does several things
Class TestRandomArrays
    Private L As String()
    Private randomizer As New Random()

    Public Sub InitializeArrayWithRandomLength()
        ' Creates an array of length between 0 and 5
        L = New String(randomizer.[Next](6) - 1) {}
    End Sub

    Public Sub FillArrayWithRandomText()
        For i As Integer = 0 To L.Length - 1
            L(i) = "P" & randomizer.[Next]()
        Next
    End Sub

    Public Function ReturnRandomArrayItem() As String
        Return L(randomizer.[Next](L.Length))
    End Function
End Class

Array items are accessed by their index using the array(index) syntax.
The brackets around the Next method are due to the fact that Next is a keyword in VB. They tell the VB compiler that Next is intended to be an identifier and not a keyword.
Random.Next(max) returns a integer between 0 and max-1.
New String(n) {} defines an array with an index range of 0..n and thus an array of length n+1.
This is NOT a jagged array. A jagged array is an array of arrays, i.e., the resulting variable would have (at least) two dimensions.


text:
Q: How to transform Delete option in Tableview cell I've transformed the tableview and tableview cell to fill the cell from bottom to top using How to populate UITableView from the bottom upwards? post.
But I want to transform the swipe to Delete option as well.
Please refer the image for more detail.

You can see the Delete option is not transform as the tableview.
Any helpful answer will be very appreciated.

A: First reverse UITableView in viewDidLoad
override func viewDidLoad() {
        super.viewDidLoad()
        tableView.transform = CGAffineTransform(scaleX: 1, y: -1)
}

Then reverse the cell in cellForRowAt.
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as? MyTableViewCell else { fatalError() }

            cell.transform = CGAffineTransform(scaleX: 1, y: -1)
            cell.contentView.transform = CGAffineTransform(scaleX: 1, y: -1)

            return cell
        }
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let delete = UITableViewRowAction(style: .default, title: nil) { (action, indexPath) in
            // delete item at indexPath
        }

        let label = UILabel(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 75, height: tableView.rectForRow(at: indexPath).height)))
        label.numberOfLines = 0
        label.textAlignment = .center
        label.textColor = UIColor.white
        label.backgroundColor = UIColor.red
        label.text = "Delete"
        UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0.0)
        label.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        if let cgImage = image?.cgImage {
            let rotada3 = UIImage(cgImage: cgImage, scale: image!.scale, orientation: .downMirrored)
            delete.backgroundColor = UIColor(patternImage: rotada3)

        }

        return [delete]
    }

Here on editActionsForRowAt I did a work around to print image with mirrored text

A: Transform tableview
tableView.transform = CGAffineTransform(rotationAngle: -(.pi))

Then within cell
cell.transform = CGAffineTransform(rotationAngle: .pi)


text:
Q: HeadlessUI Tabs active tabs gets back to 0 after refresh I badly need help about headlessUI tabs. I was trying to fix it my own and research but there's not enough resources about my problem. I still don't understand how this is not working, I also read the docs.
import { useEffect, useState } from "react";
import { Tab } from "@headlessui/react";

function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}

export default function Tabs({ tabs }) {
  const [index, setIndex] = useState();

  return (
    <Tab.Group
      defaultIndex={index}
      onChange={(index) => {
        console.log("Changed selected tab to:", index);
        setIndex(index);
      }}
    >
      <Tab.List className="text-xl space-x-9">
        {tabs.map(({ tab }, index) => (
          <Tab
            key={index}
            className={({ selected }) =>
              classNames(
                selected ? "text-gray-900" : "text-gray-400 font-avenir-roman"
              )
            }
          >
            {tab}
          </Tab>
        ))}
      </Tab.List>
      <Tab.Panels>
        {tabs.map(({ content }, index) => (
          <Tab.Panel key={index}>{content}</Tab.Panel>
        ))}
      </Tab.Panels>
    </Tab.Group>
  );
}

A: This is what I did to persist the currentTab
const [currentTab, setCurrentTab] = useState(0);

useEffect(() => {
    localStorage.setItem("currentTab", JSON.stringify(currentTab));
  }, [currentTab]);

  useEffect(() => {
    const currentTab = JSON.parse(localStorage.getItem("currentTab"));
    if (currentTab) {
      setCurrentTab(currentTab);
    }
  }, []);

 <Tab.Group
            defaultIndex={tab}
            onChange={(currentTab) => {
              setCurrentTab(currentTab);
              router.replace(
                {
                  pathname: `/path/userPath/edit/${id}`,
                  query: { tab: currentTab },
                },
                undefined,
                {
                  shallow: true,
                }
              );
            }}
          >


text:
Q: Spring AOP : How to get Caller method arguments values into Spring Aspect class advice method As i am asking this question i didn't find any solution for my requirement.
Requirement :
Currently i am working on a project using Spring Boot with Rest and Spring Integration .
My Requirement was Log all the gateway service calls into audit table for success and failure both scenarios. Each Gateway contains the gateway specific information which has to be stored in audit table.I am using the spring AOP - @After Advice annotation to log audit information, But this annotation method is expecting audit values which are part of the gateway service CALLER method.
Example :
@Autowired
com.study.pattern.sample.app.gateway.EmployeGatewayservice employeGatewayservice;

public EmployeOutput getEmployeInformation(EmployeInput employeInput,AuditInput auditInput)
{
    employeGatewayservice.getEmployeInfomation(employeInput);
}

How can i get auditInput object in my advice .
@Pointcut("execution(* com.study.pattern.sample.app.gateway..*(..))")
     protected void gateWayCalls()
     {

     }

      @After("gateWayCalls()")
      public void logAfter(JoinPoint joinPoint) {
         **// Here i need auditInput Object**
     }

I have limitations on calling the advice method on getEmployeInformation()
because some of the service method contains the not gateways calls logic.
For my case i have to use Aspect on Gateways not on service methods.
I was looking for a solution how to get Caller method arguments in to my spring aop @After advice?

A: Consider to use MethodInterceptor:
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        return invocation.proceed();
    }


text:
Q: change div id by javascript I've created a simple page to change the div id every time I pressed submit. My problem is that this changes from div_top1 -> div_top2, but the second time I press the button, it stops changing :(
<!DOCTYPE html>

This is a paragraph.

<button type="button" onclick="changediv()">Display Date</button>

A: The problem isn't the changing id - it's that you're changing it both ways every time.  You need an if condition.  You should also use .id to change the id instead of setAttribute() - I've had issues with some browsers in the past (many years ago) using setAttribute for id changes.
DEMO: http://jsfiddle.net/x2nPY/
function changediv() {
    if (document.getElementById("div_top1")) {
        document.getElementById("div_top1").innerHTML = Date();
        document.getElementById("div_top1").id = "div_top2";
    } else {
        document.getElementById("div_top2").innerHTML = "teste";
        document.getElementById("div_top2").id = "div_top1";
    }
}

A: Working FIDDLE Demo
Try this:
function changediv()
{

    if (document.getElementById("div_top1")) {
        document.getElementById("div_top1").innerHTML=Date();
        document.getElementById("div_top1").setAttribute("id", "div_top2");
    }
    else {
        document.getElementById("div_top2").innerHTML="teste";
        document.getElementById("div_top2").setAttribute("id", "div_top1");
    }

}

A: You could use if for example if you want to toggle it or change every time you submit like:
function changediv() {
if (document.getElementById("div_top1"))
 {
    document.getElementById("div_top1").innerHTML=Date();
    document.getElementById("div_top1").setAttribute("id", "div_top2");

 }
 else
 {
    document.getElementById("div_top2").innerHTML="teste";
    document.getElementById("div_top2").setAttribute("id", "div_top1");
 }

}

See the Fiddle Demo


text:
Q: Truncating Tables when seeding in Laravel 7 with Laratrust working with Laravel 7 and authenticating system Laratrust 6 and have tried seeding the tables. it has executed with some data tables with data but 3 tables did not seed. users,role_user,permission_user and in my terminal displayed following message  Truncating User, Role and Permission tables. how could I fix this problem?
my DatabaseSeeder.php file is like this
<?php
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
   public function run()
    {

        $this->call(LaratrustSeeder::class);
        }
}

A: You can prevent the tables from truncating by editing your laratust_seeder.php file which is the config folder. Under the 'truncate_tables' section, set the value to false.


text:
Q: Avoid mouseup event when selecting a file from dialog when double clicking I have a input[type="file"] in my web page and when the file dialog is open and I select a file with double clicking the mouseup event is triggered. But if I select the file and then click the Open button to select there is no extra event.
This behavior is specific to Firefox, I tested in Chrome, IE and Opera and there is not extra mouseup event. Also there is no mousedown event, so the log will have two sequential mouseup events.
HTML:
<input type="file" />

JavaScript:
jQuery(document).mouseup(function(e) {
    //...
});

Here is a fiddle where you can see this behavior. To see it in action make sure that the file dialog is over the Result box of the jsfiddle page.
How can I avoid this? Is this a browser bug? Googling didn't come up with any useful results.
Edit: This issue appears on my Firefox (version 32.0.1 on Win7 64bit) but not on Firefox 32.0 in Linux.

A: While looking a bit more into this I realized that this behaviour creates a stray mouseup event that is not fired after a mousedown event.
The fact that a mouseup event is always after a mousedown event is true in all modern browsers. The only case I found not to be true is when there is a double-click event in IE 5-8 (Source).
So, the solution I used was to set a flag that a mousedown event occurs and that the mouseup event will occur the flag should be set to true.
For example:
var mousedown = false;

jQuery(document).mousedown(function (e) {
    mousedown = true;
});

jQuery(document).mouseup(function (e) {
    if (!mousedown) { // Stray mouseup event detected, handle it with
        /*
        e.preventDefault();
        e.stopPropagation();
        */
    }
    mousedown = false;
});

A: I have try your code. I think its difficult without flag value because when double click the file, before releasing second click the menu will close and it will fire 'MouseUp' event.
I have solved it by using flag value. Please see this fiddle.
HTML
<input type="file" id='file1'/>

Java Script
var flag;
$(document).mouseup(function(e) {

    if(e.target.id != 'file1' && flag==1){
        flag = 0;
    }
    else if(e.target.id == 'file1'){
        flag = 1;
        $('#log').prepend('mouseup: ' + (new Date()).toString() + '
');
    }
    else{
        flag = 0;
        $('#log').prepend('mouseup: ' + (new Date()).toString() + '
');
    }
});

$(document).mousedown(function(e) {

    $('#log').prepend('mousedown: ' + (new Date()).toString() + '
');

});

Thank you


text:
Q: AS3: fullscreen mode issue this is my code
function btnClick (e:MouseEvent):void
{
    if (stage.displayState == StageDisplayState.NORMAL)
    {
        stage.displayState = StageDisplayState.FULL_SCREEN;
        bcgr.visible = true;
        function imgZoom (e:MouseEvent):void
        {
            //zooming - code not relevant to my issue
        }
        stage.addEventListener (MouseEvent.MOUSE_WHEEL, imgZoom);
    }
    else
    {
        //option1:  stage.removeEventListener (MouseEvent.MOUSE_WHEEL, imgZoom);
        stage.displayState = StageDisplayState.NORMAL;
        bcgr.visible = false;
        //option2:  stage.removeEventListener (MouseEvent.MOUSE_WHEEL, imgZoom);
    }
}
mybtn.addEventListener (MouseEvent.CLICK, btnClick);

I have two problems in this code that I can't solve.
First of all when I enter the FULL_SCREEN - mode the bcg.visible becomes true and when i exit  FULL_SCREEN - mode by clicking on mybtn the bcg.visible becomes false, but when i exit by hitting escape it doesn't. How to make it work?
And second of all I want't to remove the eventlistener imgZoom when I exit the FULL_SCREEN - mode. But when I place the removeLEventlistener as option1 then turning back to  NORMAL - mode doesn't work, and when I place the removeLEventlistener as option2 then the listener will not remove?
Can anyone help?

A: You can be notified of fullscreen enter/exit events by adding a listener to the Stage: stage.addEventListener(FullScreenEvent.FULL_SCREEN, ...)
Here is a link to the Stage documentation: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Stage.html#event:fullScreen
For the imgZoom issue you need to move the definition outside the btnClick function. The imgZoom variable is local to the btnClick function so it gets redefined each time the function is called. This means the second time you click on the button imgZoom is undefined and you can never remove the previous event listener.
Moving the function definition outside the btnClick handler will let you remove it again later.
Here is everything together:
function imgZoom (e:MouseEvent):void
{
    //zooming - code not relevant to my issue
}

function fullScreenListener (e:FullScreenEvent)
{
    bcgr.visible = e.fullScreen;
    if (e.fullScreen)
    {
        stage.addEventListener (MouseEvent.MOUSE_WHEEL, imgZoom);
    }
    else
    {
        stage.removeEventListener (MouseEvent.MOUSE_WHEEL, imgZoom);
    }
}

function btnClick (e:MouseEvent):void
{
    if (stage.displayState == StageDisplayState.NORMAL)
    {
        stage.displayState = StageDisplayState.FULL_SCREEN;
    }
    else
    {
        stage.displayState = StageDisplayState.NORMAL;
    }
}

stage.addEventListener (FullScreenEvent.FULL_SCREEN, fullScreenListener);
mybtn.addEventListener (MouseEvent.CLICK, btnClick);


text:
Q: How do you mitigate the inherent risk of a one-person team? What steps can one take to mitigate the risk of a one-person team working on a project, especially when that one person is a rather junior programmer?
I ask because I am that junior programmer, and there is no one available/willing to do things like code reviews. Part of the problem, I suppose, is that I am working on web applications in an embedded software company, so most employees' expertise is in a different area.

A: Source control and automated tests are two things that will help in any environment. Those two things alone will mitigate some of the major disasters (lost work, buggy code resulting from constant changes and refactoring).
Beyond that, stick to the basics: K.I.S.S. Keep your code design as simple as possible, keep your classes simple, follow the Single Responsibility Principle and above all, avoid duplication (which will greatly guide your designs). Make use of every resource you have: message boards, other programmers at other companies, friends from school, whatever you have available to you. Even having a mentor you can send e-mail to is helpful.

A: Best practices aren't much different than for a larger group. Source control, unit testing, follow a style guide for your language, script everything instead of using manual processes, and try to have at least some high level documentation and comments in the tricky parts of code. For specific decisions that are important and hard to change, like how your code interacts with the database, try to find out what approach a well-designed project uses, if necessary by checking on this site.
Unit tests especially are a great way for other people to quickly figure out how your code is supposed to behave, and to check whether their changes have broken anything.

A: StackOverflow is full of available and willing people to help solve problems and give advice.
Other than that, be prepared to make mistakes and learn from them.
Oh yeah, and get a copy of Code Complete!

A: Recognising this as a problem is more than most "junior programmers" would be able to do :)
Unfortunately most employers don't see the benefits (only the downsides) in multiple people on the same task.
With lack of understanding from your employer on this point, just stick to all the usual rules, such automated testing, documentation, and source control. I know too well that when working alone on a project, it is all too easy to become complacent.
The truth is that the documentation is not just to help others know what your code does. It helps you too. Source control is not just to enable multiple people to work on a project and merge changes, it helps productivity (in the sense that you can easily revert changes), enforces backups, and gives you good tracking of where your time and effort has been spent.

A: As @MattJ mentioned, the fact that you care enough to try to mitigate that risk implies much more seniority than your current job title purports.
I would say that you should do all of the normal things you do to mitigate risk and, where it's not possible to get another resource, just either do it yourself, or skip that step.
It's the best you can do.


text:
Q: Using Event Callback in a foreach loop in Blazor I don't know if this is a bug, but I'm getting an unexpected behaviour. I get it, when I modify microsoft doc "EventCallback" example.
Shared/Child.razor:

child

    @{
        object obj = new();
    }
    @foreach(var item in DataSource)
    {
        obj = item;
        <button @onclick="() => OnClickCallback(obj)">
            @item
        </button>
    }

@code {
public List<string> DataSource = new List<string>{"cow", "dog", "pig", "rat"};

[Parameter]
public string Title { get; set; }

[Parameter]
public RenderFragment ChildContent { get; set; }

[Parameter]
public Func<object, Task> OnClickCallback { get; set; } = DoNothingAsync;

private static async Task DoNothingAsync(object param)
{
    await Task.CompletedTask;
}

}
Shared/Parent.razor:

    @page "/"
@inject IJSRuntime JS

<PageTitle>Index</PageTitle>

Hello, world!

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<Child @ref="Child">
    Bla bla bla
</Child>

@code{
    private string message;
    private Child Child;

protected async override Task OnAfterRenderAsync(bool firstRender)
{
     Child.OnClickCallback = ShowMessage;
}

private async Task ShowMessage(object str)
{
    await JS.InvokeVoidAsync("alert", (string)str);
}
}

Expected Result: I get a list of buttons with different labels with the following Labels => "cow", "dog", "pig", "rat". And when I click on any of the button, I should get a pop-up alert displaying the label text of the button I clicked.
Actual Result: I get a list of buttons with different labels with the following Labels => "cow", "dog", "pig", "rat". But when I click on the button, I get a pop-up alert displaying "rat" regardless of whatever button I'm clicking.
I don't know, is this a bug? If it is not a bug, how do I get my expected result?

A: This is happening due to variable scoping in lamda expression.
Change
@inject IJSRuntime JS;

@for (var i = 0; i < DataSource.Count; i++)
{
    var local_i = i;
    var local_v = @DataSource[local_i];

       <button
       @onclick="() => OnClickCallback(local_v)">@DataSource[i]
       </button>

}

In codebehind
@code {

public List<string> DataSource = new List<string>{"cow", "dog", "pig", "rat"};

   private async Task OnClickCallback(string s)
   {
   Console.WriteLine(s);
   await JS.InvokeVoidAsync("alert", s);
   }

 }

Proof here
With foreach it can be written like this. See here.
@{ int x = 0;}
@foreach (var data in DataSource)
{
    var local_v = @DataSource[x];

<button
          @onclick="() => OnClickCallback(local_v)">@data</button>

    x++;
}


text:
Q: Hide taxonomy from side panel Does anybody know how to hide a custom taxonomy from under the post type?
I have tried the following.

'public' => false
'show_ui' => false

While I can remove both with the above I cannot remove just the sidebar taxonomy. I want the taxonomy to be available when adding a new post just removed from the sidebar. Any help would be appreciated.

A: Try this..
  register_taxonomy("your-taxonomy", array("your-post-type"), array(
        "hierarchical" => true,
        "label" => "Taxonomy Title",
        "singular_label" => "Taxonomy",
        'show_ui' => false,
        'query_var' => true,
        "rewrite" => array('slug' => 'your-taxonomy')
    ));


text:
Q: adjust bitmap image brightness/contrast using c++ adjust image brightness/contrast using c++ without using any other 3rd party library or dependancy

A: Image brightness is here - use the mean of the RGB values and shift them.
Contrast is here with other languages solutions available as well.

Edit in case the above links die:
The answer given by Jerry Coffin below covers the same topic and has links that still live.
But, to adjust brightness, you add a constant value to each for the R,G,B fields of an image.  Make sure to use saturated math - don't allow values to go below 0 or above the maximum allowed in your bit-depth (8-bits for 24-bit color)
RGB_struct color = GetPixelColor(x, y);
size_t newRed   = truncate(color.red   + brightAdjust);
size_t newGreen = truncate(color.green + brightAdjust);
size_t newBlue  = truncate(color.blue  + brightAdjust);

For contrast, I have taken and slightly modified code from this website:
float factor = (259.0 * (contrast + 255.0)) / (255.0 * (259.0 - contrast));
RGB_struct color = GetPixelColor(x, y);
size_t newRed   = truncate((size_t)(factor * (color.red   - 128) + 128));
size_t newGreen = truncate((size_t)(factor * (color.green - 128) + 128));
size_t newBlue  = truncate((size_t)(factor * (color.blue  - 128) + 128));

Where truncate(int value) makes sure the value stays between 0 and 255 for 8-bit color.  Note that many CPUs have intrinsic functions to do this in a single cycle.
size_t truncate(size_t value)
{
    if(value < 0) return 0;
    if(value > 255) return 255;

    return value;
}

A: Read in the image with a library just as the Independent JPEG library. When you have raw data, you can convert it from RGB to HSL or (preferably) CIE Lab*. Both contrast and brightness will basically just involve adjustments to the L channel -- to adjust brightness, just adjust all the L values up or down by an appropriate amount. To adjust contrast, you basically adjust the difference between a particular value and the center value. You'll generally want to do this non-linearly, so values near the middle of the range are adjusted quite a bit, but values close to the ends or the range aren't affected nearly as much (and any that are at the very ends, aren't changed at all).
Once you've done that, you can convert back to RGB, and then back to a normal format such as JPEG.