Calculating PDF conditioned on event

Question: I'm confused about problems where we calculate a PDF conditioned on an event.
Consider this simple problem:
We have two random variables, X and Y, X is uniformly distributed on [a,b], and Y is uniform on [a,X]. We want to find the PDF of f(x|Y>y').
What's the best approach to calculate this?
An approach that comes to my mind is to define this PDF as the derivative of its CDF:
$$
f(x|Y>y') = \frac{d}{dx}Pr(X<x|Y>y') = \frac{d}{dx}\left[\frac{Pr(X<x,Y>y')}{Pr(Y>y')}\right]=\frac{d}{dx}\left[\frac{\int_{a}^{x}\int_{y'}^{b}{f(x,y)dydx}}{\int_{y'}^{b}{f_{y}(y)dy}}\right]
$$
And we know that:
$$
f(y|x) = \begin{cases}
  \frac{1}{x-a} &a<y<x \\
  0 & \mbox{elsewhere}
  \end{cases}
$$
$$
f(x,y) = f_x(x)*f(y|x) = \begin{cases}
  \frac{1}{(x-a)(b-a)} &a<y<x<b \\
  0 & \mbox{elsewhere}
  \end{cases}
$$
$$
f_y(y) = \begin{cases}
  \int_{y}^{b}\frac{1}{(x-a)(b-a)}dx &a<y \\
  0 & \mbox{elsewhere}
  \end{cases}
$$
Is this approach correct?
Is there a better approach that's more straightforward?
Comment: Two such random variables don't exist.
Comment: I'm wondering whether you might have mis-worded the question. If X and Y are uniformly distributed, this implies their distributions are independent of one and other. That means, given they have the same support, it cannot be true that X is always larger than Y.

I'm wondering whether maybe you meant to ask something like "given that X,Y are distributed in this way, what if we are told X>Y, i.e. what is p(X|X>Y)" ?
Comment: @whuber You are right. I've changed the definition of their distributions. now I think it should make sense
Comment: The best approach, IMHO, is to draw a diagram of the events in question.  The appropriate conditional probabilities are ratios of areas in that diagram.
Comment: @whuber I think we should be more forgiving of the OP's mispunctuation and read the problem as asking
"We have two random variables $X$ and $Y$.  $X$ is uniformly distributed on $[a,b]$, and $Y$ is uniform on $[a,X]$. We want to find $f_{X\mid Y>y}(x\mid Y>y)$."
Comment: @Dilip Yes, that's what the question *now* says.
Answer: Yes, I think your approach is correct.
Perhaps a slightly simpler way to see this would be to note $f_{X|Y}(x|y) = \frac{f_{X,Y}(x,y)}{f_Y(y)}$ and then to integrate $y$ over $(y', b]$.
This would give $\frac{\int_{(y', b]} f_{X,Y}(x,y) dy}{\int_{(y', b]} f_Y(y) dy}= \frac{\int_{y'}^b f_{X,Y}(x,y) dy}{\int_{y'}^b f_Y(y) dy}$ which, by the Fundamental Theorem of Calculus, is the same as the derivative of the CDF you gave.
A side note, whuber suggests that a simple geometric approach could work as well, but I don't see it; could they elaborate?
Comment: Thanks for that link.  And yes, I agree $(X,Y)$ being uniformly distributed is certainly much easier!
Comment: Because $a$ and $b$ just determine location and scale, it suffices to analyze one case, of which the simplest is $a=0,$ $b=1.$ By applying the concepts explained at https://stats.stackexchange.com/a/584907/919 you can immediately see (*in the drawing*) that the conditional density of $x$ is supported on $[y^\prime,1]$ and must be proportional to $(x-y^\prime)/x$ on that interval.  That's an answer right there.  If you need the constant of proportionality, computing the integral is elementary: $\int_{y^\prime}^1(x-y^\prime)/x\,\mathrm dx = 1-y^\prime+y^\prime\log(y^\prime).$
Comment: BTW, the question changed after I posted my original comment.  The first version of the question stated $(X,Y)$ had a uniform distribution.  That's considerably easier to analyze.

Calculating PDF conditioned on event


Does MySQL timestamp take current server time or user?

Question: Does MySQL timestamp take current server time or User,s computer time?
Answer: It takes whatever you give it. If you are using now() when doing an insert, then it's going to use the server's time.
Answer: By default, the current time zone for each connection is the server's time


Get iptables rule from ufw

Question: Using ufw, concerning mDNS, I see:
~> sudo ufw enable
~> sudo iptables -L
ufw-not-local  all  --  anywhere             anywhere
ACCEPT     udp  --  anywhere             mdns.mcast.net       udp dpt:mdns

My understanding is that this rule accepts all incoming IPs.
How to get the corresponding iptables rule, and, limit mDNS connections to local LAN (192.168.XXX.YYY) only?
Answer: If you use ufw, I won't start touching iptables right away.

First list your ufw rules using ufw status numbered
Then delete the mdns rules ufw del number
Then add the mdns rule again with the limit ufw allow mdns in from 192.168.0.1/24

Get iptables rule from ufw


Finding advanced chords for melody

Question: I can find basic chords for most of the "normal" melodies by ear,
but I can't find right "Jazz" chords like 7th chords..(advanced chords).
Well,I'm not bad in chord theory.
What do I need to study in order to find advanced chords for a melody?
Do I need to play more songs ?
Do I need to study counterpoint ?
Comment: While the chosen answer is very good and definitely great advice, I would have included more about chord substitutions based on the way the question is phrased.  This may warrant another question more specifically geared toward using less than obvious chords and maybe changing the wording of this question to be geared toward learning resources.  Modal borrowing and functional replacements come to mind.  The question could also include harmonic language, such as extensions and how they are often not drawn from the scales implied by the key (Maj7 usually Lydian based, Min7 usually Dorian...).
Comment: What do you mean by "finding" chords? Do you mean composing / using them? Do you mean transcribing them? Do you mean arranging them?  More information can be helpful here.
Comment: I mean using them (with my left hand on piano) along side the melody that played using my right hand.
Answer: I'll qualify my answer here by saying I've studied jazz theory more as an improviser than as a composer.
My first thought is that you should study some jazz tunes to learn a bit more about the kinds of harmony that are used. Learning a bit about chords with extensions would be helpful as well, but actually I consider that more a 'stylistic' addition than a really essential one to the core of the music—often as not, Gm, Gm7, Gm9 will mean essentially the same thing: the ii chord of a ii-V-I progression.
You'll find some tunes that can be understood fairly well from a classical standpoint, with the melody following fairly simple progressions (but moving over a variety of keys quickly). The first few bars of Miles Davis's "Solar" is a good example:
    Chords:   Cm        | Gm7   C7 | Fmaj7    | Fm7  Bb7 | Ebmaj7...
    Analysis: i         | ii    V  | I        | ii   V   | I...
    Key:      C minor   | F major  | ...      | Eb major | ...
The movement by ii-V-I is nothing particularly "advanced", and while I've written the chords as they're often notated in jazz, you can understand and hear the harmony just as well ignoring the 7ths and such. Actually playing the tune, I may play the second and third bars as "Gm9 C13 Fmaj69", but all of those chords still come out of F major.
Another example, from Henry Mancini's "Days of Wine and Roses", and is a little trickier:
    Chords:   Fmaj7     | Eb7#11   | Am7      | D7b9     | Gm7...
    Analysis: I         | bVII7    | iii (ii) | VI7 (V7) | ii (i)...
    Key:      F major   | ?        | transitioning to G minor...
So, this one borrows from a sort of progression that's pretty common, namely a kind of walking down of dominant chords to an VI7 chord. In this case, however, Mancini's interposed an Am7 to function as a ii chord, really driving home the transition to Gm.
You'll find this kind of thing (a substitution, it is) done quite a lot in jazz. It's very common with vi chords, both in order to drive one's ear really solidly into the ii chord and to open up some harmonic possibilities. The dominant VI7 can be altered in a whole variety of ways (say, VI7#5, or VI7b9) to expand the possibilities for the improviser or composer.
And now that I look at it a little more deeply, you can even think of that bVII7 as a funky kind of substitution that's also pretty common in jazz, this one called a "tritone substitution". One of the best ways to get into that D7b9 with some style is from a fifth above, which is exactly what happens. But if you wanted to be a little tricky about it, you could substitute for that Am7 a chord a tritone (or diminished fifth or augmented fourth, as it suits you) away or an Eb chord. Here, Mancini's kinda flopped it around from the one to the other, in a way that works really nicely to my mind.
This is particularly common with dominant chords, because that tritone substitution keeps the relationship between the 3rd and the 7th note of the chord intact, simply switching them. In a jazz 12-bar blues type form, you'll hear a whole lot of that happening at the last turnaround. Where some would play a I-vi-ii-V type turnaround, you'll very often hear something like I7-bIII7-II7-bII7, because jazz players love dominant chords and tritones. As you can see, this is the sort of thing that compounds quickly, and for that reason I've offered only the briefest introduction, as there are indeed whole books written on the subject.
At any rate, if you fully analyze the melody to this tune, you'll find that Mancini hits chord tones really hard. In my mind, the melody follows the chords rather than the other way around. Now, his arrangement does some other cool things, and most jazz players will "stretch" the harmony around in other ways but the basic understanding, I think, comes from study of historical progressions like these and others.
If you really want to get serious about learning jazz theory, I'd recommend Mark Levine's most excellent jazz theory book, "The Jazz Theory Book". It's very much geared toward the performing and improvising musician, but it covers a lot of the weird progressions and substitutions that you may want to use in your compositions. I'd also get a good fake book (I use the Hal Leonard "Real Book" series a lot, and Sher Music's "New Real Books" are also very good) and pick as many of those tunes apart as you can until you start to understand some of the twists and turns a little better.
Answer: Look at the lead sheets for the melody and see what notes are being played with the chord. This can give you an idea of how advanced chords are built. If you are seeing complex chords with 9, 11, 13 extensions it is more than likely that the melody note is the 9,11,13 of that chord. For example a melody note Ab over G7 would then give you a G7b9 harmony.
Answer: What you should practice is ... 7th chords. Since you can figure out the basic chords, I guess you have studied them, right? Do the same thing with 7th chords. Start playing them or listening to them (on some software) and you'll eventually get used to them. Then you'll be able to find them.
In jazz, the majority of chords contains a 7th, so you could mess around with normal chords and normal chord progressions, like IV - V - I (or in a more jazzy way II- V - I) and then add the 7ths.
It would be good to take a simple jazz song like "Autumn Leaves" and "Blue Trane" both of which have simple harmony. It might help you with the 7th chords

Finding advanced chords for melody


Changing WebControl ID Inside of a Repeater

Question: <ItemTemplate>
    <asp:Label runat="server"><%#DataBinder.Eval(Container.DataItem, "Question")%></asp:Label>
    <asp:DropDownList runat="server" id="<%#DataBinder.Eval(Container.DataItem, "QuestionID")%>">>
        <asp:ListItem value="1" text="Yes" />
        <asp:ListItem value="0" text="No" />
    </asp:DropDownList>
<ItemTemplate>

This is roughly what I'm trying to do. Obviously, the implementation is faulty, but I can't find any information on how I'd go about this in practice. Any help is appreciated.
Edit: What I'm trying to do exactly is add a DropDownList for each item in this Repeater, and upon submission of the form, use the ID's of each Yes/No answer to input into a database. The SqlDataReader that I'm using has two fields: The question content and the questionID.
Comment: You can't give a control a dynamic ID like this. Tell us what it is you're trying to do (why does it need a dynamic ID?) and we can answer that. Cheers
Answer: I think you'd be better off using the built in support for IDs inside a Repeater.  If the goal is to assign it an ID to make it easy to find the proper control after the data has been bound you might try something like this:
<asp:Repeater ID="Repeater1" runat="server>
    <ItemTemplate>
        <asp:Label ID="QuestionID" Visible="False" Runat="server"><%#DataBinder.Eval(Container.DataItem, "FieldContent")%></asp:Label>
        <asp:DropDownList ID="MyDropDownList" Runat="server"></asp:DropDownList>
    </ItemTemplate>
</asp:Repeater>

Then, in your code you can loop through the items in the Repeater until you find the label you're looking for:
foreach (RepeaterItem curItem in Repeater1.Items)
{
    // Due to the way a Repeater works, these two controls are linked together.  The questionID
    // label that is found is in the same RepeaterItem as the DropDownList (and any other controls
    // you might find using curRow.FindControl)
    var questionID = curRow.FindControl("QuestionID") as Label;
    var myDropDownList = curRow.FindControl("MyDropDownList") as DropDownList;
}

A Repeater basically consists of a collection of RepeaterItems.  The RepeaterItems are specified using the ItemTemplate tag.  Each RepeaterItem has its own set of controls that are, by the very nature of a Repeater, associated with each other.
Say you're pulling the Repeater data from a database.  Each Repeater item represents data from an individual row in the query results.  So if you assign the QuestionID to a label and the QuestionName to a DropDownList, the ID in the label would match up with the name in drop down.
Comment: I need to set the ID to each record's QuestionID when the form is loaded so that I can use those ID's and corresponding values in a sproc.
Comment: That's simple enough.  If you assign each label/textbox/etc an ID and add the QuestionID as a hidden label you can then use RepeaterItem's FindControl method to access those controls.
Comment: Okay, I'll have to read more on FindControl right now. I'm trying to understand how I would then go about associating the hidden label's ID with the associated DropDownList.
Comment: I've edited my answer to try and better answer your question.
Answer: Could you remove the control from the markup file, and hook the repeater's onItemDataBound event.  In that event, you should be able to create the dropdown control "manually", assigning whatever ID you want.


If statements in twig

Question: I've got the following card in my drupal installation, I've hidden unnecessary items for my question in the picture.
What I want to achieve is the following:
I want the icon to change based on the taxonomy term showed besides the little icon (in this case, test).

This is the code that generates the card:
{% if topic_type %}
  {% embed "node--teaser__field.html.twig" %}
    {%- block field_icon -%} group {%- endblock -%}
    {%- block field_value -%} {{ topic_type }} {%- endblock -%}
  {% endembed %}
{% endif %}

I think it should look something like this but it gives me an error:
{% if topic_type %}
  {% embed "node--teaser__field.html.twig" %}
    {% if topic_type == 'test' %}
      {%- block field_icon -%} icon 1 {%- endblock -%}
    {% else %}
      {%- block field_icon -%} icon 2 {%- endblock -%}
    {% endif%}
    {%- block field_value -%} {{ topic_type }} {%- endblock -%}
  {% endembed %}
{% endif %}

Answer: Twig blocks are named control structures, you can't define them multiple times within the same scope. Either try to move the if statement inside one single block
{% if topic_type %}
  {% embed "node--teaser__field.html.twig" %}
    {%- block field_icon -%}
      {% if topic_type == 'test' %}
        icon 1
      {% else %}
        icon 2
      {% endif%}
    {%- endblock -%}
    {%- block field_value -%} {{ topic_type }} {%- endblock -%}
  {% endembed %}
{% endif %}

or don't overwrite the block at all, instead use variables and pass them down in the embed statement
{% set custom_icon = (topic_type == 'test' ? 'icon1' : 'icon2') %}
{% embed "node--teaser__field.html.twig" with {'icon': custom_icon, 'title': topic_type } %}

I'd recommend the first when there are major overwrites in the HTML output, and the 2nd when only strings/variables/placeholders are replaced.
Comment: Step one has gotten me closer as it accepts the if statement now. Thankyou. Now to figure out why it ignores the if and only takes the else.

If statements in twig


Upload Image in system_theme_settings form using Zen on Domain Access System

Question: I want to upload the image as the background in the settings page of the zen theme.
In zen , It's easy to add an extra field in the theme-settings.php and it's worked at the single site system.
However,I want to add this feature to the domain access Website.
And I got some error message.
I just write the code as belowed:
$form['background_file'] = array(
    '#type'     => 'managed_file',
    '#title'    => t('Background'),
    '#required' => True,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('background_file'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  );

picture above appeared correct.
But when i push the upload button.
I got the error message belowed

Notice: Undefined index: system_theme_settings in drupal_retrieve_form() (line 806 of /Library/WebServer/Documents/official/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'system_theme_settings' not found or invalid function name in drupal_retrieve_form() (line 841 of /Library/WebServer/Documents/official/includes/form.inc).
Notice: Undefined index: var in variable_realm_form_system_theme_settings_alter() (line 618 of /Library/WebServer/Documents/official/sites/all/modules/variable/variable_realm/variable_realm.module).
Notice: Undefined index: background_file in file_ajax_upload() (line 271 of /Library/WebServer/Documents/official/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /Library/WebServer/Documents/official/modules/file/file.module).

and i really don't know how to fix that.
I just referenced the content below and i can't find the answer.

https://stackoverflow.com/questions/7739345/drupal-7-retain-file-upload
https://stackoverflow.com/questions/11515221/is-there-a-proper-drupal-7-form-api-managed-file-tutorial
http://www.rahulsingla.com/blog/2011/06/drupal-7-handling-file-uploads-and-moving-files-to-the-public-file-system
Is there a way to add managed_file field to theme-settings.php?

Does someone fixed this situation before?
thanks a lot.
Comment: Working fine for me.. Where are you adding the code i mean in which file?
Comment: Looks like theme-settings.php
Comment: dammit! - works for me too. What is your Domain Access configuration looking like ?
Comment: Do you get these errors when you save the form without trying to upload an image ?
Answer: The form needs to be able to find system_theme_settings() when getting rebuilt via ajax.
form_load_include($form_state, 'inc', 'system', 'system.admin'); inside of theme-settings.php hook_form_system_theme_settings_alter() should do the trick.
Answer: $form['theme_extra']=array(
    '#type'         => 'fieldset',
    '#title'        => 'Extra Image',
    '#description'  => 'Image Fieldset',
    '#collapsible'  => TRUE,
    '#collapsed'    => FALSE,
    '#weight'       => -10,
  );
$form['theme_extra']['background_file']=array(
        '#type'     => 'managed_file',
        '#title'    => 'test title',
        '#description' => 'description',
        '#required' => FALSE,
        '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
        '#default_value' => theme_get_setting('background_file'),
        '#upload_validators' => array(
          'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
      );

This code !!
Comment: This is the actual answer... great job.


Calculating the tangent space to a hyperboloid

Question: Guillemin-Pollack 1.2.8:

What is the tangent space to the hyperboloid defined by $x^2+y^2-z^2=a$ at $(\sqrt a,0,0)$, where $a>0$?

Is there a way to compute it using Characterization of the tangent space in terms of velocity vectors? I cannot apply the usual definition of Guillemin and Pollack because I don't know how exactly to parametrize a point with $z=0$ on the hyperboloid (see Hyperboloid is a manifold)
Comment: Thanks for your answer! Yes, I have some questions but haven't been able to formulate them yet since some of them are lengthy. Probably I'll do that some time in the future. I've accepted your answer though.
Comment: Do you have questions to my answer below?
Answer: You can calculate the tangent space via the inverse of a function that defines your hyperboloid.
Let $f:\mathbb{R}^3\rightarrow \mathbb{R}$ be defined by $f(x,y,z):=x^2+y^2-z^2-a$. Then
    \begin{equation*}
  \begin{split}
   & df = (2x,2y,-2z),
  \end{split}
\end{equation*}
    which is isomorphic to a basis vector of $T_{f(x)}(\mathbb{R})\simeq \mathbb{R}$
    if any of the $x,y,z$ are non-zero. This must be the case for
    $f(x,y,z)=0$, so by the preimage theorem
    $H:=f^{-1}(0)$ defines the manifold of the
    hyperboloid.
Now because $df_x^{-1}(0)=T_x(f^{-1}(0))$, we can obtain the tangent space $T_x(H)$ by looking for all vectors $v$ for which $df_x(v)=0$. On $f^{-1}(0)$, we have the condition
    $z=\sqrt{x^2+y^2-a}$, so
    \begin{equation*}
  df_x(v)=
  \begin{pmatrix}
    2x\\
    2y\\
   - 2\sqrt{x^2+y^2-a}
  \end{pmatrix}
  \begin{pmatrix}
    v_1\\
    v_2\\
    v_3
  \end{pmatrix} =
  2(xv_1+yv_2-\sqrt{x^2+y^2-a}v_3)
\end{equation*}
    This is zero if $v_1 = (\sqrt{x^2+y^2-a}~v_3-yv_2)/x$ (and if one wants the tangent space at $x=0$, then one must choose other combinations like $v_3=(xv_1+yv_2)/\sqrt{x^2+y^2-a}$ etc), so the tangent space is two-dimensional, depends
    on $x,y,z$ and is given (except at $x=0$) by
\begin{equation}
   T_{x,y,z}(H)=\left\{(v_1,v_2,v_3)~|~v_2,v_3\in\mathbb{R},~v_1=(\sqrt{x^2+y^2-a}~v_3-yv_2)/x\right\}.
\end{equation}
    In particular, like the whole space, it is only defined for $x^2+y^2\ge a$.
At the point $x=(\sqrt{a},0,0)$, the tangent space is thus
\begin{equation}
   T_{\sqrt{a},0,0}(H)=\left\{(v_1,v_2,v_3)~|~v_2,v_3\in\mathbb{R},~v_1=0\right\}\simeq \mathbb{R}^2.
\end{equation}


send post data in jsf

Question: I just cannot figure this out, it looks really simple but I'm relatively new at jsf.
Here is the old stuff:
Plain old html form tag like this:
<form name="someForm" action="somewhere" method="post">
   <input name="param1"/>
   <input name="param2" />
</form

That is sending data by post to a location specified in the action attribute of the form.
The new stuff:
<h:form id="paymentForm">
<h:panelGroup>
    <h:inputText id="param1" value="#{facesView.param1}" ></h:inputText>
    <h:inputText id="param1" value="#{facesView.param2}" ></h:inputText>
    <h:panelGroup>
    <h:commandLink>Submit</h:commandLink>
</h:panelGroup>
</h:form>

This other new stuff doesn't work.
1.How do I specify to this h:form where to go(like setting action in old html) because I need it to go to a totally new url.
2.how to pass params with POST?
Any help is appreciated.
Milos
Comment: With "totally new URL", do you mean an URL outside your webapp context? If so, what exactly do you want to do? Do you want to submit directly to this URL, or to act for a proxy?
Comment: Yes, to a URL outside webapp context(another web application to be precise).
I want to submit to this URL and send data by post, like the old stuff I mentioned above, just that there is www.somewhere.com/some.jsp(some.action, some.faces, whatever) in the action attribute of form, didn't write it though.
Comment: Bozho already answered it. Sorry, no other nice jsfish ways. It's in fact also not needed, you're not interested in the data nor action.
Comment: Thanks a lot BalusC!
I supposed so when I read your article "Communications in JSF" and figured that there is no nice jsf way, yet I decided to ask a question.
At least I have some solution. Thanks again!
Answer: If you want to submit a form to a URL where it will be handled by you (or someone else) manually, then you can still use the "old stuff" with JSF and have the form submitted. That way you will lose the ability to bind the values of the inputs to properties of managed bean.
Otherwise you can't choose the URL to submit to and at the same time use the bindings - in order to get the JSF functionality you have to submit to the JSF servlet, which in turn to handle everything.
Comment: That's exactly what I did to make the thing work(and it's working).
But I don't like it because of losing the binding to managed bean and I'm searching for a diferrent solution(if it exists :)). Thanks.
Comment: Me too looking to bind managed bean property with hidden inputs (params) of submitted plain vanilla form (POST request in my case).

send post data in jsf


Proof that $\langle[\hat{H},\hat{O}]\rangle=0$

Question: How can I show that for a particle in an infinite square well in a stationary state, that the expectation value $\langle[\hat{H},\hat{O}]\rangle=0$ where $\hat{H}$ is the Hamiltonian operator and $\hat{O}$ is an arbitrary operator?
Answer:
The stationary states may have even or odd symmetry. If $\hat{O}$ is a unitary operator representing some symmetry, then it can be said that $\hat{H}$ is invariant under that symmetry provided that the Hamiltonian is invariant under conjugation by $\hat{O}$, i.e.
  \begin{align}
  \hat{O}^{-1} \hat{H} \hat{O} = \hat{H}.
\end{align}
  This condition can also be written as $[\hat{H},\hat{O}]=0$.

This question would be better answered on http://www.physics.stackexchange.com.
Here are the reference and one other link which pose a similar question:
https://physics.stackexchange.com/questions/79296/simple-quantum-mechanics-question-about-the-commutator-of-translation-operators
https://physics.stackexchange.com/questions/5353/symmetric-potential-and-the-commutator-of-parity-and-hamiltonian


VueJS decrypting values using CyptoJS gives error "Decryption failed TypeError: Cannot read properties of undefined (reading '0')"

Question: I have a Laravel backend that uses Crypt::encrypString to encrypt data before saving it in the database like:
$message = new WA_Message;
$message->content = Crypt::encryptString($received_message);
$message->is_business_message = false;
$message->conversation_id = $conversation->id;
$message->save();

When I call it in the frontend and want to decrypt it to render it it gives me the following error:
Decryption failed TypeError: Cannot read properties of undefined (reading '0')
    at Object.xorBlock (crypto-js.js?v=3aa22fc9:2402:41)

As the key I copied the Laravel appkey after base64: and put it in the .env of the Vuejs app to test.
Vuejs
decryptedMessage() {
    try {
        const decrypted = CryptoJS.AES.decrypt(this.message.content, CryptoJS.enc.Base64.parse(import.meta.env.VITE_LARAVEL_APP_KEY));
        const stringDecrypted = decrypted.toString(CryptoJS.enc.Utf8);
        return stringDecrypted;
    } catch (error) {
        console.error('Decryption failed', error);
        return '';
    }
},

The text that was encrypted: bzbz .
The ciphertext: eyJpdiI6Im94UU5zZ1hLQk5ySkw5Z21lZnExYVE9PSIsInZhbHVlIjoiK1RTOFNEeXY5Q0U0Slh2ZmpUUEMrZz09IiwibWFjIjoiYTM1NzVkNjg2MDliZDI0MDUwNDljMzM5OTlhNDNjNWVkMTI1NmIwNTA4YTI2YzA2NWU4MmZjYzgzMjAxMGYyMCIsInRhZyI6IiJ9
The key: base64:G3EfLG42xzqWAH1PuoZ72mUTJ1bC8EJMzx+1jqa7/m0=
Comment: @Topaco like this?
Comment: Post complete (non-productive) test data: Plaintext and key used for encryption in the Laravel backend, and resulting ciphertext.
Answer: The following can be deduced from the Laravel code and confirmed with your test data:
The ciphertext is encrypted with AES in CBC mode with PKCS#7 padding. For authentication, an HMAC/SHA256 is generated from the concatenation of IV and ciphertext with the encryption key.
The encryption data is stored as JSON with the properties value (actual ciphertext), iv (IV), mac (HMAC/SHA256) and tag (AEAD tag, only relevant for AEAD ciphers such as GCM, not used here).
For decryption, the ciphertext, IV and HMAC/SHA256 must first be determined from the JSON, then the authentication is performed and, if authentication is successful, the actual decryption. A possible implementation with CryptoJS is:

var keyWA = CryptoJS.enc.Base64.parse('G3EfLG42xzqWAH1PuoZ72mUTJ1bC8EJMzx+1jqa7/m0=')
var ciphertextB64 = 'eyJpdiI6Im94UU5zZ1hLQk5ySkw5Z21lZnExYVE9PSIsInZhbHVlIjoiK1RTOFNEeXY5Q0U0Slh2ZmpUUEMrZz09IiwibWFjIjoiYTM1NzVkNjg2MDliZDI0MDUwNDljMzM5OTlhNDNjNWVkMTI1NmIwNTA4YTI2YzA2NWU4MmZjYzgzMjAxMGYyMCIsInRhZyI6IiJ9'

// Get JSON with encryption data (cihertext, iv, mac)
var ciphertextWA = CryptoJS.enc.Base64.parse(ciphertextB64)
var ciphertextJsonStr = ciphertextWA.toString(CryptoJS.enc.Utf8)
var ciphertextJson = JSON.parse(ciphertextJsonStr)
console.log("JSON:", ciphertextJson)

// authenticate IV and ciphertext
var ivValueWA = CryptoJS.enc.Utf8.parse(ciphertextJson.iv + ciphertextJson.value);
var hmacIvValueWA = CryptoJS.HmacSHA256(ivValueWA, keyWA);
if (ciphertextJson.mac === hmacIvValueWA.toString()){

    // authentication succeeded: decrypt data
    var ivWA = CryptoJS.enc.Base64.parse(ciphertextJson.iv);
    var decryptedDataWA = CryptoJS.AES.decrypt(ciphertextJson.value, keyWA, {iv: ivWA})
    console.log("Decrypted data:", decryptedDataWA.toString(CryptoJS.enc.Utf8))
} else {

    // authentication failed: data integrity compromised, therefore no decryption
    console.log('decryption failed...')
}

The code successfully decrypts the ciphertext you posted with the corresponding key.

Note that CryptoJS has been discontinued. The latest version is 4.2.0.


Drupal 7 - How to show an upcoming event from site 1 on site 2?

Question: For Drupal 7, Is it possible to show an upcoming event from site A on site B's block?
Also, is it possible to show an upcoming event by category? For example, I wanna have an upcoming event for swimming class and an upcoming event for hiking group. However, they are all in one same calendar.
Thanks,
HL
Answer: You can use Shared Blocks, it has both drupal 6 and 7 stable releases:
<code>If you have a main site with blocks that you want to syndicate across several
other websites, you need this module!

Features:

Allows publishing and subscribing of Drupal blocks
Changes to published blocks are updated on sites with subscription blocks
Published blocks provides a JSON endpoint at sharedblocks/{module}/{delta}
Block subscriptions are updated on cron with an adjustable refresh interval
</code>
Answer: You can use Remote blocks module. to display 'site A' data on 'site B'. For more info go through the module documentation.
On 'site A' create a view having filter event date is greater than current date.You can also apply category filtration as per your requirement.
Comment: Ty Rupesh, but the Remote Block only available for drupal 6 :(
Comment: @H-L Why are you not mentioned Drupal version in question ?
Comment: Sorry Rupesh, I will edit my question now.


Prokofiev, Dance of the Knights, Measure 17

Question:
Heard Evgeny Kissin play Dance of the Knights on YouTube. Would like to purchase the version I heard. Purchased two sheet music versions, then discovered that there are many versions on the internet.
Question 1: How do I find/buy the version Evgeny Kissin played? (After some research discovered a YouTube video entitled Op. 75 included this performance. But the sheet music suppliers don't seem to reference Op. 75, etc.
Question 2: Which of the versions in the attached images is the "correct one?"
Question 3: Specifically, which bass clef version in the images is correct and how do I play it? Do I need to use my left hand AND right hand for the notes in the bass clef?
Answer: The MIT version is what Kissin is playing: Prokofiev's arrangement of one of the pieces from his ballet Romeo and Juliet. After composing the ballet, Prokofiev arranged 10 of the pieces for piano ("10 Pieces from Romeo and Juliet") and published it as his Op. 75. The Knight's Dance is No. 6 from that collection (i.e., Op. 75, no. 6).
The bracket next to the upper two notes in the left-hand part means to play those with the right hand. (See What does the L-shaped symbol attached to C5 and G4 on the top staff mean?)
A Google search for "Prokofiev 75 6" will give you various editions of Prokofiev's arrangement.
Comment: Hi Aaron, Thank you very much.  This is super helpful.


How to hide revisions tab in quiz module?

Question: I am using quiz module in one of my project.
The module seems to be excellent and it satisfies all my need.. thanks to the development team... http://drupal.org/project/quiz
In the mean time i need to do one additional task. And i am struggling  with it..
There is a tab called "Revisions" which will be enabled when some updates are done.
According to my criteria the "Revisions" tab should be hidden always... Is there any way to do this...
Thanks in advance..
Answer: It is provided by the Diff module: Disable the new check-box on workflow settings, "Enable revisions page."
Answer: use the hook_menu_alter() function to disable the  tab:
function {MODULENAME}_menu_alter(&$items){
  $items['player/score']['type'] = MENU_CALLBACK;
}


Snake game setting up fruit spots

Question: So I'm making a snake game, I have the controls, and basic gui.
The problem is that when trying to paint the fruit, it won't stop painting. What I want it to do is when the player collides with the fruit it adds score. To do that I need the fruit first to only paint once, how?
Basic paintComponent.
public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.RED);
        g.fillRect(x, y, 20, 20);
        g.drawRect(fruit.getXLoc(), fruit.getYLoc(), 10, 10);
        fruitCollected(); //method saying if you go into a certain range of the fruit add score;
        g.drawString("Score: " + score + fruit.getXLoc() + fruit.getYLoc(), 150, 150);
        if(gameover() == true) {
            this.setBackground(Color.ORANGE);
        }

}

In another class I have the getXLoc and getXLoc
public class FruitLocation {
int xSize = 580; //x and y boundary for placing fruit
int ySize = 350;
int xLoc;
int yLoc;
    public int getXLoc() {
    int xLoc = (int) (Math.random() * xSize) ;
    return xLoc;
}
public int getYLoc() {
    int yLoc = (int) (Math.random() * ySize);
    return yLoc;
}

}
Comment: Are you clearing the screen before you draw each time?
Comment: I'm pretty sure that's not the problem, it the "fruit square" just keeps moving to the random places, its not a screen clearing problem
Answer: The reason it's jumping is because you're drawing the rectangle using the getXLoc and getYLoc methods. These methods, however, generate a new random number each time. Instead, set the x and y locations to a value in the Fruitlocation constructor, and make a new method that generates new random values. The code for getXLoc should look as follows:
public int getXLoc(){
    return xLoc;
}

Answer: Your basic problem is you calling methods within the paint method that will cause a repaint event to be generated, again and again and...
Start by removing the calls to setBackground
Next, don't change the state of the fruit outside of the "main-loop", that is, don't do...
public int getXLoc() {
   int xLoc = (int) (Math.random() * xSize) ;
   return xLoc;
}

Because a paint cycle may be caused by any number of reasons, many of which you don't control, you want these methods to return a concrete value.  They should be update as part of your "main-loop" logic and you will need to supply appropriate methods to allow this to occur.
On a side note, you shadowing your variables.  What I mean is, when you can the xLoc value in the getXLoc method, it is not changing the xLoc instance variable of the Fruit class, for example...
int xLoc;
public int getXLoc() {
    int xLoc = (int) (Math.random() * xSize) ;
    ^--- Shadowing the instance variable...
    return xLoc;
}

Comment: Ok so how would you get new "cords" everytime a action occurs?
Comment: @ImGone98 This will depend on how you are updating your view, but we don't have enough to go on to know how this is done.  Painting does just that, it paints the view, it should not be used to modify the state of the model
Comment: I got it, it initiates the cords with just plain variables then when the player collides with the fruit it "recreates" those variables with random cords and any time the player collides it recreates the cords. Thank you, sometimes it just takes trying to think about things like this in different ways.

Snake game setting up fruit spots


get screen size for iphone 6 simulator incorrect

Question: I am working on a very old Iphone App, which we recently migrated to iOS 8. We are using
CGRect screenBounds = [[UIScreen mainScreen] applicationFrame];

To get screen size but for iphone 6 simulator it is returning 568x320 for landscape mode.We have 3 launch images Default, Default - 568h and Default. Can somebody please let me the naming convention for adding a new launch image for Iphone 6.
Answer: Below code may be helpful to you.
CGRect rect=[[UIScreen mainScreen] bounds];

It will return you proper size.
And Splash screen Name is :
iphone 4/4s : firstname.lastname@example.com
iphone 5/5s : email@example.com
iphone 6    : firstname.lastname@example.com
iphone 6plus:firstname.lastname@example.com

Comment: But How do I add these splash images for iphone 6 and above?
Comment: You get this from  Project->Target->App Icons and Launch Image->Lauch Image Source.
Another path is:
Images.xcassets->Luach Image
Answer: If you use an asset catalog for your launch images the full set of sizes are enumerated for you, and you don't have to worry about file naming conventions.
Comment: You could also use a launch xib for newer devices.
Comment: I tried to add the splash image to asset catalogs but still it was giving incorrect size, then I deleted the asset catalog, but size was still incorrect. Is there any other way to add the splash screens to project in xcode 6?
Comment: In the project's setting you need to make sure that the Launch Image is set to the one you've made correctly.


Detect Background Script Unload

Question: For my chrome and firefox extension, I need a way to figure if the background script has unloaded or is unloading. Is there an event fired when this happens? I went through multiple links on stackoverflow and even some official chromium bug links but could not find a concrete answer. beforeunload is not supported for background scripts and closing the windows does not guarantee that browser is closed cause if extension has "background" permission, the background script would still be running in background. What can I do now?
Answer: The closest there is is chrome.runtime.onSuspend, but there is no guarantee how much time you're allowed before the context shuts down. Note that this is not supported in WebExtensions as of yet. The documentation expressly states:

Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete.

In general, you can't do much on event/background page unload and should make your code robust to abrupt unloads. This event may even not trigger for some shutdowns.
Comment: You basically can't. There is no event that the browser will wait for before shutting down. You should dump the data into the storage on a regular basis to have an up-to-date snapshot.
Comment: No, I would suggest queueing a `storage.set` when your data changes. And be tolerant of loss of small chunk of data anyway since, again, no operation is guaranteed to finish before shutdown.
Comment: chrome.runtime.onSuspend is for event pages and I am not using that. I am using a persistent one. Lets consider a situation. There is some data in-memory pertaining extension and user shuts down chrome in any of the possible ways. Now, before chrome is actually shut down I want to save that data to local storage, how can I do that?
Comment: Yes but then about the edge case. The last piece of data which could not be dumped because the interval had not elapsed and chrome was already shut down. I guess you will now suggest having an interval as small as 1 sec?
Comment: The best Chrome's got is chrome.tabs.onRemoved

Detect Background Script Unload


script to change drive mapping

Question: I plan on retiring an old file server. I noticed some of my users have mapped about 10-15 "Mapped Network Drive" to this server. Is there a script I can use to change the server name in the mappings?...in order to avoid them deleting and re-creating the mapped drives?
Answer: Do you run Active Directory? If so, you could just set up a logon script. Otherwise I think you're going to be doing it by hand.
Comment: For the needs, I think this is the best way to map all drives. GPOs could also be a really good alternative but the login script can be easier to make... Not that much but that's my #1 choice.
Answer: Use the opportunity to 'Retire' mapped network drives.  Think of other ways of acheiving the same results e.g. Group Policies.
Comment: I'm in agreement with this one. If you (IT) didn't map the drives originally, they I'd say you aren't responsible for the users self-made drive mappings. Just give them fair warning, and tell them how to fix it themselves later.
Answer: this is the basic layout i use in all my domains for login scripts.  i would note the
WshShell.Run "net use z: /delete", 0, False

lines... possibly make logon script that simply goes h-z deleting mapped drives and then have it map the proper ones(if any).
this is much simpler in batch script at logon by just using
net use x: /delete
net use x: \\server\share

i know this script is big, but it comes in handy when setting printers/drives/etc for security groups in ad.
Option Explicit
Const ADS_PROPERTY_APPEND = 3        'sets the variable to Append
Const ADS_UF_NORMAL_ACCOUNT = 512
Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D
CONST HKEY_LOCAL_MACHINE = &H80000002
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Dim WshShell : Set WshShell = CreateObject("wscript.shell")
Dim strContainer, strUser, i, objRootDSE, strDisplayName, ObjFSO, objInFile, objContainer, strLine, strName, objOU, objGroup, objUser, objFile, objFile2, varDomainNC, objRoot, strText, FirstLine, arrMemberOf, Group, strFirstName, strLastName, strLine2, objOU2, objNetwork, strGroup, objConnection, objCommand, objRecordSet, objErrorLog, strComputer, colItems, objWMIService, colInstalledPrinters, strComputer2
Set objOU2 = GetObject("LDAP://CN=users,DC=arra,DC=local")
Set objOU = GetObject("LDAP://OU=arra-users,DC=arra,DC=local")
ObjOU.Filter= Array("user")
Set objGroup = objOU2.Getobject("group", "cn=CSRs")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork  = WScript.CreateObject("Wscript.Network")
Set objRootDSE = GetObject("LDAP://rootDSE")
strComputer2 = "."
Dim CRLF
CRLF = Chr(13) & Chr(10)

'*************(Global Scripting) this section applies to all computers no matter what group users are in.

''default lockheed banner script
Function Ask(strAction)

    Dim intButton
    intButton = MsgBox(strAction,                   _
                       vbQuestion + vbYesNo,        _
                       L_Welcome_MsgBox_Title_Text )
    Ask = intButton = vbYes

End Function

MsgBox "This system is the property of this Corporation, and is intended for" & CRLF &   _
       "the use of authorized users only. All activities of individuals using this computer" & CRLF &   _
       "with or without authority, or in excess of their authority, may be monitored and recorded" & CRLF &   _
       "by system personnel. If any such monitoring reveals evidence of criminal activity or is in" & CRLF &   _
       "violation of foreign or U.S. state or federal law, such evidence may be provided to law" & CRLF &   _
       "enforcement officials and/or used for further legal action by this Corporation and/or the" & CRLF &   _
       "organization's Information Protection group. Unauthorized use of this system is prohibited" & CRLF &   _
       "and may result in revocation of access, disciplinary action and/or legal action. The" & CRLF &   _
       "company reserves the right to monitor and review user activity, files and electronic messages." & CRLF &   _
       "REMINDER: Information transmitted to a foreign person on this network may be subject " & CRLF &   _
       "to applicable Export Control laws. Contact your Export Coordinator for assistance." & CRLF &   _
       "(This machine is not authorized for classified processing)",   _
       vbOKOnly,   _
       "SYSTEM USE MONITORING NOTICE - IPM-003 Banner Statement"

'*************End of global scripting

''pull local computer name for loggin info.
strComputer = objNetwork.ComputerName

''pull logon id
strUser = objNetwork.UserName

''turn logon id into container name for LDAP queries

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.CommandText = "<LDAP://" & objRootDSE.get("defaultNamingContext") & _
        ">;(&(objectCategory=User)(samAccountName=" & strUser & "));name;subtree"
Set objRecordSet = objCommand.Execute
On Error Resume Next
strUser = objRecordSet.Fields("name")
On Error GoTo 0
objConnection.Close
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing

''set user to have LDAP queries run
Set objUser = GetObject("LDAP://cn=" & strUser & ",ou=arra-users,dc=arra,dc=local")

''\/\/\/\/\/\/Determine Group memberships.  PLEASE NOTE:  group names must be in UPPER case and the "Left(strGroup, X)"
'    X must be the number of characters in the group name.
'\/\/\/\/\/\/\/

arrMemberOf = objUser.GetEx("memberOf")

If Err.Number <>  E_ADS_PROPERTY_NOT_FOUND Then
 For Each Group in arrMemberOf
  strGroup = UCase(Group)
  strGroup = Right(strGroup, Len(strGroup) - 3)
  If Left(strGroup, 2) = "IT" Then
  '*****IT group scripting

  ''set Z:IT drive
  WshShell.Run "net use z: /delete", 0, False
  WshShell.Run "Net use z: \\indarradc04\it", 0, False

  ''Prepare to set printers
  Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

  ''This prevents script from stopping when mapping network printers on the server where they
  ''are shared from
  ON ERROR RESUME NEXT

  ''Add Printers
  objNetwork.AddWindowsPrinterConnection("\\indarradc03\Xerox WorkCentre 5675 PS")

  '*****End of IT
  Else
   If Left(strGroup, 4) = "CSRS" Then
   '*****CSR group scripting

   '*****End of CSR
   Else
    If Left(strGroup, 10) = "MANAGEMENT" Then
    '*****Management group scripting - NOTE: all managers are members of "Team Leads" group

    '*****End of Management
    Else
     If Left(strGroup, 10) = "TEAM LEADS" Then
     '*****Team Lead scripting

      ''Prepare to set printers
      Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

      ''This prevents script from stopping when mapping network printers on the server
      ''where they are shared from
      ON ERROR RESUME NEXT

      ''Add Printers
      objNetwork.AddWindowsPrinterConnection("\\indarradc03\Xerox WorkCentre 5675 PS")

     '*****End of Team Lead
     End If
    End If
   End If
  End If
 Next
Else
 '*****Create Error Log if groups could not be determined

 Set objErrorLog = objFSO.OpenTextFile("\\indarradc04\errors\signonerrors.txt", ForAppending, True)
 objErrorLog.WriteLine strUser & " on " & strComputer & " could not be found in Active Directory on " & Date
 Err.Clear
End If

script to change drive mapping


How to get key statistics for yahoo finance web search api?

Question: I am working on retrieving yahoo finance companies data and I was succeeded in getting the companies stock data. Apart from the basic data I am also trying to retrieve key statistics data for the same company. Below image is the key statistics fields which I require.

I am using yahoo web service api to get the stock data. But when I am trying to add the parameters like f=nab and f=snbaopl1 , I am getting 406 error response code. The below is the finance api which I am using.
http://finance.yahoo.com/webservice/v1/symbols/SPARC.BO/quote?format=json&view=detail&f=nab

If that is the way to give then how should I get the stocks key statistics for companies.
Comment: Can anyone help me out ? I am trying very hardly and researching in many ways but I didn't found any alternate options. The one which I found were deprecated. Why no one is responding to the yahoo questions
Answer: You can try access this link:
https://query2.finance.yahoo.com/v10/finance/quoteSummary/YOUR_COMPANY_SYMBOL?modules=ANY_PERMITTED_MODULE_SEPPARATED_BY_COMMAS
i found some modules that i think are interesting:
assetProfile
financialData
defaultKeyStatistics
calendarEvents
incomeStatementHistory
cashflowStatementHistory
balanceSheetHistory

this link will response with a json file.
Comment: Thankyou!! Thats what I was looking for...
but there are still couple of attributes that I couldn't get which I needed i.e. Price/Sales (ttm), Market Cap (intraday) [very important], Price/Sales (ttm)
Any help regarding these attributes?
Comment: @YagoRodriguez Is there any documentation on this API ? I was trying to get an idea of the query parameters.
Comment: @YagoRodriguez This is great. I have to ask though - if there're no docs on it, how did you come up with it? I've been busting my head trying to scrape from the new HTML page with no luck and this really saves the day.
Comment: Can this be altered to retrieve a csv file?
Comment: Try with summaryProfile
Comment: just try the parameters and read what they return... is what i did
Comment: I'm thinking this won't be available for very long...a year at most maybe.
Comment: Is it possible to get information on the major holders?
Comment: Great list. Also recommendationTrend is a useful module
Comment: @YagoRodriguez how did you identify these modules
Comment: This article references the possible modules https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
Answer: I have succeeded in getting yahoo finance key_statistics data by using the following quotes api http://finance.yahoo.com/d/quotes.csv?s=MSFT&f=snd1l1ydrbj1mt8opjk
By default the api will display the output in csv format if we want we can also convert the CSV output to JSON format.The quotes api is working perfectly fine to my requirement in getting the above mentioned statistics which are given as f=snd1l1ydrbj1mt8opjk and also getting the JOSN format by converting the csv output to JSON.
Comment: s = symbol (i.e., Ticker symbol)
n = company full name
d1 = Last Trade Date
l1 = Last Trade (Price Only)
y = Dividend Yield
d = Dividend / Share
r = P/E Ratio
b = Bid
j1 = Market Capitalization
m = Day's Range
t8 = 1yr Target Price
o = Open
p = Previous Close
j = 52-Week Low
k = 52-Week High
Comment: No longer works, now it's saying "It has come to our attention that this service is being used in violation of the Yahoo Terms of Service. As such, the service is being discontinued. For all future markets and equities data research, please refer to finance.yahoo.com."
Comment: Still works as of the 20th of March, 2017. Also, great catch!
Comment: What is meant by `f=snd1l1ydrbj1mt8opjk` ? Can you explain what this fields indicate? Thanks.


insert com where onde não tenho o valor completo

Question: Exemplo, eu já tenho na tabela o seguinte valor na coluna NUM_IMPRESSAO:

K3244.K1019706.FSJC.08915

O novo valor que quero inserir tem apenas os 4 últimos digitos (08915) e preciso inseri-lo na mesma linha. Segue o select que tentei fazer:
def update_table(file_name, id):
        date = str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%d/%m/%Y'))

        c.execute(f'UPDATE IMPRESSAO SET BINARY = ?,  DATA_ENVIO_BINARY = ? WHERE NUM_IMPRESSAO LIKE ?;', (file_name, date, id))
        c.commit()
        select_all()

Porém não está dando certo.
Answer: Estou supondo que o id seja o NUM_IMPRESSAO,
o que você precisa fazer é um split e colocar o "." como valor para dividir a string em um array.
novoValor = str(id).split('.')

novoValor = novoValor[-1]

ou utilizar outro método da classe string que é o rfind que  retorna o valor onde está o caractere procurado. e depois só passar ele dentro da string até o final.
novoValor = id[id.rfind('.')+1:]

utilize essa variável novoValor e passar no teu update.
c.execute(f'UPDATE IMPRESSAO SET BINARY = ?,  DATA_ENVIO_BINARY = ? ,NovoVaor = ? WHERE NUM_IMPRESSAO LIKE ?;', (file_name, date, novoValor, id))

Para referencia:
split
rfind
Comment: Inclusive você pode fazer `novo_valor = id[id.rfind('.')+1:]` para obter a última parte após o ponto, isso evitaria a criação de uma lista com todas as substrings apenas para buscar a última, tendo uma economia de memória na execução do código. Lembrando que `id` não é um bom nome para uma variável, visto que estaria sobrescrevendo uma função nativa do Python.
Comment: O ideal seria corrigir essa forma que apresentou, como comentei no primeiro comentário xD
Comment: O valor de `novoValor` seria `[3]`, pois você definiu ele igual uma lista com o tamanho da lista subtraído em 1. Acredito que você queria buscar o último valor da lista, então deveria ser `novoValor[len(novoValor)-1]`, mas melhor que isso, basta você passar o índice negativo para buscar o último valor, `novoValor[-1]`, não precisa calcular o tamanho da mesma.
Comment: Isso ai Anderson, existe diversa formas de retornar este ultimo elemento que ela que, só mostrei uma forma. O ideia seria essa ultima forma que tu mostrou `novo_valor = id[id.rfind('.')+1:]`, evitando assim alocação de memória desnecessária.
Comment: Pronto meu velho, valeu a ajuda xD @AndersonCarlosWoss
Comment: `novoValor = [-1]` isso não deveria ser `novoValor = novoValor[-1]`?
Comment: Isso mesmo @AndersonCarlosWoss, vacilo dos grandes. Valeu. Corrigido!


como remover vírgulas desnecessárias usando sed no shell script?

Question: Estou tentando criar um script para automatizar um trabalho que faço. Estava tudo indo bem, até encontrar esse problema. Quando uso o sed, para remover uma palavra da string, a saída mostra 2 vírgulas juntas, e isso pode causar falhas no parâmetro editado. Ex: Removendo "BBBBB"
domain.vmfull="AAAAA,BBBBB,CCCCC,ABCDE"
domain.vmfull="AAAAA,,CCCCC,ABCDE"
Pergunta 1 Como posso remover uma dessas 2 vírgulas? A saída deve ser assim:
domain.vmfull="AAAAA,CCCCC,ABCDE"
Questão 2 De outra forma, quando a palavra a ser removida for a última ou a primeira da lista, a vírgula desnecessária será a primeira ou a última. Como posso evitar as duas possibilidades? Ex: como abaixo removendo AAAAA:
domain.vmfull=",BBBBB,CCCCC,ABCDE"
a saída deve ser:
domain.vmfull="BBBBB,CCCCC,ABCDE"
bash-3.2$ echo "$options_sched"
"-vmfulltype=vstor -vmbackuptype=fullvm -asnodename=NODE1 -MODE=IFIncremental -domain.vmfull="AAAAA,BBBBB,CCCCC,ABCDE""

bash-3.2$ options_final=$(echo $options_sched | sed "s#BBBBB##gI")

bash-3.2$ echo $options_final
"-vmfulltype=vstor -vmbackuptype=fullvm -asnodename=NODE1 -MODE=IFIncremental -domain.vmfull="AAAAA,,CCCCC,ABCDE""

#Question - 2
bash-3.2$ echo "$options_sched"
"-vmfulltype=vstor -vmbackuptype=fullvm -asnodename=NODE1 -MODE=IFIncremental -domain.vmfull="AAAAA,BBBBB,CCCCC,ABCDE""

bash-3.2$ options_final=$(echo $options_sched | sed "s#AAAAA##gI")

bash-3.2$ echo $options_final
"-vmfulltype=vstor -vmbackuptype=fullvm -asnodename=NODE1 -MODE=IFIncremental -domain.vmfull=",BBBBB,CCCCC,ABCDE""

Answer: Acredito que a forma mais correta de resolver esse problema é escrever um script que interpreta o texto, compreende e divide as partes que interessam para você para assim manusear com maior facilidade. (Por exemplo procurar o parâmetro domain.vmfull, dividir o conteúdo passado nele pelas vírgulas, remover o ítem desejado e fazer um join de volta. Isso pode ser feito tranquilamente em um script bash ou em python.)
Tentar realizar esse tipo de processamento de texto mais complexo usando apenas sed pode acabar sendo um tiro no pé.
Como sua pergunta pede usando sed, uma opção não muito elegante, mas fácil de entender seria concatenar múltiplos sed's em cascata:
Por exemplo:

Questão 1: você pode substituir ",," por "," (Duas vírgulas por uma):

$  echo $A | sed 's/BBBBB//g' | sed 's/,,/,/g'
-vmfulltype=vstor -vmbackuptype=fullvm -asnodename=NODE1 -MODE=IFIncremental -domain.vmfull="AAAAA,CCCCC,ABCDE"

Claro, você precisa ter certeza que fora desse intervalo você não tem em algum outro lugar "duas vírgulas seguidas" que realmente precisavam ser duas vírgulas seguidas, pois elas também vão ser substituídas. Poderia pensar também em uma expressão regular (regex) mais complexa, porém isso iria precisar de uma análise e uma garantia muito forte de que o texto segue um molde específico.

Questão 2: Você pode substituir vmfull=", por vmfull=" , e substituir ," no final da frase por ". Abaixo, $(símbolo de cifrão) representa o final da frase:

$ echo $A | sed 's/ABCDE//g' | sed 's/,,/,/g' | sed 's/vmfull=",/vmfull="/g' | sed 's/,"$/"/g'
-vmfulltype=vstor -vmbackuptype=fullvm -asnodename=NODE1 -MODE=IFIncremental -domain.vmfull="AAAAA,BBBBB,CCCCC"

Que dá o retorno desejado. Como pode ver, eu também juntei os comandos de suas duas questões.
Novamente, esse tipo de substituição sempre vai presumir algumas coisas do texto que se não forem verdade o comando não irá funcionar. Ele presume por exemplo que o argumento vmfull é o último da lista, ou que não existe nenhum caso de "vírgula dupla". Pode-se pensar em uma regex mais complexa, porém não acredito ser a melhor abordagem nesse caso.


Jspdf e canvas responsivo

Question: Estou a gerar PDF com jspdf e faço o screenshot com o canvas. O form que gera o PDF é muito grande e gera mais do que uma página.
Código:
window.html2canvas = html2canvas;

function demoFromHTML() {

const html_source = document.getElementById('employee_detail');
const filename = 'PIC.pdf';

html2canvas(html_source).then(function(canvas) {

let imgData = canvas.toDataURL('image/png');
let imgWidth = 210;
let pageHeight = 297;

let imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
let position = 0;
let pdf = new jsPDF('p', 'mm');
let fix_imgWidth = 0;
let fix_imgHeight = 18;

pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;

while (heightLeft >= 0) {
position = heightLeft - imgHeight;
pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, position, imgWidth + fix_imgWidth, imgHeight + fix_imgHeight);
heightLeft -= pageHeight;
}
pdf.save(filename);
})
}

O problema é que quando gero o pdf no pc, faz a quebra de página corretamente, mas quando faço gerar o pdf no telemóvel já faz a quebra de página incorreta.
Como posso colocar o meu código de forma a ajustar a quebra de página sempre correta independentemente do tamanho do ecrã?
Deixo aqui o link para visualizarem a quebra de página no telemóvel:
inserir a descrição do link aqui
Aqui deixo o link do mesmo pdf em computador:
inserir a descrição do link aqui
Queria que imprimisse onde imprimisse ajustasse o documento à tela do equipamento automaticamente.
Answer: Possível solução:

Busca o ponto de interrupção do dispositivo (Device Breakpoints);
Através do if/else ponderar a quebra da tela de acordo com o dispositivo.

Ou seja, tens que configurar o seu código de acordo com a largura de cada tela.
Existem toneladas de telas e dispositivos com diferentes alturas e larguras, por isso é difícil criar um ponto de interrupção exato para cada dispositivo. Para manter as coisas simples, você pode segmentar cinco grupos comuns:

Extra small devices (phones, 600px and down)
Small devices (portrait tablets and large phones, 600px and up)
Medium devices (landscape tablets, 768px and up)
Large devices (laptops/desktops, 992px and up)
Extra large devices (large laptops and desktops, 1200px and up)

Exemplo:
const deviceWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;

window.html2canvas = html2canvas;

function demoFromHTML() {

  const html_source = document.getElementById('employee_detail');
  const filename = 'PIC.pdf';

  html2canvas(html_source).then(function(canvas) {

    let imgData = canvas.toDataURL('image/png');
    let imgWidth = 210;
    let pageHeight = 297;

    let imgHeight = canvas.height * imgWidth / canvas.width;
    let heightLeft = imgHeight;
    let position = 0;
    let pdf = new jsPDF('p', 'mm');

    let fix_imgWidth = 0; // Padrao
    let fix_imgHeight = 18; // Padrao

    if (deviceWidth < 600) { //  max-width: 600px -  Dispositivos extra pequenos

      fix_imgWidth = 0;
      fix_imgHeight = 18;

    } else if (deviceWidth > 600) { // min-width: 600px - Pequenos dispositivos

      fix_imgWidth = 0;
      fix_imgHeight = 18;

    } else if (deviceWidth > 768) { // min-width: 768px - Dispositivos médios

      fix_imgWidth = 0;
      fix_imgHeight = 18;

    } else if (deviceWidth > 992) { // min-width: 992px  - Dispositivos grandes

      fix_imgWidth = 0;
      fix_imgHeight = 18;

    } else if (deviceWidth > 1200) { // min-width: 1200px - Dispositivos extra grandes

      fix_imgWidth = 0;
      fix_imgHeight = 18;

    }

    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft >= 0) {
      position = heightLeft - imgHeight;
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', 0, position, imgWidth + fix_imgWidth, imgHeight + fix_imgHeight);
      heightLeft -= pageHeight;
    }
    pdf.save(filename);
  })
}

E obviamente o fix_imgHeight e o fix_imgWidth vais ajustar de acordo com a tela.
Comment: no telemóvel continua sem fazer a quebra de página correta.
Comment: Meu caro Jovem, tens que alterar os valores  `fix_imgHeight` e `fix_imgWidth` de acordo com a resuloção da tela. Usa o emulador do navegador para simular vários tipos dispositivos. Abrir emulador no Chrome: `CTRL` + `SHIFT` + `I` e depois  `CTRL` + `SHIFT` + `M` e no Firefox: `Ctrl` + `Shift` + `M`
Comment: depois de imensos testes, para funcionar não posso usar o modal. Com o modal, nunca consegui obter o resultado que pretendia com esta solução e com outras que tentei testar de várias formas.

Jspdf e canvas responsivo


Exception when using @Scheduled spring annotation (Cannot find class [org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor])

Question: I have created a scheduled job using a @Scheduled annotation.
It looks like this:
package example.tools.rr;

public class RequestProcessorJob {
    private RequestService requestService;
    ...
    @Scheduled(fixedRate = 10000)
    public void process() {
         ...
    }

    public RequestService getRequestService() { return requestService; }

    public void setRequestService(RequestService requestService) { this.requestService = requestService; }

}

I've put it inside a bundle A, so I can use this class in other bundles. I imported it inside bundle B. B's blueprint.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:cm="http://www.eclipse.org/gemini/blueprint/schema/blueprint-compendium"
  xmlns:ctx="http://www.springframework.org/schema/context" xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
              http://www.eclipse.org/gemini/blueprint/schema/blueprint-compendium http://www.eclipse.org/gemini/blueprint/schema/blueprint-compendium/gemini-blueprint-compendium.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/task
              http://www.springframework.org/schema/task/spring-task-3.1.xsd
              ">
  ...

  <bean id="handsetService" class="example.handset.impl.HandsetServiceImpl">
    ...
  </bean>

  <task:scheduler id="taskScheduler" />
  <task:executor id="taskExecutor" pool-size="1" />
  <task:annotation-driven executor="taskExecutor"
                          scheduler="taskScheduler" />

  <bean class="example.tools.rr.RequestProcessorJob">
    <cm:managed-properties persistent-id="example.handset.processing"
                           autowire-on-update="true" />
    <property name="requestService" ref="handsetService" />
  </bean>

</blueprint>

When I install the bundle (inside Apache Felix) a following exception is thrown:
Unable to create application context for [example.handset], unsatisfied dependencies:
none
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor] for bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in null; nested
exception is java.lang.ClassNotFoundException: org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor not found from bundle [example.handset]
        at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1262) ~[na:na]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576) ~[na:na]
        at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1331) ~[na:na]
        at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:897) ~[na:na]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:566) ~[na:na]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913) ~[na:na]
        at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.access$1600(AbstractDelegatedExecutionApplicationContext.java:60) ~[na:na]
        at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext$4.run(AbstractDelegatedExecutionApplicationContext.java:325) ~[na:na]
        at org.eclipse.gemini.blueprint.util.internal.PrivilegedUtils.executeWithCustomTCCL(PrivilegedUtils.java:85) ~[na:na]
        at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.completeRefresh(AbstractDelegatedExecutionApplicationContext.java:290) ~[na:na]
        at org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor$CompleteRefreshTask.run(DependencyWaiterApplicationContextExecutor.java:137) ~[na:na]
        at java.lang.Thread.run(Unknown Source) [na:1.7.0_67]
Caused by: java.lang.ClassNotFoundException: org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor not found from bundle [example.handset]
        at org.eclipse.gemini.blueprint.util.BundleDelegatingClassLoader.findClass(BundleDelegatingClassLoader.java:101) ~[na:na]
        at org.eclipse.gemini.blueprint.util.BundleDelegatingClassLoader.loadClass(BundleDelegatingClassLoader.java:155) ~[na:na]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.7.0_67]
        at org.springframework.util.ClassUtils.forName(ClassUtils.java:257) ~[na:na]
        at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:417) ~[na:na]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1283) ~[na:na]
        at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1254) ~[na:na]
        ... 11 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor not found by example.handset [443]
        at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1499) ~[felix.jar:na]
        at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75)
~[felix.jar:na]
        at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1882) ~[felix.jar:na]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.7.0_67]
        at org.apache.felix.framework.Felix.loadBundleClass(Felix.java:1793) ~[felix.jar:na]
        at org.apache.felix.framework.BundleImpl.loadClass(BundleImpl.java:929) ~[felix.jar:na]
        at org.eclipse.gemini.blueprint.util.BundleDelegatingClassLoader.findClass(BundleDelegatingClassLoader.java:97) ~[na:na]
        ... 17 common frames omitted

if I add an empty class which just has a @Scheduled annotation inside the bundle B, everything works fine and the RequestProcessorJob is scheduled properly (the empty class is not used, but it makes the error not occur).
public class MockJob {
    @Scheduled(fixedRate = 10000)
    public void process() { }
}

I've tried to include the module A inside of B in pom.xml as <scope>provided</scope> as well as <scope>compile</scope>, the result is the same.
Having a reduntant class to make it work doesn't really sounds like a solution. Do You have any ideas about this? Is this a bug, or maybe somehow it was supposed to work so strangely?
Answer: Ok, I was just missing org.springframework.scheduling.annotation in <Import-Package> section in pom.xml. Quite obvious after all, but the behaviour of spring is still weird here.


How to count unique rows in sqlalchemy

Question: I already know how to count unique rows using deprecated Query API like that:
  self.session.query(table).distinct().count()

But how to do this using currently supported ORM api? (https://docs.sqlalchemy.org/en/20/orm)
select(func.count()).select_from(select(table).distinct())) does not work :(
Answer:
class Record(Base):
    __tablename__ = 'records'

    id = Column(Integer, primary_key=True)
    title = Column(String)

with Session(engine) as session:
    count_of_unique_record_titles = session.execute(select(func.count(Record.title.distinct()))).scalar()

How to count unique rows in sqlalchemy


How to globally set implementation class for model attribute data type?

Question: I would like to set a implementation class globally for certain data types. For instance, we would like to stop using annotations throughout our models. Pasted an example below.
<code>@Schema(implementation = OffsetDateTime.class)
private Instant createTime;
</code>
Can we use configure springdoc-openapi to do this? or is there a way to map a Java Instant to OpenApi date-time format?
Comment: Are you accepting the answer bellow?
Answer: You can use PrimitiveType from io.swagger.v3.core.util.PrimitiveType:
<code>static {
    PrimitiveType.customClasses().put(Instant.class.getName(),PrimitiveType.DATE_TIME);
}
</code>


Recuperar Valor Json

Question: Estou incluindo em meu site meu canal do YouTube com os vídeos.
Mas tem uma parte do Json que não estou conseguindo recuperar.
Estou fazendo assim:
$.each($feed.items, function(i,item){
var url = item.videoId;

Comentei no código a linha para vocês verem do Json. Mas está vindo undefined.

{
 "kind": "youtube#searchListResponse",
 "etag": "\"***/***"",
 "nextPageToken": "CAUQAA",
 "pageInfo": {
  "totalResults": 9,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"***/***"",
   "id": {
    "kind": "youtube#video",
    "videoId": "*************" ############################## AQUI
   },
   "snippet": {
    "publishedAt": "2015-05-26T17:47:49.000Z",
    "channelId": "****",
    "title": "TITULO",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "default.jpg"
     },
     "medium": {
      "url": "qdefault.jpg"
     },
     "high": {
      "url": "hqdefault.jpg"
     }
    },
    "channelTitle": "TESTE",
    "liveBroadcastContent": "none"
   }
  },
Comment: Assim não tem como. Eu consegui solucionar. Eu dei um **console.log(item)** e vi como ele estava retornando. Vou postar.
Comment: Só daqui dois dias.
Comment: Tente fazer assim: `var url = item.items.videoId;`.
Comment: Diego, se possível poste como resposta a solução e depois marque como aceita. =)
Answer: Solucionei a questão. Embora esse Json acima seja o retornado pela URL direto no navegador, abri meu Inspect Element e dei um console.log(item) dentro da função Each().
Daí ele me mostrou:
Object = Item {
   id : {
      videoId: *****
   }
}

Daí eu fiz um item.id.videoId e funcionou legal.
Obrigado.

Recuperar Valor Json


Transformation of Curvature 2-Form Under Global Bundle Autormphism

Question: Let $F^A$ be a curvature two form on a principal bundle $P$ corresponding to the connection one form $A$. Let $f:P\rightarrow P$ be a global bundle automorphism; there then exists a map $\sigma_f:P\rightarrow G$ such that:
$$f(p)=p\cdot \sigma_f(p)$$
Finally let $\mu_G$ be the maurer cartan form, given by:
$$\mu_G(X_g)=L_{g^{-1}*}X_g$$
where $X_g$ is a vector field on some Lie group $G$. Under the pullback of $A$ by $f$ we have:"
$$f^*A=\text{Ad}_{\sigma_{f^{-1}} } \circ A+\sigma_f^*\mu_G$$
I am trying to show that:
$$F^{f^*A}=\text{Ad}_{\sigma_{f^{-1}}}\circ F^A$$
where:
$$F^A=dA+\frac{1}{2}[A,A]$$
and for two Lie algebra valued one forms $\eta,\omega$:
$$[\eta,\omega](X,Y)=[\eta(X),\omega(Y)]-[\eta(Y),\omega(X)]$$
which comes from the definition of the wedge product for Lie algebra valued  $k$ and $l$
forms.
When replacing $A$ with $f^*A$, we see that:
$$F^{f^*A}=d(\text{Ad}_{\sigma_{f^{-1}}}\circ A)+\sigma_f^*d\mu_G+\frac{1}{2}\text{Ad}_{\sigma_{f^{-1}}}\circ [A,A]+\frac{1}{2}\sigma_f^*[\mu_G,\mu_G]+\frac{1}{2}[\text{Ad}_{\sigma_{f^{-1}}}\circ A,\sigma_f^*\mu_G]+\frac{1}{2}[\sigma_f^*\mu_G,\text{Ad}_{\sigma_{f^{-1}}}\circ A]$$
By the Maurer-Cartan equation we have that:
$$\sigma_f^*d\mu_G=-\frac{1}{2}\sigma^*_f[\mu_G,\mu_G]$$
hence:
$$F^{f^*A}=d(\text{Ad}_{\sigma_{f^{-1}}}\circ A)+\frac{1}{2}\text{Ad}_{\sigma_{f^{-1}}}\circ [A,A]+\frac{1}{2}[\text{Ad}_{\sigma_{f^{-1}}}\circ A,\sigma_f^*\mu_G]+\frac{1}{2}[\sigma_f^*\mu_G,\text{Ad}_{\sigma_{f^{-1}}}\circ A]$$
My problem is now that I am unsure of how to calculate the exterior derivative of $\text{Ad}_{\sigma_{f^{-1}}}\circ A$. By our previous formula for two Lie algebra valued one forms we have that for $\eta=\text{Ad}_{\sigma_{f^{-1}}}\circ A$,
and $\omega=\sigma_f^*\mu_G$:
$$\frac{1}{2}\left([\eta,\omega]+[\omega,\eta]\right)(X,Y)=\frac{1}{2}\left([\eta(X),\omega(Y)]-[\eta(Y),\omega(X)]+[\omega(X),\eta(Y)]-[\omega(Y),\eta(X)]\right)$$
$$=[\eta(X),\omega(Y)]-[\eta(Y),\omega(X]$$
$$=[\eta,\omega](X,Y)$$
So I feel that:
$$d(\text{Ad}_{\sigma_{f^{-1}}}\circ A)=\text{Ad}_{\sigma_{f^{-1}}}\circ dA-[\eta,\omega]$$
but I don't see why this should be true. In fact, since $\text{Ad}$ is a representation of $G$ on $\mathfrak{g}$ I would think that:
$$d(\text{Ad}_{\sigma_{f^{-1}}}\circ A)=\text{Ad}_{\sigma_{f^{-1}}}\circ dA$$
but then I have this extra factor of $[\eta,\omega]$, so I am at a loss. Any hints on how to calculate this exterior derivative, or on how that wedge product may actually be zero would be greatly beneficial.
Edit:
Employing Professor Shifrin's notation, I write that:
$$f^*A=\sigma_{f^{-1}}A\sigma_f+\sigma_{f^{-1}}d\sigma_f$$
I have already calculated the exterior derivative of the second term, albeit in a different notation, so I move to the first term:
$$d(\sigma_{f^{-1}}A\sigma_f)=d(\sigma_{f^{-1}})\wedge A\sigma_f+
\text{Ad}_{\sigma_f^{-1}}\circ dA+\sigma_{f^{-1}}A\wedge d(\sigma_f) $$
Note that:
$$\sigma_{f^{-1}}\sigma_f=e$$
hence:
$$d(\sigma_{f^{-1}})\sigma_f=-\sigma_{f^{-1}}d\sigma_f\Rightarrow d\sigma_{f^{-1}}=-\sigma_f^{-1}d\sigma_f\sigma_{f^{-1}}$$
Therefore we obtain:
$$d(\sigma_{f^{-1}}A\sigma_f)=-\sigma_{f^{-1}}d\sigma_f\wedge \text{Ad}_{\sigma_f^{-1}}A+
\text{Ad}_{\sigma_f^{-1}}\circ dA-\text{Ad}_{\sigma_{f^{-1}}}\circ A \wedge d(\sigma_{f^{-1}})\sigma_f$$
The final term in this sum can be rewritten as:
$$\text{Ad}_{\sigma_{f^{-1}}}\circ A \wedge d(\sigma_{f^{-1}})\sigma_f=-\text{Ad}_{\sigma_{f^{-1}}}\circ A \wedge \sigma_f^{-1}d\sigma_{f}$$
Thus:
$$d(\sigma_{f^{-1}}A\sigma_f)=-\sigma_{f^{-1}}d\sigma_f\wedge \text{Ad}_{\sigma_f^{-1}}A+
\text{Ad}_{\sigma_f^{-1}}\circ dA+\text{Ad}_{\sigma_{f^{-1}}}\circ A \wedge \sigma_f^{-1}d\sigma_{f}$$
From here, I can kind of see how the pieces should move, but I am unsure why. Reconciling the two notations is proving troublesome to me. To be clearer, it seems that from the definition for the wedge product of twisted forms, this product is actually symmetric for one forms, so I feel like the first term and the last term would cancel, which doesn't make sense. I am then left to conclude that there is something different about the wedge product I have used in this edit, and the wedge product I used in the original post, but I am unsure what that difference actually is, or how to make it precise.
Edit 2:
The definition of wedge product for Lie algebra valued one forms is
as follows:
Given a $\omega\in \Omega^k(P,\mathfrak{g})$ and $\eta\in \Omega^k(P,\mathfrak{g})$, then their wedge product is given by:
$$[\omega,\eta](X_1,\dots,X_{k+l})=\frac{1}{k!l!}\sum_{\sigma\in S}\text{sign}(\sigma)\left[\omega(X_{\sigma(1)},\dots,X_{\sigma(k)}), \eta(X_{\sigma(k+1)},\dots,X_{\sigma(k+l)} ) \right]$$
When choosing a basis $\{T_i\}$  for the Lie algebra $\mathfrak{g}$, we have that $\eta$ and $\omega$ can be written as:
$$\eta=\sum_{i=1}^n \eta^i\otimes T_i$$
$$\omega=\sum_{i=1}^n \omega^i\otimes T_i$$
where each $\omega^i$ and $\eta^i$ are $k$ and $l$ forms on $P$ respectively. Then the wedge product can be written as
$$\omega \wedge \eta =\sum_{i,j=1}^n \omega^i\wedge\eta^j\otimes[T_i, T_J]  $$
Hence:
$$[\eta,\omega] =\sum_{i,j=1}^n \eta^j\wedge\omega^i\otimes[T_j,T_i] $$
$$=(-1)^{lk}\sum_{i,j=1}^n\eta^i \wedge\omega^j\otimes[T_j,T_i]$$
$$=(-1)^{lk+1}\sum_{i,j=1}^n\eta^i \wedge\omega^j\otimes[T_i,T_j]$$
$$=(-1)^{lk+1}[\omega,\eta]$$
So for two one forms, $\eta$ and $\omega$:
$$[\eta,\omega]=(-1)^2[\omega,\eta]=[\omega,\eta]$$
Hence the wedge product of Lie algebra valued forms is symmetric for one forms.
Comment: Your last comment cannot be right. Obviously, $\sigma_f$ needs to be differentiated, as well. Have you tried working this out in the less abstract matrix notation, knowing that $R_g^*A = g^{-1}Ag + g^{-1}\,dg$?
Comment: For the record, if $\omega$ and $\eta$ are matrix-valued $1$-forms, then  $(\omega\wedge\eta)(X,Y) = \omega(X)\eta(Y) - \omega(Y)\eta(X)$, "as usual." This, in general, is different from $[\omega,\eta](X,Y) = [\omega(X),\eta(Y)]-[\omega(Y),\eta(X)]$. You have a sign error in your differentiation: Passing $d$ across $A$ produces a negative, as usual, since $A$ is a (matrix-valued) $1$-form. If $\tilde A = g^{-1}Ag$ and $\omega = g^{-1}dg$,  I get $d\tilde A = -\omega\wedge\tilde A + g^{-1}dA\,g - \tilde A\wedge \omega$.
Comment: @TedShifrin I was under the impression that I can only write $A$ like that in a local trivialization where I can view $A$ as a Lie algebra valued one form on the base manifold $M$ plus the Maurer Cartan form. Since $f$ is a global bundle automorphism,  I felt as though I couldn't  work it out this way. Locally I can show something similar, but globally I am struggling with that exterior derivative term.
Comment: No, this works quite generally. The Maurer-Cartan form in my expression is coming from the change of gauge. My $g$ will be your $\sigma_f$. Even having worked 40+ years in differential geometry, I avoided the notation of your post whenever I could.
Comment: @TedShifrin I think I see, in what you have written, is your $g$ constant, or is it also a function $P\rightarrow G$? Because I feel like for a constant $g$ it should still be just be $g^{-1}Ag$
Comment: Of course I intend $g$ to be a mapping to $G$ on our open set.
Comment: @TedShifrin If it's a map from our open set, doesn't that imply this a local gauge transformation though? My apologies for the continued confusion, I'm having trouble reconciling the two notations.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/139601/discussion-between-chris-and-ted-shifrin).  Sorry, I just clicked this, I did not know what it would it do. Completely understand if you would rather not join this.
Comment: No, thinking that matrix-valued $1$-forms should commute is just not right, and I don't see how the way you rewrote the last term is correct.
Comment: @TedShifrin I am confused, perhaps my book is using a different definition of the wedge product than you, or perhaps I made an error, please see edit. Also thank you, I know you must be busy.
Comment: It's the Lie bracket, not the matrix product, so OK. Wedge product of matrix-valued forms has no such property, in general.
Comment: @TedShifrin the book I'm using said the $\wedge$ of two Lie algebra forms is just different notation for the $[\cdot,\cdot]$ operation I just described. How is the wedge product actually calculated?
Answer: Here is an easier proof: (Following your notation, it seems that you are using Hamilton's book on mathematical gauge theory, right? I try to stick to this notation too).
First of all, recall that the curvature $F^{A}\in\Omega^{2}(P,\mathfrak{g})$ is "of type $\mathrm{Ad}$'', what essentially means that
$$r_{g}^{\ast}F^{A}=\mathrm{Ad}_{g^{-1}}\circ F^{A},$$
where $r_{g}:P\to G$ is the right group action $r_{g}(p):=p\cdot g$. In other words, the curvature is an element of the subset $\Omega^{2}_{\mathrm{hor}}(P,\mathfrak{g})^{\mathrm{Ad}}$.
The secons thing to realize is that
$$F^{f^{\ast}A}=f^{\ast}F^{A},$$
which follows from the fact that $\ast$ commutes with both $\mathrm{d}$ and $[\cdot,\cdot]$. As a next step, note that $f$ can be written as
$$f(p)=p\cdot\sigma_{f}(p)=r_{\sigma_{f}(p)}(p).$$
Hence, combining everything from above, we have that
$$F^{f^{\ast}A}_{p}=(f^{\ast}F^{A})_{p}=(r^{\ast}_{\sigma_{f}(p)}F^{A})_{p}=\mathrm{Ad}_{\sigma_{f}^{-1}(p)}\circ F^{A}_{p}.$$
Last but not least, note that $\sigma_{f}^{-1}=\sigma_{f^{-1}}$ and hence, we get your claimed equality
$$F^{f^{\ast}A}=\mathrm{Ad}_{\sigma_{f^{-1}}}\circ F^{A}.$$
Comment: This is a nice proof, and if I can't figure out the more brute force approach, or if no one else does I will select this answer as the correct one, but it would be nice to see how the $d(\text{Ad}_{\sigma_{f^{-1}}}\circ A)$ can be calculated out.
Comment: Well, it is true that $\mathrm{d}(\mathrm{Ad}_{g}\circ A)=\mathrm{Ad}_{g}\circ\mathrm{d}A$. Right now, it I don't see how your additional term cancels. I will have a look lateron, if I have time.
Comment: that's true for a constant $g$, but $\sigma_f$ depends on the point $p$ so the exterior derivative should do something to it. Thank you again though, and don't worry if you don't have the time.


Generalized case for identifying transcendental numbers

Question: For any strictly increasing sequence of natural numbers $ a_1...a_n $, is the expression given below transcendental? Stack Exchange gives a specific case Is $0.1010010001000010000010000001 \ldots$ transcendental? , with $ a_n=n$, as transcendent, but people I've asked don't think that can be generalized to all cases, likewise with using Liouville's inequality.
$ \sum_{n=1}^{\infty} \prod_{i=1}^{n} 10^{-a_i} $
Answer: Modern mathematics knows very little about transcendental numbers. The closest thing we have to a general case is $a^b$ where $a$ is algebraic but not $0$ or $1$, and $b$ is irrational algebraic (by the Gelfond-Schneider theorem), in particular: $2^{\sqrt{2}}$, the Gelfond-Schneider constant (or Hilbert number).


How do I read bars with only one or two notes?

Question: In this sheet there are some bars that only have one or two notes, instead of four. How do I read them? Do they last 1 unit of time as well?
In the case of the bars with only one note, does that note last for 4 units of time? Or only 1? And in the case of bars with only 2 notes?
Comment: There is no rhythm in this tab. Nothing makes it clear if a bar has two notes, the two should be equal. The tab gives you the notes, maybe you should listen to the original music to get the rhythm!
Comment: This is too incomplete to tell anything.  It doesn't even say if it's 4/4 or 2/4.  To be really snarky I could guess it's 3/4 with a quadruplet and doublet over the measure.
Comment: I dont think this is off topic. This situation is very easy to generalize, a guitarist will often have tabs which are incomplete like this, GENERALLY SPEAKING the correct way to approach this problem is exactly what is outlined below in the answers. This is a valuable lesson to a newbie guitarist.
Comment: I'm voting to close this question because to fully answer the question would require identifying elements of a recording, which is off topic here.
Answer: There isn't any rhythm in that tab.
In the absence of any rhythm, and with the numbers written with even spacing which provides no visual hints at rhythm, I would just play even values per bar.
In this example it's mostly four notes per bar. I would treat it as 4/4 meter and play it as all quarter notes. In the bars with two notes play it as two half notes. One note bars play as whole notes.
There also is no tempo indicated.
Literally there is nothing for rhythm other than the sense of 4/4 meter.
In a lot of cases tab is short hand, partial notation that just gives pitch and fret/fingerings and it's assumed the player already knows the music or will use a recording to get the rhythm and tempo. You might be able to use a recording to get the rhythm.
Answer: This way of writing music is called 'tablature' or 'tab'. Sometimes, tablature has some indication of the rhythm, such as this example:

However, tablature usually doesn't have any indiciation of the rhythm. Usually, you just need to listen to a recording of the piece to find out what the rhythm should be. From the title, it seems to be a simplified version of this piece:

If you can't work out the timing from the recording, then tablature isn't a suitable format for you to use.
Comment: I've rarely seen tab without note values.  My exposure is to American folk music for guitar and banjo; in that world, rhythm is almost always indicated in the tab.  I of course believe you that you seldom see tab with rhythm, but I'm curious what domain that is in.
Comment: @WayneConrad are you talking about music where you have standard notation and tab side by side? Or at least published tab? Perhaps I'm too used to the world of informally shared tabs...
Comment: Sometimes tab paired with standard notation, but more usually like the image in your answer (but stems pointed down instead of up).  Here is  [an example for five-string banjo](https://www.banjoteacher.com/tablature/pdfs/RolliSweetBaby'sArms-BanjoTeacher.com.pdf).  The only tab I've seen for guitar is from dad's Travis-style fingerpicking books; those all have rhythm.  But I went to try to find an example of guitar tab on the web with note values, and I learned that guitar tabs with rhythm appear to be rare on the web.  So my world view was skewed by banjo, and by dad's unusual books.
Comment: @WayneConrad interesting! I suspect that over here in the UK we have less of a banjo-influenced culture. At least it's one of the instruments I haven't tried to learn yet...
Answer: What you showed us isn't complete notation.   It's an aid for someone who knows the song already but just needs some help with where to put their fingers.   Yes, we can assume a 4-beat bar, and we can assume that when there are four notes in a bar they will be short, two or one notes in a bar will be longer.  But there is not enough information here to be any more precise about the rhythm.    If you don't know the song, try to find a copy in tab notation with rhythms, or in staff notation.
Answer: Without any rests, indication of time signatures, or clues about rhythm I think it is a fairly safe bet to assume that this song is in 4/4 and most of the notes are quarter notes. In the bars with fewer notes tabbed we are likely looking at whole-notes or half-notes which likely fall on the 1 and the 3. So bar #20 you'd play a 5 on the 1-beat and hold for 4, bar #22 you'd play your 2 on the 1-beat and the 3-beat. That's how I would play it anyway.
There are likely an infinite ways to pick this apart if you really wanted to but it looks like a fairly straightforward rock line.
Alternative #1: Radical Time Signature Changes - if you like you could treat every note as the same length and assume that bar #20 and #24 are a quick switch to 1/4 with #22 and #23 being a dip in to 2/4. Very math-rock ;)
Alternative #2: Guess The Rests - If we assume all notes are the same length (all quarter-notes), and all bars are the same length (all 4/4), then there are some implicit rests (r). So bar 20 you could play as

r-r-5-r
r-5-r-r

But if in doubt I'd stick with my original suggestion ;)
EDIT: Having listened to a few seconds of the piece that Topo has linked in his answer, yes if this is indeed the piece of music it does appear to be a fairly straightforward 4/4 piece largely in line with my original suggestion.
BONUS EDIT: Really, the best thing to do is play with the music and see how you like to play it, how it feels under your figures. Obvs if you're playing this in a group you have that constraint but feel free to experiment where the notation is incomplete :)
Answer: As other answers say, this isn't a complete or precise notation.  But to pick out a key point: Almost certainly, every bar is meant to be the same length of time.  That's standard for tablature, and generally, for most notations that don't give precise rhythm.  So if there's only one chord marked in a bar, it should last just as long as a whole four-chord bar.
There are plenty of pieces of music where not all bars last the same length of time — some individual pieces/songs notable for it (e.g. The Beatles' Here Comes the Sun), and also some genres in which it's very usual.  But within the mainstream Western tradition (classical, pop, jazz, etc…), you can generally assume that bars are all the same length unless the notation explicitly shows otherwise.
Comment: Chord?  There's no chord notation here.


Extracting multiple columns from a matrix in R

Question: If I have a matrix M of 15 columns, what is R syntax to extract a matrix M1 consisting of 1,7,9,11,13 and 15 columns?
Answer: Like this: M[,c(1,7,9,11,13,15)]


An example of a bounded, continuous function on $(0,1)$ that is not uniformly continuous

Question: I can not find the example of a continuous function on $(0,1)$ that is bounded on $(0,1)$, but not uniformly continuous on $(0,1)$. Is there any? Thank you.
Comment: See also http://math.stackexchange.com/questions/220733/is-a-bounded-and-continuous-function-uniformly-continuous
Answer: If you are not aware of the result mentioned in the example of @Tomek Kania,Here is elementary approach to prove that $\sin (\frac{1}{x})$ is not uniformly continuous on $(0,1)$.
$$f(x) = \sin\left(\frac{1}{x}\right).$$
It is certainly bounded. However, it is not uniformly continuous. Given $\epsilon=\frac{1}{4}$, for any $\delta\gt 0$ we can find a large enough value of $n$ so that
$$\frac{2}{(2n+1)\pi} - \frac{1}{2n\pi} = \frac{4n - (2n+1)}{2n(2n+1)\pi} = \frac{2n-1}{2n(2n+1)\pi}\lt \delta,$$
yet
$$f\left(\frac{2}{(2n+1)\pi}\right) =\sin\left(\frac{(2n+1)\pi}{2}\right) = \pm 1,$$ and $$f\left(\frac{1}{2n\pi}\right) = \sin(2n\pi) = 0,$$ so letting $x=\frac{2}{(2n+1)\pi}$ and $y=\frac{1}{2n\pi}$, we have
$$|x-y|\lt\delta\text{ but }|f(x)-f(y)| \geq \epsilon.$$
Comment: See also http://math.stackexchange.com/questions/79649/how-to-prove-sin1-x-is-not-uniformly-continuous
Answer: Take $$f(x) = \sin 1/x.$$
It is not uniformly continuous as such functions admit continuous extension to the closure of the domain. Here we don't have such extension as there are two sequences $(x_n)$ and $(y_n)$ in $(0,1)$ that tend to 0 such that $f(x_n)=1$ and $f(y_n)=0$ for all $n$.


Lotus Notes not running as scheduled

Question: I have 3 agents in Lotus, these agents just update different CSV files on a shared drive. Based on their logs, they are running but only took a second. Checking the CSV files, they are not updating.

I've tried to adjust the schedule time
Tried other servers
Changed the Target
Disable/re-enable the agent
Made a copy of the agent

I haven't edit the code.
Workaround is to run these agents manually. It actually updates the CSV files and its taking at least 5 minutes for the agents to finish running which is expected. These agents just suddenly stop running as scheduled.
Comment: Agents run in the context of user "System", same as the Domino Servers... they don't have network credentials.... unless you don't allow the servername itself to access the share you will never be successfull. AND: never run even one line of code without error handling... it would have told you whats going wrong. AND: you might need excel installed on the server depending which technique you use to update the excel files...
Comment: Start by checking the log.nsf on the server for the time you have the agent scheduled.  You can also check to see if the Security level on the agent has been changed.   Maybe check that the XL install on the server is ok too.  e.g. run Excel manually.
Comment: Also keep in mind Excel (and all the other Office products) is not thread safe and is not intended, nor licensed to be used on a server.  That said, you may have to explicitly set the PATH to Excel.exe (or whatever external program if you're using one) when running as a scheduled agent.  I'd also check the permissions the server service is using to see if it can actually get to the .xlsx.
Comment: Thanks you for all your answers. How do I check if an excel/csv installed on the server? And how I check the permissions the server service is using?
Comment: I do not find any reference to Excel in post. Or was it removed? CSV are plain text fails and you can use plain LotusScript read/write operations to deal with them.
Comment: You're right, I incorrectly made the assumption that Excel was being used.  My comment is otherwise still valid though.
Comment: Sorry I edited the excel to CSV to be more specific and yeah still the same, Thanks.
Answer: As Torsten mentioned, your Domino server does not have enough permissions. Per default it runs as local system, which does not have access to any shares.
See this technote before it disappears https://www.ibm.com/support/pages/domino-server-unable-locate-mapped-drives-when-started-windows-service

Lotus Notes not running as scheduled