text:
Q: Amazon.com returns status 503 I am trying to get https://www.amazon.com content with Python Requests library. But I got an server error instantly. Here is the code:
import requests

response = requests.get('https://www.amazon.com')
print(response)

And this code returns <Response [503]>. Anyone can tell me why is this happening and how to fix this?

A: Amazon requires, that you specify User-Agent HTTP header to return 200 response:
import requests

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0'}
response = requests.get('https://www.amazon.com', headers=headers)
print(response)

Prints:
<Response [200]>

A: Try this,
import requests

headers = {'User-Agent': 'Mozilla 5.0'}
response = requests.get('https://www.amazon.com', headers=headers)
print(response)

A: You have not put the code from which you want the info.
The code should be like this:
import requests

response = requests.get('https://www.amazon.com')
print(response.content)

also you can use json, status_code or text in place of content


text:
Q: How does traverse inorder print values? class node:
def __init__(self,val):
        self.data = val
        self.left = None
        self.right = None

class Tree:
    def create(self,data):
        return node(data)

    def insert(self,node,data):

        if node is None:
            return self.create(data)

        if data < node.data:
            node.left = self.insert(node.left, data)

        else:
            node.right = self.insert(node.right, data)

        return node

    def search(self,node,data):
        if data == node.data or node is None:
            return node

        if node.data < data:
            return self.search(node.right, data)
        else:
            return self.search(node.left, data)
   [ <---
    def traverseinorder(self,root):

        if root is not None:
            print(root.data)
            self.traverseinorder(root.left)
            self.traverseinorder(root.right)
                                       --->]

def main():
    root = None
    tree = Tree()
    root = tree.insert(root, 10)
    print(root)
    tree.insert(root, 20)
    tree.insert(root, 30)
    tree.insert(root, 40)
    tree.insert(root, 70)
    tree.insert(root, 60)
    tree.insert(root, 80)

    print("Traverse Inorder")
    tree.traverseinorder(root)

I am new to data structures in python.
I don't understand the traverseinorder part. I print only thr root node data, but I didnt use either of print or return statements in self.traverseinorder(root.left) and self.traverseinorder(root.right) but the value is printed. How it is done ?
can anyone explain it in simple english please?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django redirect to a view with GET arguments set I'm having a hard time understanding the Django System of views and templates. All I want to do is inform the user of the status of his request- he pushes a button and gets an infobox with a message. The button in the Dashboard is at the root of the URL and sends a POST request to the Django Web App at book/.
In the view bound to this URL, I check if the booking is valid and want to inform the user (without the use of javascript) about the result. I wanted to send back a HTTP redirect to /?response=success or /?response=failed.
I've tried to give the view of the dashboard arguments and changed the URL regex but this did not lead where I want it to go. Currently, it's just
return redirect('dashboard')

and the URL conf is:
...
url(r'^$', app.views.dashboard, name='dashboard'),
url(r'^book/$', app.views.book, name='book'),
...

I really like Django - it's really easy to use. But in simple cases like this, it just drives me crazy. I would appreciate any kind of help.
Kind regards
Eric

A: You could just use the messages framework - that's what it's for.
Oh and yes: if that's just for displaying informations (no side effect on the server), you should use a GET request - POST is for submitting data for processing by the server.


text:
Q: How can I access the /etc of a pulled servicemix image I need to install a custom bundle in a dockerized servicemix image. To do so, I need to paste some files in the /etc directory of the servicemix image.
Could anyone help me doing this?
I've tried using the Dockerfile as follows:
But it simply doesn't work. I've looked through the documentation of the image, and the author tells me to use the command: docker run --volumes-from servicemix-data -it ubuntu bash and inspect the /servicemix, but it's empty.
    Dockerfile:
    FROM dskow/apache-servicemix
    WORKDIR .
    COPY ./docs /apache-servicemix/etc

...
    Command suggested by the author:
    docker run --volumes-from servicemix-data -it ubuntu bash

A: I was unfamiliar with this approach but, having looked at the source (link), I think this is what you want to do:
Create a container called servicemix-data that will become your volume:
docker run --name servicemix-data -v /servicemix busybox

Confirm this worked:
docker container ls --format="{{.ID}}\t{{.Names}}" --all
42b3bc4dbedf    servicemix-data
...

Then you want to copy the files into this container:
docker cp ./docs servicemix-data:/etc

Finally, run servicemix using this container (with your files) as the source for its data:
docker run \
--detach \
--name=servicemix \
--volumes-from=servicemix-data \
dskow/apache-servicemix

HTH!

A: Changes in the container will be lost until it is committed back to the image.
You can use this docker file https://hub.docker.com/r/mkroli/servicemix/dockerfile and your copy statement just before the ENTRYPOINT.
COPY ./docs /opt/apache-servicemix/etc


text:
Q: Can 3D rotation be inferred from its effect on directional observations? I am thinking about a camera-based gyro that can infer the 3D orientation of an observation platform, by locking onto two (or more) known directional beacons.
Assume there is a reference coordinate axis system (with an origin and defined axis-directions for x-y and z.)  Now, assume a mobile platform (mobile in 3D such as a spaceship) having its own local x-y-z axes.  A full-spherical camera system on the platform can sense the direction of any observed directional beacon (a visible point like a very-distant galaxy, so far removed that it's apparent direction does not change observed over the entire nav-space.  Let there be a lookup table of reference directions for these beacons (directions in reference coordinates).  You can think of each beacon having a unique 3D direction vector d =  [ x y z ], or if you prefer, equivalent azimuth-elevation angle-pair [ phi theta ].
Can you solve this problem?  Using as few as two recognized beacons, you acquire (measure) the directions of these beacons in your local axis system:
d1 ,  d2   (measured directions with platform's 3D orientation superimposed)
You lookup from the reference galaxy chart the known reference directions for these two beacons:
d1_ref ,  d2_ref
Can you suggest a math formula or algorithm that crunches these 4 pieces of data into the 3D orientation of your observational platform (in relation to reference axes)?  I.e., can you turn your spherical hi-res camera into a gyroscope through software that combines your local directional observations to their known directions in reference coordinates?
An acceptable output would be a 3x3 rotational matrix, equivalent quaternion, or equivalent (roll, pitch, yaw) angles.

A: Many problems of this type can be solved by remembering that the columns of a transformation matrix are the images of the basis vectors. Using this fact, you can easily construct a pair of matrices that map between the reference and camera coordinate systems, respectively, and some common intermediate coordinate system. You then compose one with the inverse of the other to get the direct transformation.
In this case, you can use the coordinate system defined by the two measured reference objects as the common intermediate. For the third coordinate axis, take the cross product of the two vectors, which is guaranteed to be linearly independent of them (assuming that the two beacon vectors are linearly independent, i.e., not scalar multiples of each other). If $\mathbf d_1$ and $\mathbf d_2$ are the coordinates of the beacons in the reference frame and $\mathbf d_1'$, $\mathbf d_2'$ the coordinates measured by the camera, then the matrix that maps from the intermediate coordinate system to the reference coordinate system is simply: $$M_{\text{ref}}=\begin{bmatrix}\mathbf d_1 & \mathbf d_2 & \mathbf d_1\times\mathbf d_2 \end{bmatrix}$$ and from the intermediate coordinate system to the camera's: $$M_{\text{cam}}=\begin{bmatrix} \mathbf d_1' & \mathbf d_2' & \mathbf d_1'\times\mathbf d_2' \end{bmatrix}.$$ We want to know what the the camera's coordinate axes are in the reference frame, i.e., the images of the unit basis vectors under the camera-to-reference-frame mapping. Per the observation made at the start of this answer, these are the columns of $M_{\text{ref}}M_{\text{cam}}^{-1}$. This matrix maps from one orthonormal coordinate system to another, and, as is easily verified, $\det(M_{\text{ref}}M_{\text{cam}}^{-1})=1$, so it is indeed a rotation. Note that you don't need unit vectors for this, nor does the order in which you take them matter, as long as it's consistent between the two matrices.
This is a theoretical result that assumes perfect data, but will work well with high-resolution measurements. In practice, to compensate for noise and other inaccuracies in the measurements, you'd more likely instead use observed positions of many more reference objects and compute a best-fit rotation from them.


text:
Q: Scripted dynamic update not working in ElasticSearch I am using the below code to update a document in elasticsearch
client.update({
   index: 'myindex',
   type: 'mytype',
   id: '1',
   body: {
     script: 'ctx._source.tags += tag',
     params: { tag: 'some new tag' }
   }
}, function (error, response) {

});

However, this throws a compile error. When I replace tag by params.tag above, it appends null to the present field i.e. identifies params.tag as null.

A: I encountered a similar confusion.  This document shares the example you have in your question.  On the other hand, this document shares a different example (which I got to work).
Your update statement would be something like this :
client.update({
    index: 'myindex',
    type: 'mytype',
    id: '1',
    body: {
        script: {
            inline: 'ctx._source.tags.add(params.tag)',
            lang: 'painless',
            params: {
                tag: 'some new tag'
            }
        }
    }
}, function (error, response) {
    // handling of error/response
});

** Notice the .add instead of the += for the case when adding to an array.


text:
Q: Probability measures equipped with weak topology, is $P\mapsto P(A)$ measurable? Let $X$ be a compact metric space and $\mathcal{M}(X)$ be the set of probability measures on $X$ equipped with the topology of weak convergence. So $\mathcal{M}(X)$ itself can be viewed as a compact metrizable space. Let $A\subseteq X$ be any measurable set in $X$, is the map
$$\mathcal{M}(X)\rightarrow [0,1]~,~~P\mapsto P(A)$$
measurable?

A: The map $P\mapsto \int f \,dP$ from $(M(X),{\cal B}(M(X)))$ to $(\mathbb{R},{\cal B}(\mathbb{R}))$ is measurable for all bounded, Borel $f$ on $X$. In particular, for $f={\bf 1}_A,$ the map $P\mapsto P(A)$ is measurable.
Proof: If $f$ is a continuous function, then  $P\mapsto \int f \,dP$ is continuous by
the definition of weak convergence of measures, and hence is also measurable.
Now apply the functional Monotone Class Theorem. We use Theorem 2 at the link, with
$${\cal H}=\left\{f\in {\cal B}_b(X): P\mapsto \int f\,dP\mbox{ is measurable}\right\},$$
and conclude that ${\cal H}={\cal B}_b(X).$


text:
Q: PowerShell not loading assemblies for use when fired from command line or batch script As stated in question, found a very weird bug in Powershell when running from command line or batch file.
Expected behaviour of PowerShell command like Add-Type -AssemblyName is to load assembly specified as the argument to that command and then we should be able to use that assembly for the next command we run, even when we do this process in batch script or command prompt.
But that doesn't work when we run this in batch file or command prompt:
@echo off && SETLOCAL ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS
net file 1>NUL 2>NUL
if not '%errorlevel%' == '0' (
    pushd "%~dp0" & powershell Start-Process -FilePath "%0" -ArgumentList "%cd%" -verb runas >NUL 2>&1 & popd
    exit /b
)
cd /d "%1" && set "ScptDir=%1"

PowerShell "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::Clear()"
endlocal && exit

OR
@echo off && setlocal
@pushd %~dp0 & fltmc | find "." && (powershell start '%~f0' ' %*' -verb runas 2>nul && exit /b)
whoami
:: PowerShell "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::Clear()"
type NUL | clip.exe
popd && pause && endlocal && exit

These doesn't clear the Windows System clipboard contrary to what anyone would expect. Also tried PowerShell "& {Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::Clear()}", but no change.
Any changes or workaround in this to make it work ??

A: *

*The Windows clipboard is a user-specific feature.

*

*A given clipboard instance is tied to a given user's OS session (window station, typically the desktop of the interactively logged-on user).

*All locally executing processes launched in the OS session of a given user share the same clipboard - even if such processes impersonate other users. (By contrast, sensibly, the clipboards of the OS sessions of distinct users are distinct.)

*Thus, for a user's given OS session, regular and elevated (run-as-admin) processes use the same clipboard.

*

*Whether elevation happens in the context of the current user account depends on whether that user is a member of a group with administrative privileges. If so, only a yes/no UAC dialog is presented, and, if confirmed, the elevated process runs with the same user identity.

*However, as explained above, even if you used different credentials for elevation, the resulting process would still see the same clipboard.

*Setting or clearing the clipboard does not require elevation.

*

*Note that clearing the clipboard with [System.Windows.Forms.Clipboard]::Clear() and equivalent methods has no impact on the opt-in clipboard history feature available since Windows 10. That is, it clears only the clipboard's current content, not the previous copied entries that are already stored in the history.

*

*Therefore, your batch file should work, and it does when I try it.

*If you're simply looking to clear the current user's clipboard from a batch file (whether elevated or not), use the following (note: technically, this doesn't clear the clipboard but sets it to an empty string):
type NUL | clip.exe

*

*From PowerShell, a simpler alternative to [System.Windows.Forms.Clipboard]::Clear() is to use Set-Clipboard $null, but note that in PowerShell (Core) 7+, which supports only copying text to the clipboard, this too - like type NUL | clip.exe in a batch file - copies an empty string to the clipboard instead of clearing it.


text:
Q: Drag and drop text from TRichEdit to ListBox without affecting text selection I have a richedit(richedit1) and a listbox(listbox1),
I want to drag the richedit1.text  without affecting its text selection. here some code:
procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;State: TDragState; var Accept: Boolean);
begin
     Accept := (Source is TRichEdit) ;
end;

procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
begin
    if Source is TRichEdit then ListBox1.Items.Add(RichEdit1.SelText);
end;

When i set RichEdit1.DragMode to dmAutomatic, draging works fine, but i can not select text in richedit by mouse.
I know one solution is Like this:
procedure TForm1.RichEdit1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if (Sender is TCustomRichEdit) and (ssCtrl in Shift) then
       TCustomRichEdit(Sender).BeginDrag(False);
end;

But i don't want to drag by holding ctrl key;
Do you have any better idea?

A: In the OnMouseDown event, you can detect if the mouse is being clicked inside of an existing selection that is 1+ characters in size, and if so then start dragging. Look at the EM_CHARFROMPOS and EM_GETSEL messages for that.


text:
Q: How to plot two dataframes in the same area chart and difference them by dark and light colors? I have two dataframes, let's say the first one corresponds to operational power plants and the second one to pipeline power plants. I want to plot both in the same area chart. They should be differenced by dark and light colors as the plots below. I have tried to insert a column into each dataframe and set it as an index (besides Country and fuel). I could't either set a new columns as an index or plot the dataframes in the same plot. I really appreciate some idea to execute that.
df1
              2010  2020  2030  2040  2050
Country  Fuel
A        Gas   100   110   120   130   140
         Coal  100   110   120   130   140
df2
              2010  2020  2030  2040  2050
Country  Fuel
A        Gas   100   110   120   130   140
         Coal  100   110   120   130   140

A: I find that hierarchical indexes get in the way for certain tasks (like this one) and it is better to do all of the manipulation on a flat dataframe. In the steps below, I use reset_index to turn the index levels into ordinary columns, and then set_index to put them back again in preparation for the plotting step.
# reset the indexes, and add a new column to both dataframes
df1.reset_index(inplace=True)
df1['Plant Type'] = 'Operational'

df2.reset_index(inplace=True)
df2['Plant Type'] = 'Pipeline'

# concatenate the two dataframes
df_combined = pd.concat([df1, df2])

# set the index back to how it was, but also include the new column, and then plot
df_combined.set_index(['Plant Type', 'Country', 'Fuel']).plot.area()


text:
Q: Issue when open a installed web app from Mobile (add to home screen) I have created a web app, PWA, and made it possible to add to Homescreen. When I add it to my mobile and try to open it, it doesn't open and Chrome stops working.
The same web app is working when launched from a desktop.
Here my manifest file:
   {
    "gcm_sender_id": "********",
    "name": "*** **",
    "short_name": "***",
    "description":"**",
    "icons": [{
      "src": "icons/** 512x512.png",
        "sizes": "128x128",
        "type": "image/png"
      },
      {
        "src": "icons/** 512x512.png",
        "sizes": "512x512",
        "type": "image/png"
      }
    ],
    "start_url": "/",
    "display": "standalone",
    "background_color": "#032d31",
    "theme_color": "#032d31"
  }

A: If you want you can have a look at an article I wrote about it, maybe you find a missing setting.
Another thing: "gcm_sender_id"is obsolete and no more used (maybe this triggers the error). You should use FCM now (Firebase Cloud Messaging) that implements the Web Push interface and does not need to put anything in the web manifest.


text:
Q: Storing NSFont to document Our picture editing cocoa application allows the user to add a string to a photo. This string has an associated NSFont object. We want to store this NSFont object in the saved document. Is using archiving NSFont using NSCoding the best way around?

A: I would have thought you would be better off storing an NSFontDescriptor, since that way you have more control over exactly which font you use when your editing app finds itself opening a file on a machine that doesn't have the font that was used when the file was saved.


text:
Q: Cart/Catalog Price rule for a set of products only I am trying to set cart price rules for some products if they are together in the cart.
I am using Magento 1.7.0.2
For example:
If product A and B are in the cart I want to make 11 percent for both but not for any other product.
For example:
If Product A and B are in the cart together with product C I want to apply the rule only to Product A and product B but not Product C.
I tried to set two different rules but it did not work, I tried to set one rule for both but then the quantity became an issue, cause I check if the cart has more than 1 products and that means the same product lets say Product A can have 2 as quantity and the rule is being applied on it in this case but I dont want it.
My statement must be like:
If there are more than 1 products and if one of them Is product A and one of the others is Product B set a discount only for Product A and Produt B but not for any other. So not to cart totals but to individual Products that I want to set a discount.
I also tried with catalog price rules but I couldnt get it work even this far.
Any help is appretiated.
Cheers

A: You can solve your problem in a simple way using Promotion Cart Rules
I tried it and it works look at this configuration:

try to understand my images, use your own products. If you lose just ask .


text:
Q: how to fix range within a form I made a form with five options to order books. Every option is a different input type itself. The problem is that each rule doesn't stay inline. The contact form also moves to right. It should look like example 1. what went wrong with my code? please see my complete code atached.
Thanks

Katheryn Stockett - The Help:

<input id="range" type="range" min="0" max="15" step="5" list="range-lijst">
    <datalist id="boeken">
        <option value="0" label="0">
        <option value="5">
        <option value="10" label="10">
        <option value="15">
  </datalist>
Bestel 0,5,10 of 15 exemplaren

all options should stay inline.

body  {
    background-color:oldlace;
}

.bg {
    height: 100%;
}

 form button#submit
{
text-align: center;
margin: 4px;
display:inline;
}

input[type=submit] {
  background-color: black;
  color: white;
  padding: 30px 55px;
  box-shadow: 2px 5px #888888;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  float: right;
}

.leftFloated{
  float:left;
}

label{
    width: 480px;
    display: inline-block
}

input[type="radio"] {
        margin-left: 10px;
        display: inline
        }

Boeken bestellen

Op deze pagina kunt u snel en gemakkelijk uw favoriete boeken bestellen die in de top 5 staan. U kunt per boek aangeven hoeveel u er van wilt bestellen. Let wel op dat bepaalde boeken beperkt beschikbaar zijn. Dit is aangegeven bij het boek.

 Bestel hier uw boeken

Khaled Hosseini - A Thousand Splendid Suns:
      <input id="schrijver" name="aantal boeken" type="number" value="0" min="1" max="10">  max. 10 exemplaren

Paulo Coelho - The Alchemist:
      <input id="auteur" name="boeken" type="number" value="0" min="1" max="99"> max. 99 exemplaren

Katheryn Stockett - The Help:

      <input id="range" type="range" min="0" max="15" step="5" list="range-lijst">
      <datalist id="boeken">
         <option value="0" label="0">
         <option value="5">
         <option value="10" label="10">
         <option value="15">
      </datalist>
      Bestel 0,5,10 of 15 exemplaren

Miguel de Cervantes - Don Quixote
      <input type = "radio"
         name = "radSize"
         id = "5"
         value = "1" />
      5
      <input type = "radio"
         name = "radSize"
         id = "10"
         value = "10" />
      10
      <input type = "radio"
         name = "radSize"
         id = "20"
         value = "20" />
      20

Khaled Hosseini - The Kite Runner

      <select name="aantal boeken">
      <option value="geen">0</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      </select>

         <input type="submit" value="Bestellen">

Geef hier uw adresgegevens op

         <form action="/action_page.php" method="post">

               Naam:
               <input type="text" id="naam">

               Adres:
               <input type="text" id="adres">

               Postcode:
               <input id="pc3" pattern="[0-9] {4}\s[A-Z]{2}" title="Een postcode bestaat uit 4 cijfers, 1 spatie en 2 hoofdletters" placeholder="1111 AA">

               Woonplaats:
               <input type="text" id="woonplaats">

               E-mail:
               <input type="text" id="email">

               leverdatum:
               <input type="date" id="leverdatum">

               Bestand:
               <input type="file" id="bestand">

         </form>

A: Your label has 480px width. It prevents your inputs to stay in one line with their label. Change their properties like:
label /* If you want to set this style only on range inputs you should change it to label[for=range]*/ {
    float: left;
    clear: none;
    display: block;
    padding: 2px 1em 0 0;
}

input[type=radio],
input.radio {
    float: left;
    clear: none;
    margin: 2px 0 0 2px;
}

And if you want to keep form in left and button in right, you should wrap form in one div and button in another div and set their with in persent, and then wrap both divs in another div like below.

.content-wrapper:after {
  content: '';
  clear: both;
  display: block;
}

.form-wrapper, .button-wrapper {
  width: 70%;
  float: left;
}

 Bestel hier uw boeken

Khaled Hosseini - A Thousand Splendid Suns:
    <input id="schrijver" name="aantal boeken" type="number" value="0" min="1" max="10">  max. 10 exemplaren

Paulo Coelho - The Alchemist:
    <input id="auteur" name="boeken" type="number" value="0" min="1" max="99"> max. 99 exemplaren

Katheryn Stockett - The Help:

    <input id="range" type="range" min="0" max="15" step="5" list="range-lijst">
    <datalist id="boeken">
    <option value="0" label="0">
    <option value="5">
    <option value="10" label="10">
    <option value="15">
    </datalist>
    Bestel 0,5,10 of 15 exemplaren

Miguel de Cervantes - Don Quixote
    <input type = "radio"
    name = "radSize"
    id = "5"
    value = "1" >
    5
    <input type = "radio"
    name = "radSize"
    id = "10"
    value = "10" >
    10
    <input type = "radio"
    name = "radSize"
    id = "20"
    value = "20" >
    20

Khaled Hosseini - The Kite Runner

    <select name="aantal boeken">
     <option value="geen">0</option>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
    </select>

  <input type="submit" value="Bestellen">

A: I noticed that the html structure is different for each section that you want to be styled the same. To keep things consistent and eliminate potential issues, try using the same structure for each block. Looking at that, will fix that issue.
The structure below was used for one item:

        Paulo Coelho - The Alchemist:
            <input id="auteur" name="boeken" type="number" value="0" min="1" max="99">
             max. 99 exemplaren

yet, another section looked different like this:

Khaled Hosseini - The Kite Runner

    <select name="aantal boeken">
        <option value="geen">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>

Adapting the second block of code to mirror the structure of the second block fixes that layout issue, like so:

            Khaled Hosseini - The Kite Runner

            <select name="aantal boeken">
                <option value="geen">0</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>

In terms of the placement of your button, you have two options to place it to the right. The first is to absolute position it which can get tricky, or you have to visualize that there is content on the left in it's own container with float: left;, and the button is in it's own container with float: right;. This would look like this:

You would set then need to adjust the widths on the float-left and float-right class, and be sure to clear the floats on the container.


text:
Q: How to overlap an image on textview programmatically in constraintlayout? Im making a mental math app(this is my first app) and if user inputs correct number, i want it programmatically add a red circle on TextView in ScrollView like the image below. How can i acheive this in constraintralout? I searched for similar questions but nothing solved mine. Thanks in advance.

A: It is quiet simple.
First Make an item with the any layout as follows:
(I have used Constraint layout, you can use relative or any thing)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/number_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="56"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/red_circle_image_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="@+id/number_text_view"
        app:layout_constraintEnd_toEndOf="@+id/number_text_view"
        app:layout_constraintStart_toStartOf="@+id/number_text_view"
        app:layout_constraintTop_toTopOf="@+id/number_text_view"
        app:srcCompat="@drawable/circle" />
</androidx.constraintlayout.widget.ConstraintLayout>

XML Code For Red Circle: @drawable/circle
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="4dp" android:color="@android:color/holo_red_dark"/>
</shape>

The above code will create a view like the below image:

Now Reference the Textview and ImageView using Java or Kotlin:
Java:
TextView numberTV = findViewByID(R.id.number_text_view);
ImageView circleImgV = findViewByID(R.id.red_circle_image_view);

Kotlin:
val numberTV = findViewByID(R.id.number_text_view)
val circleImgV = findViewByID(R.id.red_circle_image_view)

You will need a on click listener where you will be toggling the visibility of the circleImgV
View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(v.getId() == R.id.number_text_view){
                if (circleImgV.getVisibility() == View.VISIBLE){
                    circleImgV.setVisibility(View.GONE);
                }else {
                    circleImgV.setVisibility(View.VISIBLE);
                }
            }
        }
    };

Now Set The on click listener to numberTV:
numberTV.setOnClickListener(onClickListener);

Changing the inside numbers have to be done via code in java or kotlin
Now Keep Reusing the above code for generating Complex views as follows or do it via code or use it recycler view (I am only showing an option) :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/include3"
        layout="@layout/stackoverflow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/include4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include" />

    <include
        android:id="@+id/include"
        layout="@layout/stackoverflow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/include3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include2" />

    <include
        android:id="@+id/include4"
        layout="@layout/stackoverflow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include3" />

    <include
        android:id="@+id/include2"
        layout="@layout/stackoverflow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/include"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />
</androidx.constraintlayout.widget.ConstraintLayout>

My Layout name is stackoverflow.xml


text:
Q: Lock any action on a page using JavaScript I am relatively new to JavaScript. I have developed an application with the Outsystems technology, where-in I present a pop-up to the user and once the user fills the information, the user clicks 'Save' button. Now I need to disable all the page contents as it takes a long time to save and in between that the user may click anything else.
So I need to lock the page using JavaScript, with a message that tells user to wait until the process finishes.(on-click of the 'Save' button)
Any hints ?
Thanks.

A: Simply add a full page fixed position overlay that says "Saving... Please wait." on it. You might even make it semi-transparent grey.

A: The absolutely dead-simple method would be a jQueryUI modal dialog. You can implement one with just a few lines of code, plus a little HTML markup and including the library:
$( "#dialog-modal" ).dialog({
        height: 140,
        modal: true
    });
});

However, you should take note: this, just like any other JavaScript solution, won't stop malicious users from interacting with your site when you don't want them to. The only true protection is to check all input from the user when it reaches your serverside code.

A: You could disable all inputs using JavaScript:
(in this case jQuery)
$(':input').attr('disabled', 'disabled');

But likewise that would not stop the doing something in another tab, or navigating away from the page, or refreshing it.

A: You can do something very simple, like apply a transparent div over the top of your page.  Say like this:
var overlay = $("
Loading...
");
$("body").append(overlay);

A: If you use jQuery (demo):
CSS:
.overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    background-color: #000;

    font-size: 24px;
    font-family: sans-serif;
    color: white;
    text-align: center;
}

JavaScript:
$('
in process...
')
    .addClass('overlay')
    .fadeTo(0, 0.4)
    .appendTo('body');


text:
Q: вылезает ошибка IndexError: list index out of range Во время выполнения программы вылезает ошибка: "IndexError: list index out of range".
Укажите, по возможности, на ошибку в коде, так как сам ее найти не могу.
def _get_weather(city: str = "Москва") -> list:
    request = requests.get("https://sinoptik.com.ru/погода-" + str(city))
    b = bs4.BeautifulSoup(request.text, "html.parser")

    p3 = b.select('.temperature .p3')
    weather1 = p3[0].getText()
    p4 = b.select('.temperature .p4')
    weather2 = p4[0].getText()
    p5 = b.select('.temperature .p5')
    weather3 = p5[0].getText()
    p6 = b.select('.temperature .p6')
    weather4 = p6[0].getText()
    result = ''
    result = result + ('Утром :' + weather1 + ' ' + weather2) + '\n'
    result = result + ('Днём :' + weather3 + ' ' + weather4) + '\n'
    temp = b.select('.rSide .description')
    weather = temp[0].getText()
    result = result + weather.strip()

    return result

сама ошибка
File "xxx", line 33, in _get_weather
   weather1 = p3[0].getText()
IndexError: list index out of range

A: Попробуйте такой вариант
import requests
from bs4 import BeautifulSoup

def _get_weather(city: str = "москва") -> str:
    request = requests.get("https://sinoptik.com.ru/погода-" + str(city))
    b = BeautifulSoup(request.text, "html.parser")

    # block with temperature
    temperature_block = b.find('ul', {
        'class': 'weather__article_main_right-table clearfix'
    })

    # columns
    columns_data = temperature_block.find_all('li')

    # night
    night_from = columns_data[0].find('div', {'class': 'table__temp'}).text
    night_to = columns_data[1].find('div', {'class': 'table__temp'}).text

    # morning
    morning_from = columns_data[2].find('div', {'class': 'table__temp'}).text
    morning_to = columns_data[3].find('div', {'class': 'table__temp'}).text

    # day
    day_from = columns_data[4].find('div', {'class': 'table__temp'}).text
    day_to = columns_data[5].find('div', {'class': 'table__temp'}).text

    # evening
    evening_from = columns_data[6].find('div', {'class': 'table__temp'}).text
    evening_to = columns_data[7].find('div', {'class': 'table__temp'}).text

    # result row
    result = 'Ночью: {} {}\n'.format(night_from, night_to)
    result += 'Утром: {} {}\n'.format(morning_from, morning_to)
    result += 'Днем: {} {}\n'.format(day_from, day_to)
    result += 'Вечером: {} {}\n'.format(evening_from, evening_to)

    return result

print(_get_weather())

Ночью: +22° +21°
Утром: +24° +29°
Днем: +30° +31°
Вечером: +29° +27°


text:
Q: How to report bugs for Widlfly Communitiy Editions? I'm using the CE of Widlfly, so I don't have any RedHat subscription.
Is there a way to report bugs to the CE?
Is there a way to get help from the experts on issues with the CE?
Thanks!
Greetings
Józsi

A: Well all you need is on WildFly website: https://www.wildfly.org/contribute/


text:
Q: Formula for $s_n = \sum_{i = 1}^n i^3$ Newton's Forward Difference Interpolation
Use Newton's Forward Difference formula to find an expression for $$
 S_n  = \sum_{i = 1}^{n} i^3$$

This is from an Introductory Numerical Analysis paper. I cannot figure out the connection between the expression an Newton interpolation. Any help would be appreciated. Just a hint would be amazing. Thanks.


text:
Q: Issue for facet wrap function I'd like to separate my result into two different plot using the facet wrap function, however, my codes seems to give me faulty plots where two different factors (genotype PsbS and T259D) were still shown in the plot despite the data of only one was being shown (This might sound confusing, please refer to my plots). Thanks! my plot
RE <- read_csv("Cq.csv")
view(RE)
data.frame(RE)
ggplot(data=RE, mapping = aes(x = factor(genotype), y = cq, fill= line))+
  geom_bar(stat = "identity", position = "dodge")+
  geom_errorbar(data=RE, aes(ymin=cq-SEM, ymax=cq+SEM), width=.2, position=position_dodge(width= 0.9))+
  theme_bw()+
  theme(text = element_text(size = 15))+
  facet_wrap(~genotype)

data.frame(RE)
   id genotype   line           cq       SEM
1   1     PsbS   L1.1 14.870601010 5.4970515
2   2     PsbS   L1.2 23.455655780 1.4763615
3   3     PsbS   L1.3 14.004065480 0.8800974
4   4     PsbS   L1.4  6.888686944 0.5056124
5   5     PsbS   L1.5  8.986116514 0.9482289
6   6     PsbS   L1.6  0.000703389 0.0000864
7   7     PsbS   L1.7 11.422758140 0.3682201
8   8     PsbS   L1.8  7.329694392 0.8226627
9   9     PsbS   L1.9  6.795220106 0.7286420
10 10    T259D L3.3.1 20.549244950 1.6416835
11 11    T259D L3.3.2 24.979360100 4.5510392
12 12    T259D L3.3.3 25.089471950 3.4598942

A: ~ facet.wrap(~ genotype, scales="free")


text:
Q: Clojure function throws a null pointer exception I've just begun to teach myself clojure and I'm having fun. However trouble began when I began to exec this function I wrote!
It's a simple function that accepts multiple number of arguments & returns the difference between the last and the first arguments.
(defn diff-last-first
   "gets the difference between the last & the first arguments"
   [& args]
   (- (get args (- (count args) 1)) (get args 0)))

I know that I can simply use the last function to get the last element of args, but I'm not able to understand why this is throwing a NullPointerException when I execute
(diff-last-first 1 2 3)

A: If you do want to access the nth value of a list, you can use nth:
(defn diff-last-first [& args]
   (- (nth args (dec (count args)))
      (nth args 0)))

But of course, as you pointed out in your question, it is more idiomatic to use first and last:
(defn diff-last-first [& args]
  (- (last args)
     (first args)))

A: (get (list :foo) 0) evaluates to nil.
Lists are not supposed to be accessed by index: it is a common design decision in Clojure to prevent such inefficiencies.

A: Ok, Got it!
@vemv was right! [& args] is a list and hence (get args 0) returns nil
Whereas (defn get-l-f [args] (- (get args (- (count args) 1)) (get args 0))) works as expected as args is a vector here!


text:
Q: jQuery $.position() acting different during the $(document).ready in chrome (webkit?) When I try to get the position of an element in the $(document).ready(function() { }); it gives a different (incorrect) value for position.top in chrome, but correct in firefox. It's off by 15-45px depending on which element it is getting the position for.
I have a list of items within a viewport that has overflow:hidden and I want to get the position of each of these items.

Item Info

Item Info

Item Info

Item Info

.viewport { position:relative; overflow: hidden; }
.item { margin-left: 10px; }

When I do $(".viewport .item").each(function() { var pos = this.position(); }); it will give values, but they're wrong.
Even weirder thing is, if I do this from the console (after the page is done loading) it will return the correct values. It seems like the incorrect values only appear during the $(document).ready.
Is there a way to resolve this so I can still do my positioning during the doc.ready?

A: position() (docs), like other functions in the offset module (and, more in general, in the css modules) depends on the actual position of the elements in the DOM, after they are rendered.
$(document).ready(), on the other hand, fires immediately after the DOM is constructed.
On modern browsers, it corresponds to DOMContentLoaded:

the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading

In ready, you can manipulate the DOM safely (attach events, etc.) but you may have problems if you "measure" it. For example, it does not wait for stylesheets to download, or for images to download and be rendered.
You ran into a very annoying problem, as it is extremely platform (browser + jQuery version) dependent: in our case, it was working on two browsers out of three, and even on the third it was working 99% of the time, which indicates it is probably a race condition (JavaScript is single-threaded, but the browser is not).
If you need to measure elements, you are much better off using $(window).load()


text:
Q: exec(gencat) failed (No such file or directory) I'm trying to compile the source code of Minix 3.3.0 OS and I got troubles as following.

    make[5]: exec(gencat) failed (No such file or directory)
    *** Error code 1

    Stop.
    make[5]: stopped in /usr/src/lib/libc
    *** Error code 1

    Stop.
    make[4]: stopped in /usr/src/lib/libc
    *** Error code 1

    Stop.
    make[3]: stopped in /usr/src/lib
    *** Error code 1

    Stop.
    make[2]: stopped in /usr/src/lib
    *** Error code 1

    Stop.
    make[1]: stopped in /usr/src
    *** Error code 1

    Stop.
    make: stopped in /usr/src
    #

I and I ran this command on my VM of Minix3:

    git clone git://git.minix3.org/minix src

And then I try to compile it by this command:
    cd src
    make build

And it failed with problems above. It seems like lacking of some files.
Bus how could it happen after I download the code from the official web?
This question has troubled me for a few days and I can't solve it.
Could someone do me a favour?


text:
Q: Generating random variables from a mixture of Normal distributions How can I sample from a mixture distribution, and in particular a mixture of Normal distributions in R? For example, if I wanted to sample from:
$$
0.3\!\times\mathcal{N}(0,1)\; + \;0.5\!\times\mathcal{N}(10,1)\; + \;0.2\!\times\mathcal{N}(3,.1)
$$
how could I do that?

A: Conceptually, you are just picking one distribution (from $k$ possibilities) with some probability, and then generating pseudo-random variates from that distribution.  In R, this would be (e.g.):
set.seed(8)               # this makes the example reproducible
N     = 1000              # this is how many data you want
probs = c(.3,.8)          # these are *cumulative* probabilities; since they
                          #   necessarily sum to 1, the last would be redundant
dists = runif(N)          # here I'm generating random variates from a uniform
                          #   to select the relevant distribution

# this is where the actual data are generated, it's just some if->then
#   statements, followed by the normal distributions you were interested in
data = vector(length=N)
for(i in 1:N){
  if(dists[i]<probs[1]){
    data[i] = rnorm(1, mean=0, sd=1)
  } else if(dists[i]<probs[2]){
    data[i] = rnorm(1, mean=10, sd=1)
  } else {
    data[i] = rnorm(1, mean=3, sd=.1)
  }
}

# here are a couple of ways of looking at the results
summary(data)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
# -3.2820  0.8443  3.1910  5.5350 10.0700 13.1600

plot(density(data))

A: Already given perfect answers, so for those who want to achieve this in Python, here is my solution:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

mu = [0, 10, 3]
sigma = [1, 1, 1]
p_i = [0.3, 0.5, 0.2]
n = 10000

x = []
for i in range(n):
    z_i = np.argmax(np.random.multinomial(1, p_i))
    x_i = np.random.normal(mu[z_i], sigma[z_i])
    x.append(x_i)

def univariate_normal(x, mean, variance):
    """pdf of the univariate normal distribution."""
    return ((1. / np.sqrt(2 * np.pi * variance)) *
            np.exp(-(x - mean)**2 / (2 * variance)))

a = np.arange(-7, 18, 0.01)
y = p_i[0] * univariate_normal(a, mean=mu[0], variance=sigma[0]**2) + p_i[1] * univariate_normal(a, mean=mu[1], variance=sigma[0]**2)+ p_i[2] * univariate_normal(a, mean=mu[2], variance=sigma[0]**2)

fig, ax = plt.subplots(figsize=(8, 4))

ax.hist(x, bins=100, density=True)
ax.plot(a, y)

A: It's good practice to avoid for loops in R for performance reasons. An alternative solution which exploits the fact rnorm is vectorized:
N <- 100000

components <- sample(1:3,prob=c(0.3,0.5,0.2),size=N,replace=TRUE)
mus <- c(0,10,3)
sds <- sqrt(c(1,1,0.1))

samples <- rnorm(n=N,mean=mus[components],sd=sds[components])

A: In general, one of the easiest ways to sample from a mixture distribution is the following:
Algorithm Steps
1) Generate a random variable $U\sim\text{Uniform}(0,1)$
2) If $U\in\left[\sum_{i=1}^kp_{k},\sum_{i=1}^{k+1}p_{k+1}\right)$ interval, where $p_{k}$ correspond to the the probability of the $k^{th}$ component of the mixture model, then generate from thedistribution of the $k^{th}$ component
3) Repeat steps 1) and 2) until you have the desired amount of samples from the mixture distribution
Now using the general algorithm given above, you could sample from your example mixture of normals by using the following R code:
#The number of samples from the mixture distribution
N = 100000

#Sample N random uniforms U
U =runif(N)

#Variable to store the samples from the mixture distribution
rand.samples = rep(NA,N)

#Sampling from the mixture
for(i in 1:N){
    if(U[i]<.3){
        rand.samples[i] = rnorm(1,0,1)
    }else if(U[i]<.8){
        rand.samples[i] = rnorm(1,10,1)
    }else{
        rand.samples[i] = rnorm(1,3,.1)
    }
}

#Density plot of the random samples
plot(density(rand.samples),main="Density Estimate of the Mixture Model")

#Plotting the true density as a sanity check
x = seq(-20,20,.1)
truth = .3*dnorm(x,0,1) + .5*dnorm(x,10,1) + .2*dnorm(x,3,.1)
plot(density(rand.samples),main="Density Estimate of the Mixture Model",ylim=c(0,.2),lwd=2)
lines(x,truth,col="red",lwd=2)

legend("topleft",c("True Density","Estimated Density"),col=c("red","black"),lwd=2)

Which generates:

and as a sanity check:


text:
Q: Magento PWA Studio + Retrive Dropdown attributes value (Product) into front end I'm developing a ecommerce website using mageto PWA studio.
I have created "Subject" Product dropdown attribute from magento admin panel.
My Requirement is: I have to display the subject value into product detail page.
For that I have added following querys into exiting product page GraphQL query:
1st I tried in following way
export const ProductDetailsFragment = gql`
    fragment ProductDetailsFragment on ProductInterface {
        __typename
        categories {
            id
            breadcrumbs {
                category_id
            }
        }
        description {
            html
        }
        id
        media_gallery_entries {
            id
            label
            position
            disabled
            file
        }
        meta_description
        name
        price {
            regularPrice {
                amount {
                    currency
                    value
                }
            }
        }
        sku
        small_image {
            url
        }
        url_key
        subject
    }
`;

Output: Instead of subject value, It's giving option id of the subject.
2nd I tried in following way
export const ProductDetailsFragment = gql`
    fragment ProductDetailsFragment on ProductInterface {
        __typename
        categories {
            id
            breadcrumbs {
                category_id
            }
        }
        description {
            html
        }
        id
        media_gallery_entries {
            id
            label
            position
            disabled
            file
        }
        meta_description
        name
        price {
            regularPrice {
                amount {
                    currency
                    value
                }
            }
        }
        sku
        small_image {
            url
        }
        url_key
        subject {
            label
            value
        }
    }
`;

Output: Throwing console error

How can I over come from this issue..


text:
Q: LCAO (Linear Combination of atomic orbitals) for center nuclei with different charge It is known that if we want to study the dynamics of the electron cloud in, for example, an $H_2$ atom, i.e. the center consists of two protons with separation R, we can employ the method of LCAO. The Hamiltonian of the electron consists looks something like the following, where V is the Coloumb potential.
$$H=\frac{p^2}{2m}+V_L+V_R$$
Specifically, it works as following: label the two protons as L and R. And assume, for example, initially the electron is in $|211,L>$, i.e. the $n=2,l=1,m=1$ state of the L proton. Then we should take all six $n=2$ states, three for each proton, as the whole Hilbert space. Other states are ignored due to large separation of energy (This is actually dubious to me). It turns out this works pretty well in general.
However, there comes a question about its generalization when the two positive charge center carries different charge, for example, one $+e$ and the other $+2e$. $\textbf{ What is the criteria to determine what states should be included in the calculation?}$ Is it the case we should include $n=2$ state for one positive charge center while including $n=1$ state for the other center?


text:
Q: VBA Excel - How to know if a specific cell is affected by any macro? I have an excel file with hundreds of macros, where which macro has extensive code.
I need to change the layout of the cells and that includes moving some cells to another location.
My only problem is that after doing that i need to change the macros that interacts with that cell. Interacts as his value/formula was changed or his value is used in another operation
I can't search in the code for range("C2") for example because the cell can be affected in diferent forms like:
Range("C2")
Cells(2, 3)
Range("B1:E5")
Range(Cells(1, 1), Cells(10, 10))
Offset

Is there any whey that i can discover which macros are changing a specific cell?

A: Are you looking for a way to track a specific cell, or for a way to track all cells affected by VBA code? Also, "affected" as in "value was changed" or "formula was changed", or "cell was merged with another", "range was unmerged", or "borders were changed", or "backcolor was changed"? Is adding conditional formatting "affecting" a cell? Data validation?
And then, there are more ways a cell can be "affected", too. Without tracking the code as it's running, it could be hard to tell whether this myRange variable is affecting the cell you're looking for.. especially if methods like Range.Offset and Range.Resize are used.
Then ranges can be named, so Range("Foo") might be referring to a cell you're interested in, but you can't know that without verifying whether Names("Foo").RefersToRange includes that cell.
Short of carefully reviewing the code, I'm afraid you can't.
If no macro is highlighting any cell in bright yellow, you could always make a copy of the file and then handle Workbook_SheetChange in ThisWorkbook:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Target.Interior.Color = vbYellow
End Sub

You can easily add conditional logic here to only recolor modified cells from a specific sheet, or from a specific column or row.
Now remove or comment-out any Application.EnableEvents toggling everywhere in the code, and run your macros - the cells it affected (assuming a change in value is what we're after) should all be bright yellow.
If you need to know what code caused this, you can place a breakpoint there, and inspect the call stack:


text:
Q: set backlight time Is there any way to change backlight turn off TIME using programming(Preferred  c# or vb.net other c++ can be used too)? I guess, may be it is changed using registry info or API.
Manually, it is done by:
Setting > Backlight (Battery Power and External Power)
Thank you

A: Adjust the following registry keys (which is what the CPL does):
[HKEY_CURRENT_USER\ControlPanel\Backlight]`
    "UseBattery"=dword        ;if '1' turn off the backligh after "BatteryTimeout" seconds
    "UseExt"=dword:           ;if '1' turn off the backligh after "ACTimeout" seconds
    "BatteryTimeout"=dword:X  ;backlight timeout in seconds
    "ACTimeout"=dword:Y       ;backlight timeout in seconds

Then broadcast a WM_SETTINGCHANGE message.

A: ::SystemParametersInfo does it.
Specify uiAction parameter to SPI_SETBATTERYIDLETIMEOUT to adjust "battery timeout" and/or SPI_SETEXTERNALIDLETIMEOUT for "AC timeout".
See detailed information on msdn.


text:
Q: TypeError: this.$el.querySelector is not a function nuxt filepond I have these codes
my template codes
<no-ssr>
  <file-pond />
</no-ssr>

script codes for file-pond component
// Create component
const FilePond = vueFilePond(FilePondPluginFileValidateType, FilePondPluginImagePreview)

export default defineComponent({
  components: {
    FilePond
  },
  setup() {
...

and then I have this error
TypeError: this.$el.querySelector is not a function
    at VueComponent.mounted (vue-filepond.js?1501:123)
    at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1863)
    at callHook (vue.runtime.esm.js?2b0e:4235)
    at Object.insert (vue.runtime.esm.js?2b0e:3158)
    at invokeInsertHook (vue.runtime.esm.js?2b0e:6390)
    at VueComponent.patch [as __patch__] (vue.runtime.esm.js?2b0e:6609)
    at VueComponent.Vue._update (vue.runtime.esm.js?2b0e:3963)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4075)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495)
    at Watcher.run (vue.runtime.esm.js?2b0e:4570)
    at flushSchedulerQueue (vue.runtime.esm.js?2b0e:4326)
    at Array.eval (vue.runtime.esm.js?2b0e:1989)
    at flushCallbacks (vue.runtime.esm.js?2b0e:1915)

it seems like the file is running on server-side where DOM is not accessed but i don't know how actually to run this in client only , <no-ssr> and client-only are not working

A: Go to vue-filepond GitHub repo, download the file stored in lib/index.js.
Put it somewhere in your codebase and edit the mounted function, change this.$el.querySelector to document.querySelector.
Then you can directly import this file instead of importing as a node_module:
import vueFilePond from './file-pond.js'

Note: for Vue 2 use version 6.x of the plugin


text:
Q: Android Translate Animation Progress Callback I am using a Translate animation (borrowed from here) as follows:
TranslateAnimation a = new TranslateAnimation(
Animation.ABSOLUTE,200, Animation.ABSOLUTE,200,
Animation.ABSOLUTE,200, Animation.ABSOLUTE,200);
a.setDuration(1000);
a.setFillAfter(true);
animationSet.addAnimation(a);
myView.startAnimation(a);

Is there any callback that can give me the current position of myView? I would like to perform an action depending on myView's position while the animation is in progress.

A: Unfortunately not, but you could do something like this. Use
a.setRepeatCount(200);

and set the animation to move 1 pixel at a time
Animation.ABSOLUTE,1

then
 a.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                 // this will fire after each repetition
            }
        });

A: New solutions are available now as part of Spring Physics in android.
You can make use of DynamicAnimation.OnAnimationUpdateListener interface.
Implementors of this interface can add themselves as update listeners to a DynamicAnimation instance to receive callbacks on every animation frame.
Here is a quick code in kotlin to get started
// Setting up a spring animation to animate the view1 and view2 translationX and translationY properties
val (anim1X, anim1Y) = findViewById<View>(R.id.view1).let { view1 ->
    SpringAnimation(view1, DynamicAnimation.TRANSLATION_X) to
            SpringAnimation(view1, DynamicAnimation.TRANSLATION_Y)
}
val (anim2X, anim2Y) = findViewById<View>(R.id.view2).let { view2 ->
    SpringAnimation(view2, DynamicAnimation.TRANSLATION_X) to
            SpringAnimation(view2, DynamicAnimation.TRANSLATION_Y)
}

// Registering the update listener
anim1X.addUpdateListener { _, value, _ ->
    // Overriding the method to notify view2 about the change in the view1's property.
    anim2X.animateToFinalPosition(value)
}
// same for Y position
anim1Y.addUpdateListener { _, value, _ -> anim2Y.animateToFinalPosition(value)

}
You can listen to per-frame update of the animating view and animate/update other views accordingly.


text:
Q: Move Cannon.JS Body Toward Dynamic Position? I'm having a hard time wrapping my head around how to do this.
What I'm trying to do, is move a physics body, by the means of velocity, toward another body, until it reaches and hits said body. (Think AI following a player)
One solution is the following:
body.velocity.x = target.position.x-body.position.x;
body.velocity.z = target.position.z-body.position.z;

This has issues, though. One being that the velocity is higher depending on the distance between the two bodies. I would prefer a fixed speed. Another way would be to use the following example: Position a body in cannon.js relative to local rotation
But in this case, I need a way of rotating the quaternion, so it faces the target position, this with only knowing the 2 positions of the bodies.
So the question is, how do I calculate the velocity OR direction of the body, so that it can follow and collide with the target body, by using a fixed speed/velocity?

A: To get a fixed speed, .normalize() your velocity vector and then scale (.mult()) the result by the speed you want. The result will be a vector that always has the length you want.
To get a quaternion that makes your body face in a certain direction, you can use Quaternion.setFromVectors(u,v). This method creates a quaternion which will rotate u so it points in the same direction as v. If you set u to your forward vector and v to the direction you want the body to look, you will get the correct "look at" behavior. Note that the "forward" vector might be different for your game.
// Compute direction to target
var direction = new CANNON.Vec3();
target.position.vsub(body.position, direction);
direction.y = 0;
direction.normalize();

// Get the rotation between the forward vector and the direction vector
var forward = new CANNON.Vec3(0,0,1);
body.quaternion.setFromVectors(forward, direction);

// Multiply direction by 10 and store in body.velocity
var fixedSpeed = 10;
direction.mult(fixedSpeed,body.velocity);


text:
Q: Search Data on datagrid view vb/access can someone provide help?
Trying to search data from data grid view using binding source
I'm using 2 text box with 2 different columns to search but only one can be search on at a time
    Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
    StudenName.Enabled = False
    StudentNo.Enabled = True
    StudenName.Text = Nothing
End Sub

Private Sub RadioButton2_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton2.CheckedChanged
    StudenName.Enabled = True
    StudentNo.Enabled = False
    StudentNo.Text = Nothing
End Sub

and this where i need to input the search code
    Private Sub Search_Click(sender As System.Object, e As System.EventArgs) Handles Search.Click
    If StuNo.Checked = True Then
        'search code

    Else
        'search code
    End If
End Sub

what i read in other thread is using binding source find and filter,
I'm Using visual studio 10 and access as databased


text:
Q: What is the best way to add a jumper J1 to a circuit, wrt electronic design & simulation (i.e. w KiCAD & ngSpice) What is the best way to add a jumper J1 to a circuit, wrt electronic design & simulation (i.e. w KiCAD & ngSpice).?.
I originally tried to add a jumper J1 (symbol type GS2) to my circuit in eSim-2.1 (containing KiCad 4.0.7) on Windows 10 x64:

... this caused the program to crash... here're the last items in the console window:
==================================================

r0 srcpw net-_r0-pad2_ 1k

* u2 srcpw2 plot_v1

r2 gnd srcpw2 7k

r3 srcpw2 net-_r3-pad2_ 1k

v2 net-_r3-pad2_ gnd 10

j1 net-_j1-pad1_ gnd 1

Traceback (most recent call last):

File "projManagement Kicad.py", line 209, in openkicadToNgspice

File "frontEnd\DockArea.py", line 199, in kicadToNgspiceEditor

File "kicadtoNgspice\KicadtoNgspice.py", line 142, __init__

File "kicadtoNgspice\KicadtoNgspice.py", line 157, in createMainwindow

File "kicadtoNgspice\KicadtoNgspice.py", line 207, in createcreateConvertwidget

File "kicadtoNgspice\DeviceModel.py", line 209, in __init__

IndexError: list index out of range

… it may be due to user error, or a software bug, I am not sure ... perhaps I simply need correct value the jumper j1 perhaps?.. I've tried:

*

*GS2

*0 / 1

*open / closed

*false / true

... but they all crash the program.?.
After further research && feedback (both on here and other forums), I decided to try the more up-to-date KiCAD 5.1.12_1:

... and I ran into a very similar issue:
No compatibility mode selected!
Circuit: KiCad schematic
Error on line 8 :
jp1 net-jp1-pad1 net-jp1-pad2 jumper_2_open
Unable to find definition of model
Error: circuit not parsed.

… when trying to run the built-in [Spice Simulator].
Which tends to imply to me that I'm missing something perhaps, vs an inherent software issue.
I can't see I'm the only person who wants a jumper in their schematic, that can then be further consumed by a board layout program, without their simulation failing.
So I'm curious what the 'best practice' is in the industry wrt adding/modeling for jumpers?
Thanks in advance for any help.

A: If the program crashes, then it's a software bug, not an electronics problem. Report it to the developers.

A: I'm not sure if this could be considered a 'best practice'; however, it is a work around I discovered (at least for KiCAD 5.1.12_1)...
With a related comment by @franzee (user on another site) I eventually figured out a way to solve the issue.
So I was thinking how can I maybe just "copy the model"… and that prompted me to look at the model for the basic resistors in the circuit and the "model" for the jumper… then, I just tried to add the info from the basic resistors to the J1 jumper:

And, voila! … success. I tested it with both values of 1e9 (open) && 0 (closed) and it responded correctly in both regards.  In addition, for completeness sake, another possibility for a closed version of the jumper would be to set Spice_Netlist_Enabled to N...  I'm not sure if that's any better/worse than using a 0 Ohm resistor.?.
I did try to do the same under eSim 2.1 & KiCAD v4.0.7:

... but I had exactly the same error.  I will note, that the alternate possibility from above for a closed version of the jumper of setting Spice_Netlist_Enabled to N did in fact work...  but I don't consider it resolved, since it only works "half way".
But again, I don't know if this is an industry best-practice, or just a hack.?. … i.e. was there an easier way or option I missed?


text:
Q: LostKeyboardFocus event not firing when textbox loses focus I am using the MVVM pattern with the help of MVVM light. When I click a button I change the visibility property that the textboxs' visibility is bound to. When I lose focus, the trigger should execute and collapse the textbox. The problem is that the textbox never loses focus.
<TextBox x:Name="TextBox"
                 Text="{Binding TextBoxText, Mode=TwoWay}"
                 Visibility="{Binding TextBoxVisibility}"
                 Grid.Row="0"
                 Grid.Column="0"
                 HorizontalAlignment="Left"
                 VerticalAlignment="Bottom"
                 Height="30" Width="100"
                 TextWrapping="Wrap">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="LostKeyboardFocus">
                <command:EventToCommand Command="{Binding CollapseTextBoxCommand}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>

CollapseTextBoxCommandchanges the TextBoxVisibility property to Visibility.Collapsed.
Here is the button
<Button Name="AddButton"
            Command="{Binding ShowTextBoxCommand}"
            Grid.Column="0" Grid.Row="1"></button>

ShowTextBoxCommand changes the TextBoxVisibility property to Visibility.Visibile.
Here is a recorded screencapture of the problem I'm talking about.
What should happen, is that when I click off the textbox, it should collapse the visibility.
Any help is much appreciated. Thanks.

A: I suggest looking at this older stackoverflow question TextBox LostFocus does not fire . I tried out a few things on a dummy project, and I couldn't get it to work with LostKeyboardFocus or PreviewLostKeyboardFocus as the other question suggests.
What I did try and I can confirm it worked, was to create an eventtrigger on the WPF window itself, to detect when clicking somewhere else other than the textbox:
<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseUp">
        <command:EventToCommand Command="{Binding ShowTextBoxCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Of course you can use MouseDown if you prefer.

A: I think it does nothing to the MVVM pattern, so I tried to replicate your issue simply using a Button, a CheckBox and a TextBox, where the CheckBox acts as a focusable control to help to remove the focus from the TextBox. Please try the following code snippet.
xaml:
<UniformGrid Columns="1">
    <TextBox Name="textBox"
             Text="Text is coming"
             LostKeyboardFocus="TextBox_LostKeyboardFocus" />
    <Button Content="getFocusButton"
            Click="AddButton_Click" />
    <CheckBox Content="dummyCheck" />
</UniformGrid>

xaml.cs:
private void TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    (sender as TextBox).Visibility = Visibility.Collapsed;
}

private void AddButton_Click(object sender, RoutedEventArgs e)
{
    textBox.Visibility = Visibility.Visible;
}

Based on your screen capture, the reason I think why your LostKeyBoardFocus event is not fired is because when your TextBox is focused, the black background you clicked is not focusable, so that the focus on TextBox is not lost at all.
Therefore, in my code snippet, I add a CheckBox. When TextBox is focused, its Visibilty will be collapsed once the  CheckBox is clicked and focused.


text:
Q: How do I access object property in Handlebars template? My Ember component JS looks like below;
row = {};
Ember.set(row[my.constants.fieldKey], "cssType", 'leftPadding')

and my component HBS looks like below;
{{my-field cssType=(get row (concat (my-field-key 'SECTION_ID' 'FIELD_ID') '.cssType'))}}

To summarize, I only wanted to understand how can I achieve the equivalent of following JS code in hbs dynamically ?
row['my-field-key'].cssType

A: Your composition of get and concat template helpers is absolutely fine. I've setup an ember-twiddle to verify that this approach is working. You could find it here.
You might have an issue with your my-field-key template helper but it's hard to tell cause that code is missing. Also a reproduction in an ember-twiddle would be very helpfull.


text:
Q: El campo con el atributo 'required' eliminado sigue validando después del submit Tengo un formulario para enviar varios campos. Dos de ellos son para cambiar una contraseña.
No es necesario completar estos campos de contraseña antes de enviarlos. Sin embargo, si uno de ellos se rellena, agrego el atributo 'required' a ambos campos cuando se modifica a través de jQuery. Elimino los atributos cuando vacío uno de los campos y el otro ya se encuentra vacío.
En la mayoría de casos funciona, con una excepción que explico en el siguiente caso de uso:

*

*Relleno password

*password2 se encuentra vacío

*Envío el formulario

En este caso, la validación para password2 aparece, pero si quiero eliminar todo y enviar de nuevo, no puedo:

*Borro lo que se encuentra en password

*Envío de nuevo el formulario

*La validación para password2 aparece de nuevo. Incluso si el atributo 'required' no aparece en la fuente HTML

¿Por qué me sigue validando ese campo si el 'required' ya está eliminado?

$('#password').change(function() {
        if($(this).val() != ''){
            $(this).attr('required', true);
            $( '#password2' ).attr('required', true);
        }else{
            if($('#password2').val() == ''){
                $(this).removeAttr('required');
                $( '#password2' ).removeAttr('required');
            }
        }
    });
    $('#password2').change(function() {
        if($(this).val() != ''){
            $(this).attr('required', true);
            $('#password').attr('required', true);
        }else{
            if($('#password').val() == ''){
                $(this).removeAttr('required');
                $('#password').removeAttr('required');
            }
        }
    });

<form id="edicionPerfilForm" action="actor/edit.do" method="post">

            Password
            <input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">

            Repeat password
            <input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">

   <button name="save" type="submit" class="btn btn-dark">Send</button>
</form>

A:

$('#password').change(function() {
        if($(this).val() != ''){
            $(this).prop('required', true);
            $( '#password2' ).prop('required', true);
        }else{
            if($('#password2').val() == ''){
                $(this).prop('required', false);
                $( '#password2' ).prop('required', false);
            }
        }

        mostrar_estados_password();

    });

    $('#password2').change(function() {
        if($(this).val() != ''){
            $(this).prop('required', true);
            $('#password').prop('required', true);
        }else{
            if($('#password').val() == ''){
                $(this).prop('required', false);
                $('#password').prop('required', false);
            }
        }

        mostrar_estados_password();
    });

    function mostrar_estados_password() {
      if ($('#password').prop('required') == true) {
          alert('Password está requerido');
        }
        else {
          alert('Password NO está requerido');
        }

        if ($('#password2').prop('required') == true) {
          alert('Password2 está requerido');
        }
        else {
          alert('Password2 NO está requerido');
        }
    }

<form id="edicionPerfilForm" action="actor/edit.do" method="post">

            Password
            <input id="password" name="password" class="form-control" type="password" value="">

            Repeat password
            <input id="password2" name="password2" class="form-control" type="password" value="">

   <button name="save" type="submit" class="btn btn-dark">Send</button>
</form>

A partir de HTML5 se dejó de considerar a algunos atributos como tales para empezar a considerarlos como propiedades. Como bien te indica el compañero @iMangas deberías dejar de usarlo como atributo y empezar a usarlo como propiedad. Modificando tu código he puesto unos alerts a modo de escuchadores y he modificado el tratamiento de los atributos required para tratarlos como propiedades.
De esta manera podrás comprobar en que estado está cada uno de los paswords antes de darle al botón de "Enviar".
Añadir que la lógica de programación la tenías bien planteada, tan solo te faltaba manejar bien la propiedad required.

A: El problema en tu código es que tienes que modificarlo como property, no como attributo:
Marcar como requerido:
$( '#password' ).prop('required',true);

Desmarcar como requerido:
$( '#password' ).prop('required',false);

Te dejo un ejemplo de tu código funcionando.
Aunque no veo la necesidad de agregar o quitar la propiedad required según el usuario llena los datos, ya que lo hace por su cuenta.
https://codepen.io/anon/pen/OqWXZj


text:
Q: Heroku error after adding Tailwind and CRACO I recently added TailwindCSS to my React application following these steps: https://tailwindcss.com/docs/guides/create-react-app
Now the challenge is, when I deploy to Heroku, which has buildpack https://github.com/mars/create-react-app-buildpack installed, I get the error:
Error injecting runtime env: bundle not found '/app/build/static/js/*.js' from
Since I had to change the build script in package.json to
"build": "craco build"
My question is, does CRACO build my application to a different folder from what Heroku expects? Or is my problem possibly caused by something else?
Here is my package.json
{
  "name": "nantoo-react",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "flow": "flow",
    "format": "prettier --write 'src/**/*.{js,jsx}'",
    "heroku-postbuild": "npm rebuild node-sass"
  },
  "dependencies": {
    "@craco/craco": "^6.1.2",
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.3.0",
    "autoprefixer": "^9.8.6",
    "axios": "^0.21.1",
    "body-scroll-lock": "^3.1.5",
    "bootstrap": "^4.5.2",
    "browser-image-compression": "^1.0.14",
    "cropperjs": "^1.5.9",
    "env-cmd": "^10.1.0",
    "eslint": "^7.27.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^3.4.0",
    "eslint-plugin-react": "^7.23.2",
    "flow-bin": "^0.151.0",
    "jquery": "^3.5.1",
    "mobile-detect": "^1.4.5",
    "node-sass": "^4.14.1",
    "p-sleep": "^1.1.0",
    "postcss": "^7.0.35",
    "prettier": "^2.3.0",
    "prettier-eslint": "^12.0.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-facebook-login": "^4.1.1",
    "react-modal": "^3.12.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "react-slick": "^0.27.13",
    "react-tinder-card": "^1.3.1",
    "react-toastify": "^6.2.0",
    "react-tour-onboarding": "^1.15.63",
    "reactour": "^1.18.1",
    "slick-carousel": "^1.8.1",
    "socket.io-client": "^3.0.4",
    "styled-components": "^5.2.1",
    "tailwind-scrollbar-hide": "^1.0.3",
    "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.1.4",
    "web-vitals": "^0.2.4"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "engines": {
    "node": "14.x",
    "npm": "7.x"
  },
  "devDependencies": {}
}

And my craco.config.js is
module.exports = {
  style: {
    postcss: {
      plugins: [require("tailwindcss"), require("autoprefixer")],
    },
  },
};


text:
Q: How to display data from DB2 database with SQL query in php I'm using php to build a simple front end web application to my db2 database. This php query connects to the database and pulls the data from my selected table. I'm trying to insert my data into an html table to display it better (the rows are showing up in array formatting right now due to the "db2_fetch_array" function. How do I put my data into an html table? My php code is below, what should I add? Most questions I could find only dealt with mySQL and didn't have the same specification as I do.

<title>DB Testing</title>

<?php
//db2 express c (v10.5)
$database = "database";
$user = "db";
$password = "password";

$conn = db2_connect($database, $user, $password);

if($conn) {
echo "DB2 Connection succeeded.
";
}
    else{
    exit("failed".db2_conn_errormsg());
    }

$sql = "select 'JUNK', apple, banana, orange, cake, grapes, egg from
kitchen";

//db2_execute executes a sql statement that was prepared by db2_prepare
if($stmt){
    $result = db2_execute($stmt);
    if(!$result){
        echo "exec errormsg: " .db2_stmt_errormsg($stmt);
        }
    echo '
';
while($row = db2_fetch_array($stmt)) {
    echo '
';
    echo '' . $row['apple'] . '	';
    echo '' . $row['banana'] . '	';
    echo '' . $row['orange'] . '	';
    echo '' . $row['cake'] . '	';
    echo '' . $row['grapes'] . '	';
    echo '' . $row['egg'] . '	';
    echo '
';
}
echo '
';
}else {
echo "exec errormsg: ".db2_stmt_errormsg($stmt);
}
db2_close($conn);

?>
<?php
function print_r2($val){
        echo '
';
    print_r($val);
    echo '
';
    }

    ?>

A: I assume the syntax error here:
$sql = "select rows from table ;

is the result of you changing your query to ask this question. In any event, fix it, the query string is not closed. Also, I guess you don't have a field named "rows" in your table, you need to list the columns you want.
You already have the right loop, just change the
 tags with a table structure:
echo '
';
while($row = db2_fetch_array($stmt)) {
    echo '
';
    echo '' . $row['columnName'] . '	';
    // repeat with your other columns
    echo '
';
}
echo '
';


text:
Q: python matplotlib label/title wrong character This is a partial cross-post to this question.
Here is a minimal example of my code:
import matplotlib.pyplot as plt

x = [0.0, 0.25, 0.5, 0.75, 1.0]
y = [7.0, 3.0, 5.0, 1.0, 0.0]

II = 2

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)

# un-comment title as needed:
#plot_title = r"A$_" + str(II) + r"$"
#plot_title = "A$_" + str(II) + "$"
plot_title = (r"A$_%s$" % (str(II)))
print plot_title
plt.title(plot_title)
plt.show()

There are three different versions of the same plot-title-string. The print plot_title above gives the correct raw string for each case:
A$_2$

However, none of those approaches shows the correct string in the figure (independent of the back-end I use). The output in the figure  reveals this relation between the input integer value and the output:
$0$ -> E
$1$ -> £
$2$ -> N
$3$ -> ®
$4$ -> X
$5$ -> ¸(cedille)
$6$ -> b
$7$ -> ¿
$8$ -> j
$9$ -> 3

I am using python 2.6.6 and matplotlib 0.99.1.1 -- I have no control over these versions and will have to do with them.
How should I change my input to get the desired output?
Edit
Inspired by this question/answer I tried all the different fonts my system knows:
import matplotlib.font_manager as font_manager

for i in range(0,len(sorted(font_manager.findSystemFonts()))):
    plt.rcParams['font.family'] = os.path.basename(sorted(font_manager.findSystemFonts())[i])[:-4]

And generated a plot for each font and the above example. While I got different fonts for the text, the one subscript I care about, $_2$, did not change and was always shown as N.
EDIT 2
I have upgraded to matplotlib 1.3.0 and the issue is gone. This leaves me thinking it had to do with version 0.99.1.1
To me, this is still not satisfactory, because I would have liked to know why it was behaving in this way.
EDIT 3
I came across this question: Superscript in Python plots
The answer suggests that the issue may arise from using A$_2$ instead of $A_2$.
Unfortunately, this did not change the output in this case.

A: I am using matplotlib version 1.3.1 and python version 2.7.8.
I was having a similar problem. I was writing
ax1.set_yticklabels(['$10^4$','$10^5$','$10^6']$'

The 1 would render as a phi symbol. The 0 would render as E. The 4 would render as a Xi... so on.
I was able to 'fix' it by using '$\mathregular{10}^\mathregular{4}$' which is kind of cumbersome but it does the job.

A: I had a similar problem. This minimal example:
from matplotlib.pyplot import *
subplot( 111, title=r"$\mathcal{O}\left( N^3 \right)$" )
show()

was rendered to:

Adding matplotlib.rc('text', usetex=True) at the beginning solved the problem for me:
from matplotlib.pyplot import *
matplotlib.rc('text', usetex=True)
subplot( 111, title=r"$\mathcal{O}\left( N^3 \right)$" )
show()

This line makes matplotlib use LaTeX instead of the internal mathtext engine, which seems to be a subset of LaTeX, although superscripts should still work. Using LaTeX requires a working LaTeX installation, as well as dvipng and ghostscript, also it is slower. So this solution might only be worth trying if you have these prerequisites installed anyway.
I opened an issue here.
After some time-costly tests I found out, that downgrading from fonts-lyx 2.2.0-2 to 2.1.4-2 also solved the problem for me. fonts-lyx is a dependency of python-matplotlib-data, but no specific version is specified, resulting in this problem. Although I don't have enough techical knowledge to be able to say what changes to a font are incompatibel with programs using it.


text:
Q: Identity Generation error with EF5 In my DbContext, I have an override of the SaveChanges method to generate a Guid for entities to be added to the Database. This works fine except in the case of a shared primary key.
It generates different Id instead of one to be shared by the entities. Is there a way to check the type of Relationship?
  public override int SaveChanges()
  {
      foreach (var entry in ChangeTracker.Entries().Where(e => e.State == EntityState.Added))
      {
          var t = entry.Entity.GetType();
          if (t.GetProperty("Id") == null)
              continue;

          var info = t.GetProperty("Id").GetCustomAttributes(typeof (DatabaseGeneratedAttribute), true).Cast<DatabaseGeneratedAttribute>();
          if (!info.Any() || info.Single().DatabaseGeneratedOption != DatabaseGeneratedOption.Identity)
          {
              if (t.GetProperty("Id").PropertyType == typeof(Guid) && (Guid)t.GetProperty("Id").GetValue(entry.Entity, null) == Guid.Empty)
                  t.GetProperty("Id").SetValue(entry.Entity, Guid.NewGuid(), null);
          }
      }
      return base.SaveChanges();
  }


text:
Q: What is the correct format for the address (&) and indirection operator I've seen many different ways of writing the address-of operator (&) and the  indirection operator (*)
If I'm not mistaken it should be like this:
//examples
int var = 5;
int *pVar = var;

cout << var << endl; //this prints the value of var which is 5

cout << &var << endl; //this should print the memory address of var

cout << *&var << endl; //this should print the value at the memory address of var

cout << *pVar << endl; //this should print the value in whatever the pointer is pointing to

cout << &*var << endl; //I've heard that this would cancel the two out

What would happen if for example you wrote &var as & var with a space between the two? Common syntax I have seen: char* line = var;, char * line = var;, and char *line = var;.

A: Firstly, int *pVar = var; is incorrect; this does not store the address of var, but it stores the address "5", which will lead to a compilation error saying:

main.cpp: In function 'int main()':
main.cpp:9:15: error: invalid conversion from 'int' to 'int*' [-fpermissive]
    int *pVar = var;
                ^~~

var needs to be references in the initialization of *pvar:
int *pVar = &var;

Secondly, cout << &*var << endl; will also cause an error at compilation because var is not a pointer (int*) type variable:

main.cpp: In function 'int main()':
  main.cpp:19:13: error: invalid type argument of unary '*' (have 'int')
     cout << &*var << endl; //I've heard that this would cancel the two out
               ^~~

Now, to answer your question, adding whitespace between the referencing (&) operator and the pointer (*) operator will make absolutely no difference to the compiler. The only time it makes a difference is when you want to separate 2 tokens; like const and string for example. Running the following code just to exaggerate an example of what you are asking:
cout <<             &             var << endl;
cout <<                            *                    & var << endl;
cout <<                                   *pVar << endl;

Yields the same results as those from code without so many spaces:
0x7ffe243c3404
5
5


text:
Q: Why new component opening in the same page I am new to Angular, I have created very simple application with two component, I just want to navigate from one to another.
But second components opens in same(below the 1st) component. How can I open 2nd comp. in new page?
This is my code
 Privacy Policy

  <router-outlet></router-outlet>

app-route.module.ts file
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProductsComponent } from './products/products.component';
import { DeviceListComponent } from './device-list/device-list.component';

const routes: Routes = [
  { path: 'devicelist', component: DeviceListComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],

})
export class AppRoutingModule { }

Edit: 1
app.component.html
<router-outlet></router-outlet>

app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProductsComponent } from './products/products.component';
import { DeviceListComponent } from './device-list/device-list.component';

const routes: Routes = [
  {
    path: '',
    component: ProductsComponent,
  },
  { path: 'devicelist', component: DeviceListComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule { }

Comp1 file

          Product Name
          Compliance
          Failed
          Inprogress
          Reprocess

            Connected Courrier
             Privacy Policy
            Failed
            Inprogress
            Reprocess

            Admin App
            20
            Failed
            Inprogress
            Reprocess

Comp2 file

device-list works!

A: you have placed  <router-outlet></router-outlet> inside the first component.so whenever you navigate to the second component it will render inside the first component.
Note: Place  <router-outlet></router-outlet> in the app.component.html and create two separate components then will work

A: Place router-outlet></router-outlet> in the app.component.html, then create 2 separate components and give the links accordingly. This will help in navigating.

A: *

*Just add <router-outlet></router-outlet> in your app.component.html,nothing more than that.

*Add routings in your appModule

imports: [RouterModule.forRoot([
  { path: 'first', component: FirstComponent},
  { path: 'second', component: SecondComponent }
])],


text:
Q: Time dependent unit tests breaking when run in parallel, any workarounds? I have time dependent unit tests in which I have to simulate "now". I use JodaTime and when I need to simulate the value of now for purposes of time dependent testing I use DateTimeUtils.setCurrentMillisFixed(...), as suggested in the accepted answer in question Time dependent unit tests.
However, this has now caused problems when unit tests are run in parallel. Proper solution would be to make all classes obtain current time from a Clock dependency which could be mocked out in tests (as suggested in most upvoted answer in Time dependent unit tests). However, I will not have enough development resources to make that refactoring effort at the moment.
My question is is there a way to work around this by somehow specifying which tests may be run in parallel and which may not? Is there a way to work around this by using DateTimeUtils.setCurrentMillisProvider() ?
Testing framework is JUnit4, tests are run from maven.

A: Implement and set a CurrentMillisProvider that stores "now" in a ThreadLocal<Long>, as suggested in these Parallelism Tips:

P.S. Joda Time has DateTimeUtils which lets you change the current time used by the library. It's a global variable, but if you call DateTimeUtils.setCurrentMillisProvider with a ThreadLocal backed implementation, it'll be reasonably isolated when testing legacy code that uses Joda Time.

A: If the tests are started from one thread you can use a InheritableThreadLocal to store the current time.

A: Already mentioned by Joe implementation of DateTimeUtils backed with ThreadLocal would do the job.
Sadly, nobody has provided such implementation.
You can find one in https://github.com/restx/restx project: HERE
And later in your tests you can manipulate the time with:
ThreadLocalMillisProvider.setCurrentMillisFixed(now.getMillis)
ThreadLocalMillisProvider.setCurrentMillisSystem()

With classes which use JodaTime under the hood.
Enjoy!


text: Q: Irreducible Representations of $S4$ so ive been trying to get all the irreducible representations of $S4$ and their dimensions, I know that there are 5 because they are 5 conjugacy classes in $S4$ and that 2 have dimension 1 because $S4/[S4,S4] \cong \mathbb{Z}_2$, but i need to find the dimension of the other tree, where i tried using the formula $|S4|=1+1+n_3^2+n_4^2+n_5^2$. My question is is there any other way to find out the dimensions of these representations without having to find the right 3 numbers that squared give 22? Is there another way to do it ? Thanks.


text:
Q: (ubuntu) nginx: [emerg] bind() to 0.0.0.0:80 failed (13: permission denied) I need help figuring out the root cause of this permission denied error. What permissions does nginx need? Why is it so complicated?

A: the socket API bind() to a port less than 1024, such as 80 as your title mentioned, need root access.
here is "Bind to ports less than 1024 without root access"
and another easier way is to run nginx as root.

A: If see this msg after run "nginx -t", you dont have premission run as root "sudo nginx -t"

A: nginx needs root access. Just use

sudo nginx

next step along with your password

A: If you use a port bigger than 1024 with root privilege, but still got this problem, that's may be caused by SELinux:
Check this port, say 8024, in segange port
sudo semanage port -l | grep http_port_t

If 8024 doesn't exist in the port list, add it into segange port
sudo semanage port -a -t http_port_t  -p tcp 8024

###update in 2017.12.22
Sometimes your SELinux is disabled, you need to enforcing it first. Check the status of SELinux by
$ sestatus
More steps can read this wonderful article: https://www.digitalocean.com/community/tutorials/an-introduction-to-selinux-on-centos-7-part-1-basic-concepts

A: The best solution would be:
1) add user to sudoers ( my user is prod)
usermod -aG sudo prod

2) inside circus ( process manager ) append sudo before nginx executable, mine looks like this:
[watcher:nginx]
cmd = sudo /usr/sbin/nginx
args = -c /home/t/Projects/x_b_11/etc/nginx.conf -p /home/t/Projects/x_b_11

3) and finaly add line into file /etc/sudoers ( my user is prod). This line avoids error (sudo: no tty present and no askpass program specified). Probably need to restart session ( reboot). Enjoy.
prod ALL = NOPASSWD: /usr/sbin/nginx

A: Ubuntu uses AppArmor and not SELinux. The responses pointing to SELinux may not be that relevant to the OP.
For the others that Googled this: I also encountered this issue on a SELinux-enabled CentOS 7 machine. nginx would not bind port 80 and gave me error 13: permission denied despite having already run
setcap 'CAP_NET_BIND_SERVICE=+ep' /usr/sbin/nginx to allow the service to bind the port with a non-root user.
Temporarily setting SELinux to Permissive (sudo setenforce Permissive) allowed nginx to start. I then ran audit2allow -a which gave me
#============= httpd_t ==============

#!!!! This avc can be allowed using the boolean 'httpd_can_network_connect'
allow httpd_t ntop_port_t:tcp_socket name_connect;

Which meant the solution was to also run:
sudo setsebool -P httpd_can_network_connect on

After which you can set SELinux back to Enforcing (sudo setenforce Enforcing) and restart everything to verify.


text:
Q: Fedora 16 slow with multiple nvidia cards Emacs is slow to open, and there is a lag when moving the cursor position, opening files, and searching within frames when emacs is in maximized/full screen mode -- it's ok when it's only taking up part of the screen.
gedit appears to be ok, and running emacs in no window mode (emacs -nw) and No-X mode (emacs-nox) works great - things are snappy.
This system is an Intel quad-core box with 8gb memory. It has two nvidia cards, and three monitors.
Dual-head card:
EVGA GeForce GT 520 Graphics Card Video Card 01G-P3-1526-KR
Single-head card:
ZOTAC GeForce GT218 (ION) 512MB DDR3 DVI/HDMI PCI Express 1 Graphics Card, ION-GPU-A-E
I had been running both cards with three screens on Fedora 14 64bit, and everything worked fine. But when I upgraded to Fedora 16, the kernel and nvidia drivers upgraded, and things started running slow.
For example, in emacs, adding new lines to a file while it's fully maximized caused a lag while the screen redrew/repatined, as the lines slowly moved into position. If you hold down the backspace key and release it, it will take a few seconds for the cursor to stop and complete. It's like a buffer or repaint/redraw issue.
Things improve somewhat when I disable the GeForce GT218 card and only run two screens, both on the GT520, but there is still a lag in emacs when you backspace over a series of characters.
This happens in both Gnome and XFCE so it's not specific to Gnome. Gnome 3 is running in fallback mode, and I switched to XFCE thinking Gnome 3 was the culprit, but the lag remains.
Fedora 14 was fine, and all the hardware is the same.
$ uname -a
Linux love 3.1.2-1.fc16.x86_64 #1 SMP Tue Nov 22 09:00:57 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux
Any ideas?
nvidia bug report attached here...
http://www.nvnews.net/vbulletin/showthread.php?t=169199