Uninstall DevicePolicyManager app

Question: My App uses a DevicePolicyManager. If my users want to uninstall the app they have to do following steps:

SETTINGS -> Location and Security-> Device Administrator
deselect my App and then thay can uninstall it

I think that is not a good solution for a Play Store app. Can I do these steps for my users in the code so they can uninstall my app easily from their launcher?
Comment: An aside: Uninstalling an can be done from the Google Play app.
Answer: Yes you can. Do it like this:
<code>  DevicePolicyManager dpm;
 ComponentName admin;
          try
          {
            dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
            admin = new ComponentName(YourActivity.class, AdminReceiverActivity.class);
            if(dpm.isAdminActive(admin))
            {
                dpm.removeActiveAdmin(admin);
            }
          }
     catch(Exception e)
     {
        e.printStackTrace();
     }
     finally
     {
          Intent intent = new Intent(Intent.ACTION_DELETE);
          intent.setData(Uri.parse("package:" + this.getPackageName()));
          startActivity(intent)
     }
</code>

Uninstall DevicePolicyManager app


pymongo - how to append values to array?

Question: I am trying to create a database if it is not there already in mongo, and then create a collection in the database; then insert/update a document (which contains two keys, called erp and dataset whose value is a list of strings) in the collection. I know how to upsert a document like,
self.connection = pymongo.MongoClient(host=db_host, port=db_port)
self.connection.datasets.datasets.update_one({'erp': 'erp1'},
                                             {'$set': {'data_set': ['database1']}},
                                             upsert=True)

When the document is inserted into mongo for the 1st time, create a list with string(s) as values for the field 'data_set', but how to maintain/update the list of strings that whenever a new string comes in, just append the existing list for data_set.
UPDATE.
The working query
connection.erp_datasets.erp_datasets.update_one({'erp_name': 'erp1'},
                                                {'$push': {'data_set': 'database1'}}, upsert=True)

Answer: I think what you're looking for a $push update operator.

The $push operator appends a specified value to an array.

self.connection.datasets.datasets.update_one(
   {'erp': 'erp1'},
   {'$push': {'data_set': 'database1'}}
)


Why does turning on one light turn off a different light?

Question: I have a ceiling fan with a light and another light with switches on opposite sides of the wall. One side has a double switch which goes to the fan with a light and the other a single three way switch which goes to a light in the pantry. They both run off the same power. When I turn on one switch to run the light on the fan the light on the other side of the wall goes off and vice versa.
How do I fix this problem?
Answer: You mentioned having a 3 way switch for the pantry.  Is there actually a second switch somewhere that is also supposed to control the pantry light, or did someone just throw in a 3 way switch in a situation where a normal, single pole switch would have worked?  How many screws are present on the switch that controls your fan and fan light, not counting the green grounding screw?
Where does the power enter this circuit?  It could enter the box with the double light switch, the box for the pantry light switch, the box the fan is mounted on, or the box that the pantry light is mounted on.
Helping you rewire this mess to work properly is going to require detailed information about exactly what wires are present in each location.  There are several "right" ways to do the wiring in this situation, and picking the RIGHT "right" way for you will depend upon what wires are already present.
I'm going to go out on a limb with one possible answer to your question.  Just keep in mind that it's only a guess since I don't have all of the information needed to know for sure.
You know how a duplex receptacle has 2 sets of connections on it, and you can run power in to the top two screws and out through the bottom two screws and on to the next outlet, right?  Well, it may be possible that some very inexperienced person in the past saw a 3 or 4 way light switch and thought they could do the same thing.  If they tried to daisy chain the power between light switches the way you would do it between receptacles, and they chose just the right (or, in this case, WRONG) way to attempt it, it could lead to your current situation.
In any case, the situation needs to be fixed sooner rather than later.  The fact that your lights are functioning this way indicates that whoever did the electrical work had absolutely no idea what he was doing, and he VERY likely created unsafe conditions in your home.  If you aren't up to making a diagram of the current wiring configuration for us to look at here, then you really, really need to get an electrician in to sort out your problems before your house burns down or someone gets electrocuted.
Comment: I already figured it out,allI had to do is connect the wire that feeds from the fan to the power wire that goes to the black screw on the pantry three way switch, and yes a single pole switch is all that would of been needed, I looked at the diagram in my book and it seems that all the rest of the wires a hooked up correctly, thanks for your reply.
Answer: I already figured it out, all I had to do is connect the fan switch wire to the main power wire which goes to the black screw on the pantry three way switch, and yes   a single pole switch is all that  would of been needed.


TypeError: 'NoneType' object is not callable when using twice BeautifulSoup in the code

Question: I am using a BeautifulSoup in my code to find all occurrence of 'tr' and 'td' but received an error for the second usage in the code.
params = urllib.urlencode({'cmm': 'onion', 'mkt': '', 'search': ''})
headers = {'Cookie': 'ASPSESSIONIDCCRBQBBS=KKLPJPKCHLACHBKKJONGLPHE; ASP.NET_SessionId=kvxhkhqmjnauyz55ult4hx55; ASPSESSIONIDAASBRBAS=IEJPJLHDEKFKAMOENFOAPNIM','Origin': 'http://agmarknet.nic.in', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6','Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Cache-Control': 'max-age=0','Referer': 'http://agmarknet.nic.in/mark2_new.asp','Connection': 'keep-alive'}
conn = httplib.HTTPConnection("agmarknet.nic.in")
conn.request("POST", "/SearchCmmMkt.asp", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
soup = BeautifulSoup(data,'lxml')
result = soup.findAll("tr")
for y in result:
     row = BeautifulSoup(y,'lxml')
     k = row.findAll("td")
     for x in k:
        text = x.text
        print text

I received the below error
Traceback (most recent call last):
  File "commodity.py", line 15, in <module>
    row = BeautifulSoup(y,'lxml')
  File "/usr/local/lib/python2.7/dist-packages/bs4/__init__.py", line 175, in __init__
    markup = markup.read()
TypeError: 'NoneType' object is not callable.

Can anyone help me in resolving this issue and tells me correct way to use it.
Comment: Why are you cpassing `y` to `BeautifulSoup()` *again*? It is not a HTML string, it is a BeautifulSoup `Element` object.
Answer: You should not pass Element objects to BeautifulSoup() in the first place. Just remove the BeautifulSoup(y, 'lxml') call altogether:
for row in result:
    cells = row.findAll("td")
    for cell in cells:
        text = cell.text
        print text


EJB 2.0 and 3.0 life cycle

Question: Respected EJB Expert,
I am writing this email after lot of R&D. Recently I attended an interview wherea I was asked for EJB event cycle in terms of method invocation. I told them exactly whatever is mentioned at internet. But the interviewer was very dangerously expert. He asked me which component calls which method. Eg. who created the EJB home object and EJB Object.. I answered him with the info what I had... but then he confused me a lot especially by asking me who invokes the above methods in EJB 3.0. Basically he wanted me to tell the complete cycle starting from the client's JNDI lookup till client getting the response of the EJB method. He also wanted to know the enviornment in which the method or event occurs and who invokes the method or event.
I will be very thankful to you if can provide me with your inputs in the below format for all EJBs for 2.0 and 3.0 version
Environment ## Method-name or Event ## Method or Event Invoker
Comment: Try to explain better this: Environment ## Method-name or Event ## Method or Event Invoker
Answer: The correct answer is that the EJB container itself is responsible for creating the EJB home implementation, instantiating the EJB object instances, and invoking all lifecycle methods on the EJB object instance.
For EJB 2.x, the client looks up a reference to a home from JNDI, and the container provides an object that implements the home interface.  The container home object responds to the create method by returning another container proxy object that implements the component interface, which allows it to implement all the EJB qualities of service (transaction, security, java:comp, etc.) before delegating the actual bean instance that it creates.
For EJB 3.x, the situation is similar, except the container proxy object that implements the business interface is either injected directly or looked up directly from JNDI because the home interface is no longer required.

EJB 2.0 and 3.0 life cycle


Better way to fix imports after changing the package of imports

Question: So I have two projects, A and B. A is framework project. B is an actual project where other developers extend the framework.
The project structure of Project A was:
    A
    |_apple
    |_ant

But now I have added test cases in it changed a little bit structure of the project. The project structure now is
    A
    |_src
    |  |_apple
    |  |_ant
    |_test

apple and ant are imported in project B in couple of hundred files. Now I have to update the import paths as previously the import statements were
    from apple import *

but now they should be
    from src.apple import *

My question is that is there any easier way to handle this change than manually updating the reference in each file?
Comment: Use the function of Find in Files in your IDE to find all lines (or simply find and replace)
Comment: I think what you did is awful. I'd would have done the following: `src -> A -> apple, ant` and `test` outside `src`. This would avoid changing all the imports in other places since `src` should *not* be visible in your package
Comment: One of the golden rules of writing a framework is that you do nothing that will break working code. You've broken that rule. Go back and unbreak it.
Comment: @FindOutIslamNow Yes that is what I am doing but I was asking that if there is more cool way to solve this problem
Comment: @GiacomoAlzetta I didn't get your idea. A is my project then how can I put source folder outside the project. I would be really grateful if you can explain a little bit more.
Comment: @BoarGules That is true. I would really appreciate if you can give me some pointers on what I should have done.
Comment: Seems to me that @GiacomoAlzetta has a good suggestion.
Answer: I think that you should only use import src.apple (or from src.apple import ...) if src really is a package. But in this case that doesn't seem to be true.
If it's just a directory holding your Python sources (e.g. modules and packages), than you could add the directory to your Python search path. For example, add the directory to the PYTHONPATH environment variable, or in your main Python file add import sys; sys.path.append('src').


JScrollPane not working in null layout

Question:   import javax.swing.JCheckBox;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.JScrollPane;

public class ScrollJPanelDemo extends JFrame {
   public ScrollJPanelDemo(){
    setSize(480, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Select one or more options : ");
    JCheckBox jcb1 = new JCheckBox("Chandigarh");
    JCheckBox jcb2 = new JCheckBox("Mohali");
    JCheckBox jcb3 = new JCheckBox("Delhi");
    JCheckBox jcb4 = new JCheckBox("Noida");
    JCheckBox jcb5 = new JCheckBox("Mumbai");
    JCheckBox jcb6 = new JCheckBox("Kolkata");

    //creating JPanel to hold the checkboxes
    JPanel jpnl = new JPanel();
    jpnl.setLayout(null);
    jpnl.setOpaque(true);
    jcb1.setBounds(0,0,100,40);
            jcb2.setBounds(0,60,100,40);
            jcb3.setBounds(0,120,100,40);
            jcb4.setBounds(0,180,100,40);
            jcb5.setBounds(0,240,100,40);
            jcb6.setBounds(0,300,100,40);
    //adding check boxes and label to the JPanel
    jpnl.add(label);
    jpnl.add(jcb1);
    jpnl.add(jcb2);
    jpnl.add(jcb3);
    jpnl.add(jcb4);
    jpnl.add(jcb5);
    jpnl.add(jcb6);

    //creating the scroll pane that will scroll the panel.
    JScrollPane jscrlPane = new JScrollPane(jpnl);
    jscrlPane.setBounds(0,0,300,300);

        jscrlPane.setHorizontalScrollBarPolicy
       (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS) ;
   jscrlPane.setVerticalScrollBarPolicy
   (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    //adding that scroll pane to the frame.
    getContentPane().add(jscrlPane);
    setVisible(true);
  }

    public static void main(String args[]){
            new ScrollJPanelDemo();
        }

 }

I'm new in Java Swing and try to use of Scroll pane on my Java code, but it's not working. The Scroll Pane is add on the frame in vertical direction but not worked.
Comment: Urgent? Using a real layout will likely save you time & effort. See also [*Initial Threads*](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html).
Answer: You should create your own panel that extends JPanel containing all checkboxes  and in this panel override getPreferredSize() method like:
@Override
public Dimension getPreferredSize()
{
    return new Dimension( 300,300 );
}

and use it in your code:
...

// creating the scroll pane that will scroll the panel.
JScrollPane jscrlPane = new JScrollPane( new MyPanelWithCheckboxes() );
jscrlPane.setBounds( 0, 0, 300, 300 );
...

Comment: [Don't use `setPreferredSize()` when you really mean to override `getPreferredSize()`](http://stackoverflow.com/q/7229226/230513).
Comment: Sorry, but this solution does not work for me at all, unfortunately: JScrollPane shows its scrollers right away in almost full length and their length does not change when content of my class that extended JPanel changes. I mean it does not work for dynamic JPanel which is exactly my case.
Answer: I see OP already set desired/correct answer for him, yet that solution does not work with dynamic content (in my case vertically on Y axis) so I "repaired" or updated - if you will - Mateusz's original answer so that now it actually works even with dynamic JPanel content (like when you adding to it other components on the run which was my case).
Here is my code (works, using it myself):
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JPanel;

public class JPanelForNullLayoutScroll extends JPanel {

    int h;

    @Override
    public Dimension getPreferredSize() {

        if (getComponentCount() > 0) {
            h = 0;

            for (Component c : getComponents()) {
                h += c.getHeight();
            }

        } else {
            h = 0;
        }

        // as I do not need width recount
        //I set it to be taken directly from the component itself
        Dimension d = new Dimension(getWidth(), h);

        return d;
    }

}

You can use it then in your code by implementing it like:
int tableW = 300;
int tableH = 300;

// JPANEL WITH NULL LAYOUT
JPanelForNullLayoutScroll container = new JPanelForNullLayoutScroll();
container.setLayout(null);
container.setVisible(true);
container.setEnabled(true);
container.setBounds(0, 0, tableW, tableH);

// SCROLLER
JScrollPane scrollPane = new JScrollPane(container);
scrollPane.setAlignmentX(JLabel.LEFT_ALIGNMENT);
scrollPane.getVerticalScrollBar().setUnitIncrement(8);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(0, 0, tableW, tableH);

JScrollPane not working in null layout


Dot product between two vectors transformed by orthogonal matrices

Question: I am reading through the "Matrix Transformations" chapter of this book and more specifically on Orthogonal Matrices. I understand their properties and understand that multiplying vectors by them is an affine transformation, so the dot product between two vectors will be the same as between the same vectors multiplied by the same orthogonal matrix $\mathbf{M}$.
However this proof from the book confuses me to no end:

And more specifically this:
$$\mathbf{(Ma)\cdot (Mb)=(Ma)^T (Mb)}$$
What exactly is happening on the right side of the equation? Is the transpose of $\mathbf{Ma}$ somehow the reciprocal of the dot operation?
Answer: The idea here is that a dot-product can be interpreted as the product (as in matrix multiplication) of a row-vector and a column-vector. Note that vectors are considered to be "column-vectors" by default, so treating a vector as a row-vector means that we need to transpose it.
For example, if we have the vectors
$$
\mathbf u = \pmatrix{1\\2\\3}, \quad \mathbf v = \pmatrix{-2\\0\\1},
$$
then we can express the dot-product $\mathbf u \cdot \mathbf v$ as the matrix product
$$
\mathbf u \cdot \mathbf v = \mathbf u^T \mathbf v = \pmatrix{1&2&3} \pmatrix{-2\\0\\1} = (1)(-2) + (2)(0) + (3)(1) = 1.
$$
Note that there is a slight (and very common) abuse of notation happening here: we have the product of a $1 \times 3$ and $3\times 1$ matrix, which results in a $1\times 1$ matrix. However, instead of writing our answer as the $1\times 1$ matrix $[1]$, we think of it as simply being the scalar $1$.  In general, $1\times 1$ matrices are thought of as scalars.
From there the rest of the steps in the proof use the properties of the transpose as it relates to matrix-multiplication, then reinterprets the final $\mathbf a^T\mathbf b$ as a dot-product.
Comment: @GeorgiB.Nikolov Glad to help. If you're happy with my answer, I'd appreciate it if you could "accept" my answer by clicking the check mark ($\checkmark$) on the top-left of my answer.
Comment: Hey thanks for that, I think I get it now.
Comment: the final   converts ***a*** back to column vector so we can perform dot product between them. Thanks, I get it.
Answer: If you consider the vectors $Ma$ and $Mb$ to be $n\times 1$ matrices, then the product $(Ma)^T(Mb)$ is just matrix multiplication, $\sum_{i=1}^n (Ma)_i(Mb)_i=(Ma)\cdot (Mb)$.
We use this form of the dot product, so that we can expand the brackets and use the fact that the matrix product of $M$ and $M^T$ is the identity matrix.


Registry writes only 4 Chars

Question: When im try to write a RegEdit Key, he only writes only the first 4 Charaters of the file path.
HKEY hKey;
RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hKey);
RegSetValueEx(hKey, "Test", 0, REG_SZ, (BYTE*)file, sizeof(file));
RegCloseKey(hKey);

Comment: I can't reproduce this code because `file` is not defined.
Answer: sizeof(pointer) gives 4 on 32 bit systems. Try string::size (online documentation) instead.
std::string filename ("file.exe");
RegSetValueEx( ..., filename.size());

Answer: Apparently your file is a pointer. sizeof(file) is size of pointer in bytes, which is 4 on your platform.
What is file? How is it declared? What does it point to? Why are you using sizeof on it in order to determine how many bytes to write? If file is a pointer to a C-style string, then sizeof will not help you to determine the length of that string. You need strlen for that.
Comment: file is a char array
Comment: @noaaah an *array* or a *pointer to an array*?
Comment: @noaaah: Unlikely. Apparently `file` is a `char *` pointer.
Answer: If file is a char array, then...
RegSetValueEx(hKey, "Test", 0, REG_SZ, (BYTE*)file, strlen(file) + 1); // API says to include terminating NULL.

"The size of the information pointed to by the lpData parameter, in bytes. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters."
https://msdn.microsoft.com/en-us/library/windows/desktop/ms724923(v=vs.85).aspx

Registry writes only 4 Chars


find method vba run-time error 91

Question: There is a problem with the find method in below code.
c = Cells.find(wValue).Address

i always get run-time error 91: object variable or with block variable not set.
It worked perfectly when i tried it in a trial code without loop, but i can't really figure out, what exactly i need to change in order to make it work.
Do you have any suggestions on that?
Sub find()

Dim cRange As Range, rngQty As Range, z As Range
Dim Date1 As Integer
Dim c As String

With Application
        .ScreenUpdating = False
        .EnableEvents = False
End With

Set wkbZ = Workbooks("Order History.xlsm")
Set wkbY = Workbooks("Forecast Form.xlsm")

For Each z In wkbZ.Sheets("2015").Range(Range("A2"), Range("A2").End(xlDown))

Set rngQty = z.Offset(, 3)
Date1 = Month(z.Offset(, 4))

wValue = z.Value

wkbY.Activate

c = Cells.find(wValue).Address

Set cRange = Range(c)

cRange.Select

If Date1 = 1 Then
    Set rngPaste1 = Selection.Offset(, 3)
End If
If Date1 = 2 Then
    Set rngPaste = cRange.Offset(, 4)
End If
If Date1 = 3 Then
    Set rngPaste = cRange.Offset(, 5)
End If
If Date1 = 4 Then
    Set rngPaste = cRange.Offset(, 6)
End If
If Date1 = 5 Then
    Set rngPaste = cRange.Offset(, 7)
End If
If Date1 = 6 Then
    Set rngPaste = cRange.Offset(, 8)
End If
If Date1 = 7 Then
    Set rngPaste = cRange.Offset(, 9)
End If
If Date1 = 8 Then
    Set rngPaste = cRange.Offset(, 10)
End If
If Date1 = 9 Then
    Set rngPaste = cRange.Offset(, 11)
End If
If Date1 = 10 Then
    Set rngPaste = cRange.Offset(, 12)
End If
If Date1 = 11 Then
    Set rngPaste = cRange.Offset(, 13)
End If
If Date1 = 12 Then
    Set rngPaste = cRangec.Offset(, 14)
End If

rngPaste.Value = (rngPaste.Value) + (rngQty.Value)

wkbZ.Activate

Next

With Application
        .ScreenUpdating = True
        .EnableEvents = True
End With

End Sub

Comment: If `Find()` fails to make a match then it returns `Nothing`, so you need to test for that first
Comment: Do you get the error on the first iteration of the loop or an the second? And what value does z.Value return?
Comment: wkbZ.Sheets("2015") needs to be the activesheet when you run that or your for ... next will fail. see [Is the . in .Range necessary when defined by .Cells?](https://stackoverflow.com/questions/36368220/is-the-in-range-necessary-when-defined-by-cells)
Comment: `Set rngPaste = cRangec.Offset(, Date1 + 2)` you don't need all those `If` blocks!
Answer: Untested but should be close...
Sub find()

    Dim cRange As Range, rngQty As Range, z As Range
    Dim Date1 As Integer
    Dim rngSrch As Range
    Dim wkbZ As Workbook
    Dim wkbY As Workbook

    Set wkbZ = Workbooks("Order History.xlsm")
    Set wkbY = Workbooks("Forecast Form.xlsm")

    'fully-qualify all Range calls with a worksheet object
    With wkbZ.Sheets("2015")
        Set rngSrch = .Range(.Range("A2"), .Range("A2").End(xlDown))
    End With

    For Each z In rngSrch.Cells

        Set rngQty = z.Offset(0, 3)
        Date1 = Month(z.Offset(0, 4))

        'better to specify whether looking at full content or part..
        'also not clear which sheet you're searching?
        'notice no select/activate needed...
        Set cRange = wkbY.Sheets(1).Cells.find(what:=z.Value, lookat:=xlWhole)
        If Not cRange Is Nothing Then
            With cRange.Offset(0, Date1 + 2)
                .Value = .Value + rngQty.Value
            End With
        End If

    Next

End Sub

Comment: Man, you are the best. It runs so smooth. Thanks a lot!

find method vba run-time error 91


Install Windows7 side by side with ubuntu 12.04

Question:
Possible Duplicate:
How can I install Windows 7 after I've installed Ubuntu?

I had a Windows OS on my machine. One time, when I tried installing Kubuntu 12.04, I messed up the whole computer and it wouldn't boot up anymore. So, I installed Ubuntu 12.04 from a USB drive and it worked. Now, I need Windows for my school work. So, I wanted to ask if I can install Windows 7 without deleting Ubuntu 12.04 and how do I install it?
Answer: In order to install Windows 7 without messing Ubuntu, follow this steps:
You should create a partition for your Windows 7 installation, I recommend you to install GParted from the Software Center.
After you create your partition, install Windows 7 in the new partition.
Reboot, you should see that you no longer boot into Ubuntu, but in Windows 7, to boot into Ubuntu, put your Live CD in your PC and boot from it, then follow the instructions provided here.
If everything is done correctly, you should be able to choose the OS you want to boot from GRUB menu every time you turn on your computer.


Can I move the GNOME top bar (and status icons) to the side?

Question: I would like to have as much vertical screen space as possible, but I like having the status icons and time visible. Is there an extension to move the "top bar" to the left or right side, perhaps as part of a dock or side panel?
I'm aware of the Hide Top Bar extension as a fallback.
Answer: Since its October update, the Dash to Panel GNOME Shell Extension supports vertical panel orientation.
To install and enable the extension:

Make sure that you have chrome-gnome-shell installed:
sudo apt install chrome-gnome-shell

You also need the GNOME Shell integration browser extension installed. You can install it for Firefox or for Chrome-based browsers, depending on your choice of web browser.

Additionally, install Tweaks to access the extension's options (and a bunch of other useful GNOME settings):
sudo apt install gnome-tweaks

Now, you can visit the Dash to Panel GNOME Shell Extension webpage, toggle the switch on the right-hand side of the page to ON and click Install on the pop-up.

Then, press Alt+F2, input r and press Enter to restart GNOME Shell and make the extension take effect.

To enable the vertical panel:

Open Tweaks
Go to Extensions.
Click the cog icon next to Dash to Panel.
Set Panel screen position to Left or Right.


Stone Weierstrass theorem application

Question: Let $B$ be an algebra of continuous real valued function defined on a compact topological space $X$ which separates the points of $X$. Show that the closure of $B$ in $C(X)$ with respect to uniform metric is either all of $C(X)$ or else that there exist some $a \in X$ such that closure of $B$ is $ \{ f \in C(X):f(a)=0 \}$ .
Comment: I would strongly advise you familiarize yourself with MathJax.
Answer: Suppose that $B$ vanishes nowhere Stone Weirstrass implies that $B$ is dense. Otherwise, let $Z$ be the set of zeroes of $B$, $a\in Z$, if $b\in Z$ distinct of $a$, there exists $f\in B$ such that $f(b)\neq f(a)$ since $B$ separates the points, this implies $f(b)\neq 0$. Contradiction. We deduce that $Z$ is $\{a\}$.
https://en.wikipedia.org/wiki/Stone%E2%80%93Weierstrass_theorem#Locally_compact_version
Comment: how does it contain constant function 1?

Stone Weierstrass theorem application


How do I track Amazon packages by the "TBA" number?

Question: I have a tracking number from Amazon that starts with TBA that I'd like to track via their API. I've seen their getPackageTrackingDetails endpoint but it takes an integer as input and I get an error when I try to use a TBA number on that endpoint. I know it is possible somehow, since AfterShip can do it (just enter a valid tracking number that starts with TBA). I cannot find in Amazon's docs how to do it and Amazon customer support doesn't know how to do it, either.
Comment: Could it be as simple as not sending the "TBA" prefix? Maybe using [Network Monitor](https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor) on the AfterShip site could reveal the API parameters.
Comment: It looks like this question fails at the "asking for docs" hurdle for SO. Is the "TBA number" being presented in the wrong format, perhaps?
Comment: `I've seen their getPackageTrackingDetails endpoint but it takes an integer as input`. I've also asked their customer support but, somehow, Aftership can do it so I ask here.
Comment: Does aftership really do this? They claim to, but I just tried tracking an amazon shipment that's out for delivery by its TBA number, and aftership said it was not found.
Comment: I was able to do it with a number of TBA packages. Weird that it doesn't work for you.
Answer: You have to distinguish between the packageNumber (which is an integer) and the trackingNumber (which is a string). When creating your shipment, you will get the packageNumber. With that number you can call getPackageTrackingDetails.
The Shipping-Api seems to be the right endpoint to use. See https://github.com/amzn/selling-partner-api-docs/blob/main/references/shipping-api/shipping.md#get-shippingv1trackingtrackingid
The getTrackingInformation operation accepts a tracking number as an input parameter.
Comment: That isn't my question.
Comment: You can't use getPackageTrackingDetails with your Tracking Number. You have to use the package number. So you have to get this number first.

How do you get the tracking number at the moment? Via Api or via Seller Central?
Answer: Looking through the API documentation, there doesn't seem to be a good way to go from TBA number (if you can't just cut off those first three letters) to Package ID.
My order of operations on fixing this problem:

Chop the first three letters off the TBA variable you have, convert to integer, try it. Per Andrew Morton's comment.

What AfterShip may also be doing is going from the order ID. If the TBA is closely related to the order ID, the Amazon API will give you the information to go from Order ID -> Fulfillment Shipment -> Fulfillment Package -> Package ID.  You could then use the Package ID to get your package information. So I'd look at Order ID's as well as Package ID's to see if you could convert one to another.

Given Stevish's comment, it's possible that the TBA can be cut off the TBA number and used as a package number if there is only one package in the order, but things get more complicated in other situations.
If you're working on a site that has the seller Order ID stored on your side, that seems to be the intent they have for getting it through the API.


Intuition or wisdom for stability and instability properties of locally linear system. Boyce, p513, Table 9.3.1

Question:

Our instructor requires us to memorize this table for our differential equations exam. So I wonder if anyone has some deeper intuition or observation to help with this?
For example, I noticed that whenever eigenvalues $< 0$, the stability (for linear and locally linear systems) is stable. Why is this?
@snarski I'm terrified too for the exam. I write about the most general eigenvalue, when $r = \lambda \pm iu$. Solutions to $\mathbf{ x' = Ax }$ are, from BOYCE p161, $x(t) = e^{\lambda t}(\cos(ut) + i\sin(ut)).$  So when $\lambda <0$, then $\lim_{t \to \infty} x(t) = \lim_{t \to \infty} e^{\lambda t}(..) = 0$ ?
Comment: It terrifies me that you have to memorise this table and don't yet know why negative eigenvalues lead to local stability. In order to help you, we'll need to know (i) what you know about eigenvalues and eigenvectors of $2\times 2$ matrices and how $r_i$ relate to these (ii) what you know about solutions to equations of the form $\dot{x}(t) = f(x(t))$ and $\dot{x}(t) = Ax(t)$, where $A$ is a constant coefficient matrix. Please write out explicitly the basic tools you have in your class and what you know about them (where do $r_i$ come from, what is 'local' stability...)
Comment: @snarski i updated my question. please edify me now?
Comment: I can begin to help. What I wanted you to say was that $r_1$ and $r_2$ are the roots of $\lambda^2 - (a+d)\lambda + \det(A)$, where $A = \begin{pmatrix} a & b \\ c & d \end{pmatrix}.$ You cite Boyce & Duprima about the general solution, but you need to know how to obtain that solution yourself, and why it makes sense -- can you do this?

Your comment that if $\lambda < 0$, then $\lim_{t\rightarrow\infty} x(t) = 0$ is correct and is the reason for local stability.
Comment: To understand local stability, however, you need to understand basic Taylor expansions. In other words, to what extent the approximation $f(x) = f(x_0) + f'(x_0)(x-x_0) + E(x-x_0)$ is valid, where $E$ is the error and $E(x-x_0) \rightarrow 0$ as $x \rightarrow x_0$. In this example $f(x)$ is a real-valued function, but in the case where $f(x) = (f_1(x), f_2(x))$, $f'(x_0)$ will be a matrix $Df(x_0)$ (do you know this)?
Answer: The imaginary part only adds oscillations to the general magnitude behavior. So the result only depends on the real part of the eigenvalues. Negative real parts have falling eigenfunctions, positive parts have eigenfunctions that grow over all bounds.
To have (asymptotic) stability, you will need all real parts negative.
If only one real part is positive, there is at least one infinitely growing solution starting close to the fixed point, so the fp is instable.
If some real parts are zero (and all the other negative), the growth behavior depends on the multiplicity of the eigenvalue and, in the non-linear case, the higher order terms of the Taylor expansion.
It makes not really much sense to separate this discussion into real and complex eigenvalues, since the important point is their location on the positive or negative real-part half-plane. Of course, the shape of the two-dimensional phase pictures is different for complex conjugate pairs and pairs of unrelated real eigenvalues.


How do I associate files with the xml that references them in Python?

Question: I have two directories: assets and metadata.
The assets directory has a bunch of video files while the metadata directory has a bunch of existing xml files.
I want to calculate checksums and grab file sizes of all the assets and put them in the metadata that matches them. Those fields already exist, but are empty.
I'm parsing with element tree and am already able to get the file sizes and checksums, but I'm not sure how to get them into the right metadata.  The video files are named with an ID that is also present in the metadata and is already assigned to the variable 'id', so I thought I could associate them like this:
<code>for file in glob.glob("*.mov"):
    if file == (id + '.mov'):
        video_filename = file
    elif video_filename != (id + '.mov'):
        print(id, 'There is no video file associated with that ID!!!')
</code>
When I run the script, and it sees one of the other files first, I get the else if condition above.
How do I check that I have the correct video file for the xml and that the data is going into the right xml file?
Comment: If you're looking for the file that has a name that matches `(id + '.mov')`, then you're looking for a file with a specific name, right?  So why go through all of the files in the directory when you can just reference that one file directly by name?
Comment: Because I have multiple .xmls and multiple .movs.  I want to be able to run the script once and process all the files in the directory.
Comment: Then you need different logic.  You should be extracting the `id` from the filename.  You shouldn't have to go through all of the files in a directory for every `id`.  But you COULD do that.  If one of the files matches, then your code will work as it exists.  So then just don't do anything if the filename doesn't match...just remove your `elif` case (which, btw, could be just `else:`.
Answer:
Iterate over all the movie files and make a dictionary of {id:filepath} pairs.
Iterate over the xml files, for each metadata get the ID of its movie

and use that ID with the dictionary to look up the path to the correct movie file
process the movie file
put the new info in the metadata.


How to join two key values from map in dart?

Question: I have this List<Map>:
var listMap = [
        {
          "label": "Title",
          "align": "left",
          "width": 50
        },
        {
          "label": "Date Created",
          "align": "left",
          "width": 50
        },

];

I want to join label, align and width with |
So the final result is of type List<String> :
var finalResult = ["Title|left|50", "Date Created|left|50"];

How can i achieve finalResult?
Comment: `listMap.map((m) => m.values.join('|'))`
Answer: I have tried this
var listMap = [
        {
          "label": "Title",
          "align": "left",
          "width": 50
        },
        {
          "label": "Date Created",
          "align": "left",
          "width": 50
        },

];
  var newList = [];
  for (var e in listMap) {
    newList.add(e.values.join('|'));
  }
  print(newList);

Also @pskink answer is correct to!


What is the type of a by-value lambda capture of a reference?

Question: Look at this program (godbolt):
template <typename> struct TD;

void foo(int &par) {
    auto l = [par]() {
        TD<decltype(par)>();
    };
}

It intentionally doesn't compile, it uses a technique to make the compiler to display the type of par. Note that par is a by-value capture.
What is the type of par inside the lambda? Both gcc and clang give an error message which tells that par's type is int &:
<source>:5:9: error: implicit instantiation of undefined template 'TD<int &>'

On the other hand, MSVC complains about TD<int>:
<source>(5): error C2027: use of undefined type 'TD<int>'

If I change the standard to C++20 to MSVC, it also complains about int &.
The current draft standard says:
For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the referenced type if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an anonymous union shall not be captured by copy.
Which compiler is correct? Have something related changed in the standard? If par really should be reference according to the standard, then why? As far as I understand the cited text, it supposed to be the referenced type, which is just int.
(Note: printing out par's address in foo and in the lambda, they differ, so the compiler did make a copy. But then why is par in the lambda a reference? Did the compiler make an anonymous copy ofpar and then bind it to a non-const reference?)
Comment: [Demo](https://godbolt.org/z/e6jK8xeq4) with `[par2 = par]` as capture.
Comment: [cpprefrence](https://en.cppreference.com/w/cpp/language/lambda) has similar example  (`f3()`)(capture with `=`)
Comment: @Jarod42: I think the `par2 = par` construct obeys some other rule. Regarding `f3()`, yes, it has a similar example, the variable `r` is a reference there. The page talks about some transformation: `(transformation not considered)`. I'm not sure what it is about.
Answer: The correct type is int&, as explained in [dcl.type.decltype] p1.

otherwise, if E is an unparenthesized id-expression or [...], decltype(E) is the type of the entity named by E.
If there is no such entity, the program is ill-formed;

- [dcl.type.decltype] p1.3
par is an unparenthesized id-expression, and the type of the par entity is int&. It just remains to be shown that name lookup for the unqualified-id par finds the function parameter, not the captured variable in the lambda.
Name lookup does find the int& par parameter due to the rules in [expr.prim.id.unqual] p3, which have the following example:

float f() {
  float x, &r = x;

  [=]() -> decltype((x)) {
    // ...
    decltype(r) r1 = y1; // r1 has type float&
    // ...
  }
}

Even though par (or r in the standard example) is captured by copy, name lookup in an unevaluated operand does not find it.
A more detailed explanation of these rules can be found at regarding the type derivation of lambda-captured variables, which is iso compliant
Also, If you wrote an init-capture [par = par], the rules would apply again, and decltype would find the captured par.

Note: The C++20 wording for [expr.prim.id.unqual] may be easier to understand. This was changed in C++23 through p2036 Change scope of lambda trailing-return-type
Compiler Conformance
All compilers actually agree on this, but MSVC deviates in /permissive mode.
This is the default, so you're getting this surprising behavior.
/std:c++20 disables MSVC compiler extensions, so it is as if you had written /permissive-. Adding the /permissive- flag on its own also makes MSVC think that the type is int&.
You can find an example of this feature in Microsoft's documentation:

decltype(auto) x = cond ? a : b; // char without, const char& with /Zc:ternary

Comment: Thanks. I checked older standards (C++11, C++14), and it seems that this behavior is very intentional. If a capture is not ODR-used, the "original" variable is used. And there is a rule, that if `declspec((x))` is used, then even though it doesn't ODR use `x`, it still uses the captured variant. I just don't understand the reason. It is **very** unexpected that the same name refers to different entities depending on these rules.


UDPclient rate control in c#

Question: Im sending multiple udp packets consecutively to a remote pc. the problem is, if the amount of data is too high, some device somewhere between the channel experience buffer overflow. i intent to limit/throttle/control sending rate of the udp packets. can somebody give me some guide on how to find the optimal rate sending interval?
By the way, please stop suggesting tcp over udp. the objective is not to send data reliably, but to measure maximum throughput.
Comment: If you really want to measure throughput then send as much as you can and count on the other side.  You don't have to throttle to measure max throughput.
Comment: Of course I don't have a clue since you said: *the objective is not to send data reliably, but to measure maximum throughput.* and as far is measuring is concerned, my proposal will do just this.
Comment: @Daniel Mošmondor. i take it you dont have a clue on what the issues is. please dont spam.
Comment: @DanielMošmondor Let me explain. If you send udp packets without some method of throttle, the packet will eventually overflow network element between endpoints. When that happens, the endpoint will just drop packets. When that happens, there is no way you could tell the bandwidth between endpoints. Not to mention, some network elements used by telco will detect that situation as packet spams and immediately drop every udp packet from that ip. There are also issue of efficiency.
Comment: @DanielMošmondor If you think you can measure the bandwidth by measuring how much data you can send, how can you measure the bandwidth when you can send data as much as 1gb per second on a cat 5 cable? If you believe you can send udp packet as much as you can and be able to measure the bandwidth by counting on the other side, show it to the world and prove me wrong.
Answer: Trial and error. Point.

Make up a secnod connection (UDP or TCP based) that you use ONLY to send control commands.
Send stats there about missing packets etc. Then the sides can decide whether the data rate is too high.
Possibly start low then up the data rate until you see missing packets.

NEVER (!) assume all packets will arrive. Means: you need (!) a way to reask for missing packets. Even under perfect cnoditions packets will get lost sometimes.
If loss is ok and only should be minimized, a statistical approach is pretty much the only way I see to handle this.
Comment: Check RTP protocols. The problem you face is standard in things like real time voice / video transfer. RTP is using UDP and there is a control protocol for stuff like this.
Comment: to be honest, the 'decide' thing is pretty easy for non-robot(human). representing the problem in mathematical way is nontrivia. is there any papers, research on this topic? what is the keyword that i should google? my background is not computer networking, so...
Answer: Try this then:

Start with packets of 1KB size (for example).
For them, calculate how many packets per second will be OK to send - for example - 1GB ethernet = 100MBytes of raw bandwidth -> 100000 packets
create a packed so first 4 bytes would be the serial number, rest could be anything - if you are testing here, fill it with zeroes or noise (random data)
on sending side, create a packets and push them at the speed of RATE (previously calculated) for one second. calculate time spent, and Sleep() the rest of the time, waiting for new time slot.
on receiving end, gather packets and look into their serial numbers.  if packets are missing, send (another connection) some info to the sender about it.
sender, on info about lost packets, should do something like RATE = RATE * .9 - reduce sending rate to 90% of a previous one
sender should gradually increase rate (say 1%) every few seconds if it doesn't get any 'lost packets' message
after some time you RATE will converge to something that you wanted in the first place

Some considerations:
- if back connection is TCP, you'll have some overhead there
- if back connection is UDP, you can also have dropped packets here (because you are flooding the channel) and sender could never know that packets are dropped
- algorithm above won't solve missing data issue or out-of-order data issue, it will just measure the throughput.
Comment: Thanks Daniel. Have a look at my current implementation here http://stackoverflow.com/questions/4167278/how-to-calculate-bandwidth-using-c. Corrent me if im wrong, from what i understand, if i send data for 1 second, and the receiver received data for 2 second, that means i have to readjust my sending rate until i get 1 second send and 1 second receive? pardon my language. im not good at explaining myself. this by the way, remind me of some papers on bandwidth estimation. one of em is pathload.thanks.
Comment: Well, it's time you bang your head into it - you have all the info you need, now experiment until you get it right.  Programmers do that from time to time, it's fun and it's most valuable experience.  Have fun.
Answer: Despite your proposal that I don't suggest TCP over UDP, I have to.  In same paragraph you are stating that the main purpose of your test is to measure throughput - that is bandwidth - and only way to do it properly without to re-invent whole TCP stack is to actually USE TCP stack.
Large parts of TCP are designed to work with flow control issues, and when TCP streams are used, you'll get exactly what you need - maximum bandwidth for given connection, with ease and without 'warm water inventing'.
If this answer doesn't suit you, that probably means that you have to re-state your requirements on the problem.  They are in conflict.
Comment: sigh. what im trying to achieve is to measure how much data can flow through a channel. for example, on 1 mb channel, the maximum data can flow through the channel is 1mb. the bandwidth that you can get using tcp is the good data excluding packet headers, excluding the data that have to be retransmitted. with tcp, you ALWAYS have lower results that what it is.plus with udp, you can get more statistics than just bandwidth. i appreciate that you want to help. but please.
Comment: UDP has headers also.  I every protocol you'll have 'slack'.
Comment: of course udp have headers. i never said udp doesnt have headers, have i? but can you track how much data headers consume? can you track how much data in tcp has been retransmitted?
Comment: The problem with tcp is the inability to track how much packet is lost. The other problem with tcp for bandwidth measurement is data retransmission and tcp slow start. For example, you are sending 100Mbits of data over 100Mbits/s channel. The channel have packet loss rate of 50%. If using tcp, the results would be the channel is 50Mbits/s, which is wrong. The primary concern is not how much 'good' data the end user received, but how much bandwidth the channel can transmit. When a telco said that they provide 100Mbps/s bandwidth, they dont mean the user would received 100Mbps/s 'good' data.

UDPclient rate control in c#


"command 'gcc' failed with exit status 1" when running %%cython in jupyter notebook

Question: I have installed cython with conda
cython installation
After restarting the kernel, I have also loaded it without error using %reload_ext Cython.
However, when I try to run the following code
%%cython

import numpy as np

cdef int a = 0
cdef int g[10]
cdef int i

for i in range(10):
    g[i] = a
    a += i
print(g)

I get the error command 'gcc' failed with exit status 1.
I am fairly new to cython and have no idea on how to solve this or even what questions to search for.
The complete error log:
---------------------------------------------------------------------------
DistutilsExecError                        Traceback (most recent call last)
~/opt/anaconda3/lib/python3.7/distutils/unixccompiler.py in _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
    117             self.spawn(compiler_so + cc_args + [src, '-o', obj] +
--> 118                        extra_postargs)
    119         except DistutilsExecError as msg:

~/opt/anaconda3/lib/python3.7/distutils/ccompiler.py in spawn(self, cmd)
    908     def spawn(self, cmd):
--> 909         spawn(cmd, dry_run=self.dry_run)
    910

~/opt/anaconda3/lib/python3.7/distutils/spawn.py in spawn(cmd, search_path, verbose, dry_run)
     35     if os.name == 'posix':
---> 36         _spawn_posix(cmd, search_path, dry_run=dry_run)
     37     elif os.name == 'nt':

~/opt/anaconda3/lib/python3.7/distutils/spawn.py in _spawn_posix(cmd, search_path, verbose, dry_run)
    158                           "command %r failed with exit status %d"
--> 159                           % (cmd, exit_status))
    160             elif os.WIFSTOPPED(status):

DistutilsExecError: command 'gcc' failed with exit status 1

During handling of the above exception, another exception occurred:

CompileError                              Traceback (most recent call last)
<ipython-input-25-16f694f6508b> in <module>
----> 1 get_ipython().run_cell_magic('cython', '', '\nimport numpy as np\n\ncdef int a = 0\ncdef int g[10]\ncdef int i\n\nfor i in range(10):\n    g[i] = a\n    a += i\nprint(g)\n')

~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2357             if getattr(fn, "needs_local_scope", False):
   2358                 kwargs['local_ns'] = self.user_ns
-> 2359
   2360             with self.builtin_trap:
   2361                 args = (magic_arg_s, cell)

</Users/w849277/opt/anaconda3/lib/python3.7/site-packages/decorator.py:decorator-gen-128> in cython(self, line, cell)

~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

~/opt/anaconda3/lib/python3.7/site-packages/Cython/Build/IpythonMagic.py in cython(self, line, cell)
    331         extension = None
    332         if need_cythonize:
--> 333             extensions = self._cythonize(module_name, code, lib_dir, args, quiet=args.quiet)
    334             if extensions is None:
    335                 # Compilation failed and printed error message

~/opt/anaconda3/lib/python3.7/site-packages/Cython/Build/IpythonMagic.py in _build_extension(self, extension, lib_dir, temp_dir, pgo_step_name, quiet)
    441                 force=True,
    442             )
--> 443             if args.language_level is not None:
    444                 assert args.language_level in (2, 3)
    445                 opts['language_level'] = args.language_level

~/opt/anaconda3/lib/python3.7/distutils/command/build_ext.py in run(self)
    338
    339         # Now actually compile and link everything.
--> 340         self.build_extensions()
    341
    342     def check_extensions_list(self, extensions):

~/opt/anaconda3/lib/python3.7/distutils/command/build_ext.py in build_extensions(self)
    447             self._build_extensions_parallel()
    448         else:
--> 449             self._build_extensions_serial()
    450
    451     def _build_extensions_parallel(self):

~/opt/anaconda3/lib/python3.7/distutils/command/build_ext.py in _build_extensions_serial(self)
    472         for ext in self.extensions:
    473             with self._filter_build_errors(ext):
--> 474                 self.build_extension(ext)
    475
    476     @contextlib.contextmanager

~/opt/anaconda3/lib/python3.7/distutils/command/build_ext.py in build_extension(self, ext)
    532                                          debug=self.debug,
    533                                          extra_postargs=extra_args,
--> 534                                          depends=ext.depends)
    535
    536         # XXX outdated variable, kept here in case third-part code

~/opt/anaconda3/lib/python3.7/distutils/ccompiler.py in compile(self, sources, output_dir, macros, include_dirs, debug, extra_preargs, extra_postargs, depends)
    572             except KeyError:
    573                 continue
--> 574             self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
    575
    576         # Return *all* object filenames, not just the ones we just built.

~/opt/anaconda3/lib/python3.7/distutils/unixccompiler.py in _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
    118                        extra_postargs)
    119         except DistutilsExecError as msg:
--> 120             raise CompileError(msg)
    121
    122     def create_static_lib(self, objects, output_libname,

CompileError: command 'gcc' failed with exit status 1

Also, my mac is updated to 10.15.3 Catalina while my friend's mac that stayed as 10.14.6 Mojave ran the same code without any problems. I have heard compatibility issues with Anaconda when Catalina first came out, but I don't know if this has anything to do with my error.
Comment: gcc will have written an error message to stderr before it exited. Those errors are where you need to start.
Comment: The meaningful error message was printed to stderr as Charles Duffy already said, see also https://stackoverflow.com/q/57726729/5769463
Answer: Just answering my own question so I can close this.
Thank you for two comments on my question! I was able to locate the meaningful answer in my terminal according to the answer provided here: What does CompileError/LinkerError: "command 'gcc' failed with exit status 1" mean, when running %%cython-magic cell in IPython
It turns out the error was
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

which simply needed to be resolved by running this code in the terminal:
xcode-select --install

For a more detailed solution to the missing xcrun problem, check here https://apple.stackexchange.com/questions/254380/why-am-i-getting-an-invalid-active-developer-path-when-attempting-to-use-git-a


The value of the textarea isn't going into the database

Question: if($_POST['button']){
    $name= $_POST['name'];
    $url= $_POST['url'];
    $description= $_POST['description'];

    mysql_query("INSERT INTO videos VALUES (
        '','$name','$url','$description'
        )");
}

echo '
Add Video

<form action="addvideo.php" method="post">
Name: <input type="text" name="name" />

Url: <input type="text" name="url" />

Description:
<textarea    name="description" style="height:500px; width:750px;"></textarea>
<input type="submit" value="submit" name="button" style="position:relative; top:-250px;" />
</form>';

This is my code for a website i am building where you can input data for a youtube video. It is then supposed to insert that in a table in my database. The problem is that when the description is in one line, it makes it break when it gets to the end of the textarea. This makes it not put anything into the table for some reason. So that is the question.
Comment: Try using mysql_real_escape_string on your assignments. ie. `$description= mysql_real_escape_string($_POST['description']);` or better yet use mysqli or pdo as mysql is now officially deprecated. It might also be useful to check the requrn of mysql_query and check it for errors.
Comment: What is the error you getting? What is the input of text area; just copy here!
Comment: This is another good example why you should use [prepared statement and variable binding](http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php).
Comment: @Orangepill Thanks that seemed to work. I also might try to look into using mysqli.
Answer: You can use MySQL_real_escape_string like
<?php
if(isset($_POST['submit'])){
    $con = mysql_connect ('localhost','username','password') or die(mysql_error());
        mysql_select_db('database') or die(mysql_error());
    //$desc = mysql_real_escape_string($_POST['txtDesc']);//nl2br($_POST['txtDesc']);
    $desc = mysql_real_escape_string($_POST['txtDesc']);
    $sql = "INSERT INTO desc_tbl (desc) VALUES('$desc')";
    $result = mysql_query($sql) or die(mysql_error());
}
?>
<form method="POST" action="textarea.php">
<textarea name="txtDesc" row = "50" cols = "50" id="txtDesc" wrap="hard"></textarea>
<input type="submit" value="submit" name="submit">
</form>

Answer: I would suggest to use mysqli over mysql. Also use prepared statements, they will save you from much trouble.


Use just one table to store more than one type of relation, is efficient?

Question: Consider I have a table name Post which stores likes and comments etc. So I want to share a table for comment and likes by storing actual relation in a separate column, example tables :-
Posts

post_id
post_description

then a relation table :

post_has_

post_id
user_id
relation(string : "like", "comment", "shares") etc

So by single table we can store more then one relation, all can be manage by application level, not need to create separate table, I want to know is that good idea, or anyone has does that before? Any tradeoffs etc?
Comment: Time to read a textbook on  information modeling, the relational model & database design. You are just asking us to write yet another one. Read one & ask a specific question where you are stuck following it. Your "relation" field is not explained but it seems likely you are talking about partly using a design idiom called EAV, which is typically an anti-pattern.
Comment: I'm not clear on how these two tables are meant to represent anything useful. I.e. if something's a "comment", how is the text of that comment stored or how is it related back to what it's a comment on? Unless you're working with a very odd database product, trying to minimize the number of tables is a very odd "goal".
Answer: Sounds like you're thinking about a parent-child tables relationship as one post could have multiple likes and comments.
Or if you ever decide to get even fancier (crazier lol) and want to be able to have comments about comments or even comments about comments about comments (i.e. getting deeper into the levels) then you may want to somehow use one table that can handle all the possibilities such as:
 posts:
      post_id
      parent_post_id_if_applies
      post_description
      user_id
      relation(string : "original", "like", "comment", "shares") etc
And maybe a level field to say what level in you are such as 1 for an original post, 2 for a view or a comment about the original post, 3 for a view or a comment about #2 etc.
Answer: It's hard to be specific, but the design you show is typically used for a "many-to-many" relationship between posts and users.
What that might mean in application terms is "One post can belong to several different users; each user might have a different "relation", and "One user can create several posts".
This may or may not be true - it's hard to tell from your question.
If your intent is "One user can create many posts. Each post can have many relations. A post belongs to exactly one user.", you would add "user_id" to your posts table.


Where is stored the Certificate when the first Remmina connection was accomplished?

Question: For Ubuntu Desktop 22.04 and when Remmina (1.4.25+dfsg) as client does the first attempt of connection to a remote host (in this case other Ubuntu Desktop 22.04 too), once written the valid username and password, only for the first time appears a dialog window with the option to accept a Certificate, only when is accepted the connection can be established. For the coming connections that dialog window does not appear anymore and the username and password are not requested too, therefore the newer connections are accomplished directly.
Question
Where is stored that certificate?
Reason
For academic purposes, I want to delete that certificate to simulate again the first connection to see again the dialog window where the Certificate appears.
Note
I deleted the Certificate though the GUI according with

Where does Remmina store the encrypted password?

But when the next connection is tried, it is accomplished directly, therefore does not appear the dialog window as expected.
Furthermore according with How to extract saved password from Remmina?
should exists the ~/.remmina directory, but it does not exist.
How accomplish this goal? - See again the Dialog Window to accept the Certificate as the first time.
Answer: File is:
~/.config/freerdp/known_hosts2


ASP.NET Core 3.1 get method body breaks the request

Question: Issue happened on ASP.NET Core 3.1 Web API controller. I have a method in controller with [HttpGet] attribute and [FromBody] for only parameter:
[HttpGet]
public async Task<ActionResult> GetMessages([FromBody] MessageRM messagesRequest)

This method expects to receive a request model:
public class MessageRM
{
    public int RegionID { get; set; }
    public int? LastMessageID { get; set; }
    public int? StartMessageID { get; set; }
    public int? PageSize { get; set; }
}

When I do make a get request to this method without body the returning result is:
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"|f6d2c92d-47865e9e3ad9a87d."}

That was quite unexpected. Had a feeling that I'm missing something important, this feeling increased when I passed the body. At first with '{}', then fully simulating my request object. Either of these requests contained 'application/json' content-type header. Both times same response:
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|f6d2c92e-47865e9e3ad9a87d.","errors":{"$":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}

Any suggestions?
Comment: Also please read [this](https://stackoverflow.com/a/983458/2501279).
Comment: As far as I know get methods does not support body. You should use POST or PUT for example.
Answer: Change [HttpGet] for [HttpPost] and issue a POST request instead of a GET.
Comment: @hitpoint As the linked question's answers note, the RFC does not specifically forbid the use of a body in a GET request, but does not give any semantic importance to it either, which means most implementers of server-side frameworks ignore the body of GET requests.
Comment: Yeah, already tested that, works fine. But i'm still curious for the cause.
Can you add more details. Is this a bypass for an error or there is a spec for this somewhere. Some link to msdn where is explicitly written: "GET IS NOT ALLOWED TO HAVE A BODY"?


When is the right time to hit the ball protection button?

Question: Madden 12 has a button to be used when rushing that makes the player tuck the ball to prevent fumbles.  The game does a good job of mentioning the button's existence, but just says to press it before being tackled.
I'm unclear on whether that means I press the button and hold it, or pressing it once makes them tuck it for the rest of the run.  Hitting it right when I get tackled seems awkward, since at the same time I'm also trying to press the stiff arm button to break the tackle.
Answer: You have to hold the button, and you can't stiff arm someone and protect the ball at the same time. You have to pick, attempt to break the tackle, or play it safe, take the tackle and not risk a turnover.
I generally don't use it because fumbles are a lot rarer than successful stiff arms.
Comment: This seems to be what I've noticed too.  Thanks for the info!


{exp:search:keywords} filtering out insignificant words

Question: With my current project I need to display the exact search phrase entered on the results/no-results pages.
However the {exp:search:keywords} variable seems to have insignificant keywords removed.
"Who am I?" becomes "who am"
I understand why this is the case but for the purposes of this particular website I need the exact phrase.
Does anyone know how I can achieve this ? Please let there be a workaround...
I am using the Simple Search module in 2.7.0
Thanks.
Answer: /system/expressionengine/modules/search/mod.search.php:236 (v2.7.0)
<code>//$original_keywords = $this->keywords;
$original_keywords = $_POST['keywords'];
</code>


PEP8 style for decorators exceeding recommended line length

Question: I have been tinkering with Invoke, but I came across something that is quite an odd case that there seems to be no real PEP guideline for it.
Invoke lets you define your own CLI arguments for whatever tasks you define, and you can optionally provide "help notes" to a task decorator. Specific example can be found here.
If there are more parameters, I could probably do it like this, but it feels kind of weird if there are many tasks. What coding style would you guys do?
help_for_hi = {
    'name1': 'Name of Person 1',
    'name2': 'Name of Person 2',
    'name3': 'Name of Person 3',
}

@task(help=help_for_hi)
def hi(ctx, name1, name2, name3):
    """Say hi to three people."""
    print("Hi %s, %s, and %s!" % (name1, name2, name3))

UPDATED
As requested, this is what 'too long' would probably look like.
@task(help={'name1': 'Name of Person 1', 'name2': 'Name of Person 2', 'name3': 'Name of Person 3'})
def hi(ctx, name1, name2, name3):
    """Say hi to three people."""
    print("Hi %s, %s, and %s!" % (name1, name2, name3))

Comment: Sorry, can you spell out how it would look when it is 'too long'? And the decorator expression is just like any other call, wrap it onto multiple lines within the `(...)`.
Comment: Decorators with arguments are just function calls with an `@` prefix — so just follow the PEP8 guidelines for function calls.
Answer: You'd just break up the decorator expression into many lines the same way you'd break up any other function call.  One example could be:
@task(help={
    'name1': 'Name of Person 1',
    'name2': 'Name of Person 2',
    'name3': 'Name of Person 3'})
def hi(ctx, name1, name2, name3):
    """Say hi to three people."""
    print("Hi %s, %s, and %s!" % (name1, name2, name3))

... A codebase that I work on daily has quite a few @mock.patch.object written out this way.
Obviously, breaking out the dictionary into a separate variable can work in this case as you've done in the question (I might actually prefer it assuming that the variable is well named :-).
# Nothing wrong with this as far as I can tell ...
help_for_hi = {
    'name1': 'Name of Person 1',
    'name2': 'Name of Person 2',
    'name3': 'Name of Person 3',
}

@task(help=help_for_hi)
def hi(ctx, name1, name2, name3):
    """Say hi to three people."""
    print("Hi %s, %s, and %s!" % (name1, name2, name3))


Jump distribution of a continuous time Markov chain

Question: Given the following jump chain:
\begin{pmatrix}
0 & 1 & 0 & 0 & 0 & 0\\
1 & 0 & 0 & 0 & 0 & 0\\
\frac{1}{4} & 0 & 0 & \frac{1}{4} & \frac{1}{2} & 0\\
0 & 0 & 0 & 0 & 0 & 1\\
0 & 0 & \frac{1}{2} & 0 & 0 & \frac{1}{2}\\
0 & 0 & 0 & 1 & 0 & 0\\
\end{pmatrix}
And that $q_1=q_3=q_5=12$ and $q_2=q_4=q_6=6$.
Given as well that $X_0=3$ what are:

$\lim_{t\to\infty} P(X_t=2|X_0=3)$

the distribution of the number of jumps to state 3

I have found the Q matrix and computed part 1 as follows but I am not sure if it is correct and I do not understand how to do part 2.
Q-matrix:
\begin{pmatrix}
-12 & 12 & 0 & 0 & 0 & 0\\
6 & -6 & 0 & 0 & 0 & 0\\
3 & 0 & -12 & 3 & 6 & 0\\
0 & 0 & 0 & -6 & 0 & 6\\
0 & 0 & 6 & 0 & -12 & 6\\
0 & 0 & 0 & 6 & 0 & -6\\
\end{pmatrix}
$\lim_{t\to\infty} P(X_t=2|X_0=3)= h_3^{\{1,2\}}\lim_{t\to\infty} P(X_t=2|X_0\in \{1,2\}) = 1 h_3^{\{1,2\}} = \frac{1}{3}$ \
where $h_3^{\{1,2\}}$ is the probability to $\{1,2\}$ starting from 3.
Answer: I highly recommend that you draw a state transition diagram to solve this problem. If you do this you'll clearly see that $\{1,2\}$ and $\{4,6\}$ are absorbing and $P(X_{2n-1}=2|X_0=3)=0$ for any $n\in \mathbb{N}$ i.e. the Markov chain can only reach state $2$ on an even$-$numbered step originating at state 3. In fact, we have for large $n$ that $$P(X_{2n}=2|X_0=3)\approx P\Big(\text{Absorbed in \{1,2\}}\Big|X_0=3\Big)$$ To calculate the probability on the right hand side, set $$a_i=P\Big(\text{Absorbed in \{1,2\}}\Big|X_0=i\Big)$$ for $i\in\{1,\ldots,6\}$. Clearly $a_1=a_2=1$ while $a_4=a_6=0$. Using the total law of probability with recursion we have $$a_3=p_{31}a_1+p_{34}a_4+p_{35}a_5=\frac{1}{4}+\frac{1}{2}a_5=\frac{1}{2} \\ a_5=p_{56}a_6+p_{53}a_3=\frac{1}{2}a_3$$ Solving this system yields $a_3=\frac{1}{3}$ and $a_5=\frac{1}{6}$. To summarize, $$\lim_{n\rightarrow \infty}P(X_{2n-1}=2|X_0=3)=0 \\ \lim_{n\rightarrow \infty}P(X_{2n}=2|X_0=3)=\frac{1}{3}$$
For the second part, let $X$ represent the number of jumps to state #$3$. Clearly $X$ is supported on the set $\{0,1,2,\ldots\}$. Notice $$p_X(0)=p_{31}+p_{34}+p_{35}p_{56}=\frac{3}{4}$$ and for $k \geq 1$ we have $$p_{X}(k)=\frac{3}{4}\times\Big(\frac{1}{2}\Big)^{2k}$$


LOST .p12 key for Air Published App in Google Play- Can I create same finger print?

Question: I reformatted my drive. Saved all but somehow the p12 is gone.
I tried uploading my .apk to Google Play, an existing app, signed with a new .p12
key and this is the error I get in the image.

Is there a way to make a new .p12 using the numbers they showed me?
Or can I abstract my old .p12 from an app I already uploaded and have copies
of?
Thank you for any advice in this matter.
Answer: You can't create a p12 like this, but you can try "migrate" the app to a new certificate, like described here
I never actually tried this, though, so good luck!


Basic Geometry Sum

Question: Suppose P,Q,R and S are the midpoints of the sides AB,BC,CD and DA, respectively of a rectangle ABCD. If the area of the rectangle is delta, then area of the figure bounded by straight lines AQ,BR,CS and DP is?
Please help.Thanks.
Answer: Let $AQ\cap DP=\{L\}$, $AQ\cap BR=\{M\}$, $CS\cap DP=\{K\}$ and $CS\cap BR=\{N\}$.
Since $AQCS$ and $DPBR$ are parallelograms, we see that $KLMN$ is parallelogram.
Now, let $F$ is a middle point of $RC$.
Thus, $QF||BR$, which says that $G$ is a middle point of $NC$, where $\{G\}=QF\cap NC$.
In another hand, since $R$ is a middle point of $DC$ and $RB||DP$, we obtain that $N$ is a middle point of $KC$.
By the same way we can get that $AL=LM=KN=NC$ and $DK=KL=BM=MN$
and since $AQ=CS$ and $DP=BR$, we obtain $SK=MR$ and $PL=RN$.
Now, since $NG=GC$ and $MNGQ$ is parallelogram we obtain that $S_{\Delta GQC}=\frac{1}{3}S_{MNCQ}.$
But $GC=GN=MN=SK$, which says that $GC=\frac{1}{5}CS$ and $S_{\Delta GQC}=\frac{1}{10}S_{AQCS}$.
Hence, $S_{MQCN}=\frac{3}{10}S_{AQCS}$.
By the same way we can get that $S_{ALKS}=\frac{3}{10}S_{AQCS}$, which says that
$$S_{KLMN}=S_{AQCS}-2\cdot\frac{3}{10}S_{AQCS}=\frac{2}{5}S_{AQCS}=\frac{\Delta}{5}$$
and we are done!

Basic Geometry Sum


How to fit vents in a roof

Question: The home we have just brought has no vents in its tiled roof; therefore it is getting a lot of condensation in the loft.
So how do I fit vents?
Do the vent you fix from the inside (rather than putting in venting tiles) work well enough?
Comment: Do you have to put the vents in the roof itself?  It might be easier to put a vent in the siding at the peak of a wall depending on how the walls/roofline/attic space is laid out.
Comment: @auujay, our roof slopes on all 4 sides, so we don't have any end walls to put vents in.
Comment: Ah, then my answer doesn't help you much. I'll leave it up for anyone else with a similar problem but different style of roof.
Answer: A gable louver might be a good option if you don't want to mess with the tiled roof.
Comment: good answer, only way to do it without ridge vents. Also consider soffit vents with "proper vent tunnels" if possible in conjunction with a gable end vent.
Comment: nice looking vent..
Answer: I can think of only think of one solution other than going through the tile. you could run a large 6"-8" venting from the crown to the soffits with an in line fan to draw the air down. You would have to make sure that your fan will be able to exchange enough air. I am not exactly sure how to calculate this.
Other than this you would need to put the venting in from the top. Flashing will need to be installed to prevent leaking. I have never dealt with tile, sounds like a big job.

How to fit vents in a roof


No audio input and non-existing S/PDIF sinks/sources in list

Question: I've installed a simple utility for audio recording Sound Recorder, but it won't start recording, as there is only one source: "Master".
I use Behringer UMC202 USB audio interface; it has one stereo input and one stereo output (both analog). Audio driver is snd_usb_audio.
However, when I open "Sound Settings", I see two outputs: First is S/PDIF, and second is analog. Same thing with inputs, one digital and second is analog. The difference is that it does not even meter my input.
If I open alsamixer tool, and select my audio card with F6 key, I see only two outputs. Real output volume may be changed by both of them.
I think that something is messed up with my configuration, causing input not to work and fake "S/PDIF" digital interfaces to be detected by Ubuntu.
I am sure that my analog input is muted, but usable. question is, how do I fix sinks/sources detection to remove digital ports and unmute my input?
What should I change in my system?
$ cat /proc/asound/{version,cards,devices,hwdep,pcm,seq/clients}
Advanced Linux Sound Architecture Driver Version k3.13.0-24-generic.
 0 [Intel          ]: HDA-Intel - HDA Intel
                      HDA Intel at 0xf9ff8000 irq 44
 1 [U96k           ]: USB-Audio - UMC202 96k
                      BEHRINGER UMC202 96k at usb-0000:00:1d.7-1, high speed
  1:        : sequencer
  2: [ 0- 2]: digital audio capture
  3: [ 0- 1]: digital audio playback
  4: [ 0- 0]: digital audio playback
  5: [ 0- 0]: digital audio capture
  6: [ 0- 0]: hardware dependent
  7: [ 0]   : control
  8: [ 1- 0]: digital audio playback
  9: [ 1- 0]: digital audio capture
 10: [ 1]   : control
 33:        : timer
00-00: HDA Codec 0
00-00: ALC1200 Analog : ALC1200 Analog : playback 1 : capture 1
00-01: ALC1200 Digital : ALC1200 Digital : playback 1
00-02: ALC1200 Alt Analog : ALC1200 Alt Analog : capture 1
01-00: USB Audio : USB Audio : playback 1 : capture 1
Client info
  cur  clients : 2
  peak clients : 2
  max  clients : 192

Client   0 : "System" [Kernel]
  Port   0 : "Timer" (Rwe-)
  Port   1 : "Announce" (R-e-)
Client  14 : "Midi Through" [Kernel]
  Port   0 : "Midi Through Port-0" (RWe-)

Answer: It turned out that the reason is the "recording" feature is not "enabled":
sudo apt-get install gnome-alsamixer
gnome-alsamixer

In a dialog window find your sources and check Rec. for each. Input will then appear.


Remove/re-install LAMP with current versions on Ubuntu 18.04

Question: I'm having trouble with my LAMP stack since the Ubuntu 18.04 upgrade, so I'd like to just remove everything and start with a clean slate. I'm referring to the post entitled "How do I remove the LAMP stack so I can start over?" but, it appears to list older versions, PHP5 for example. I can't find documentation for anything more current and I have PHP 7.2.7 installed. Can I just substitute PHP7 in every instance of PHP5 and accomplish the same results, or is there more current and specific documentation that I haven't found. Thanks, in advance, for your assistance.
Comment: using an old guide and replacing php7 where neccessary should work for removing. once you have removed your lamp stack, install it following this guide: https://linuxconfig.org/how-to-install-lamp-ubuntu-18-04-bionic-beaver-linux-apache-mysql-php
Comment: posted it to an answer.... you might just use php instead of php7
Answer: You can remove all the main stuff with these commands:
sudo apt-get purge mysql-server apache2 php
sudo apt autoremove && sudo apt autoclean

Then reinstall it the modern way using taskel:
sudo apt install tasksel
sudo tasksel install lamp-server

Comment: OK. I was able to get back to this and follow your instructions. After the installation I rebooted the PC, and tried an Apache2 test with localhost/index.html. That looked fine. The PHP version showed 7.2.something. The one question I had was that when I logged into MySQL it accepted my OLD user/pass. Is that normal??  I was prepared complete install to be purged and to start over. Thanks for the steps.
Comment: What does it install, Mysql or MariaDb ? https://help.ubuntu.com/community/Tasksel#Task_descriptions says nothing much


Download MP3 file on click

Question: Being a new coder I keep doing a lot of trial and errors and stick with the finds that work, how ever the method I have at the moment does not work with all browsers.
Our PHP code.
$songs = file_get_contents('https://example.com/tracks/'.$id.'/');
$filename = './tmp/'.$SongTitle.'.mp3'; // used for the file_put_contents.
$filenames = '/tmp/'.$SongTitle.'.mp3'; // used for the echo
file_put_contents($filename, $songs);

HTML Download Button.

<button type="button" class="btn btn-success"><a href="<?php echo $filenames; ?>" download='<?php echo $filenames; ?>' href="javascript:">Download</button>

You can see that I am using the Html5 and the Javascript method above meaning it only has support on FireFox and Google Chrome.
How can I allow users on all browsers to download the file on click of our button?
Comment: What browsers are you having issues with and what are those issues? See http://blog.deepbluesky.com/blog/-/browser-support-for-css3-and-html5_72/
Comment: You can do this by sending headers :)
Comment: @icecub Could you provide an example?
Comment: Sure give me a few mins
Comment: @DelightedD0D The download button simply does not appear on browsers like Safari and Waterfox even have not tested any other browsers but with this method those are the two that I know for sure it's not working on.
Comment: @DelightedD0D Not a duplicate, already read over that post.
Answer: The reason is FireFox and Google Chrome plays audio or video automatically for mime type octet stream, however IE does not have support for this.
You need to add .mp3 extension and mime type in server configuration to download your file in IE.
Answer: Alright, as promissed:
<?php

$file = "example.mp3";

header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.$file);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: audio/mp3");
readfile($file);

?>

Now just create a hyperlink or button that points to this php file.
EDIT: I should add that this is just an example as requested ofcourse! This method is very inefficient in its current form. If you plan on using multiple audio files, you should make the filename dynamicly through POST / GET.
Comment: Using this method it downloads an empty file, just as it did the first time I messed around with headers... I must be doing something wrong.
Comment: @Open Probebly. I've tested it here first and it works perfectly fine. Unfortunetely I can't help you with the issue because I don't have your code. You can either edit your question with it or click on my profile. You'll find my email address over there for more in depth help if required :)
Comment: I shot you an email! thanks.
Comment: @Open Got it. Send reply

Download MP3 file on click


Filter response from api on user search getting error :`Unhandled Rejection (TypeError): Cannot read property 'results' of undefined`

Question: Trying to update my state with a filtered api response. I make the call and then update the results state (see below).
api call
  async searchMovies(keyword, year) {
    const response = await getMoviesFiltered(keyword, year);
    console.log(response); // filtered response
    this.setState({ results: response.results});
  }

request
export const getMoviesFiltered = async (keyword, year) => {
  try {
    const response = await axios.get(
      `https://api.themoviedb.org/3/search/movie?api_key=<apikey>&language=en-US&query=${keyword}&page=1&include_adult=false&year=${year}`
    );
    console.log(response.data.results);
    return response.data;

  } catch (error) {
    console.error(error);
  }
};

response from api:
{page: 1, results: Array(20), total_pages: 95, total_results: 1889}
page: 1
results: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
total_pages: 95
total_results: 1889

I want to update my state with the response (results key, which is an array) and map over it but it tells me that Unhandled Rejection (TypeError): Cannot read property 'results' of undefined
which is strange as i can see results in the response
Also, when I attempted to update the results in the state with response e.g
this.setState({ results: response});

I get:
TypeError: movies.map is not a function
i.e it can't map over the response i am passing down....
I have looked at other questions on stack and they say this is because the response is not an array, but mine is :S
Here is where i am mapping over the data, which is passed down from the parent.
 <MovieList movies={results || []} genres={genreOptions || []} />

component:
    return (
      <MoviesWrapper>
        {movies && movies.map((movie, index) => {
          const {
            title,
            vote_average,
            overview,
            release_date,
            poster_path,
            genre_ids,
          } = movie;
          return (
            <MovieItem
              key={index}
              title={title}
              rating={vote_average}
              overview={overview}
              release={release_date}
              poster={poster_path}
              movieGenres={matchGenres(genre_ids)}
            />
          );
        })}

can anyone see what is wrong?
Answer: Cant see your full component codes; but the problem is probably that you initialized your state null.
When you have a state defined in your code, the state initializes with its initial value.
const [Movies, setMovies] = useState(null)

Now i have defined a state called Movies and its null at the beginning.
I do my API call at useEffect block(or ComponentDidMount); and after my API response, i update the state to response with setState, or in example above; setMovies().
useEffect(() => {
   const response = await axios.get(`ENDPOINT_URL`);
   setMovies(response)
},[]);

Now my state is the response array from my API call. Only now I can use map function, not before; because it was null and would throw an error.
Lets dive into how React handles this flow in return block. React does not wait for the API call to end to initialize the state and print what is in return block. This is important; because if i try to do something with the state at the first render; before react updates the state with the response array from api; the state will be "null".
So the order is like this.
1.Initialize state with initial value (null)
2.Render return block
3.Update state (Example: setMovies([1,2,3]) )
4.Re-render return block.
Lets say i have {console.log(Movies)} in my return block. I will see 2 logs in the console; the first one will say "null"(step 2), and the second one will say "[1,2,3]" (step 4)
Now, if i have Movies.map function inside return block; it will throw an error which will say "TypeError: Movies.map is not a function"; because Movies is null at the first.
As for your other question: "Unhandled Rejection (TypeError): Cannot read property 'results' of undefined"
This error is thrown when parent object is empty; in this case; parent object of results. Cant be sure which "results" is throwing error here because you didnt provide row number of exact error. For example; data.results is throwing this; it means "data" is empty and does not have results as child object. This is most likely result of 2 things; when we judge response object schema wrong, (Ex: response.data.movies.results instead of response.data.results) or we tried to reach data.results before we fill it "Ex: data = apiresponse.content".
If you can provide a CodeSandbox; it would be much easier to answer.
Edit after codesandbox
Error corrected: https://codesandbox.io/s/movies-app-angela-forked-ehr9u
Errors:

MovieList where you .map movies; the state initializes empty because of the reasons i explained above; so it throws error; You can just add {movies && movies.length > 0 ...} 1 step above map function to check if movies exists and isnt empty.

In your searchMovies function your fetcher call catches
errors but only console.logs; this creates problem in searchMovies
function. Because even if the response is null or errorcode, searchMovies function still continues to work, and updates the state wrongly.

Your search doesnt show responses in view; because
after the call in searchMovies; you need to provide a direct access to results object array so view knows types. MoviesList component knows and renders array of movie objects; but after searching you set the state to the object also containing different properties; so MoviesList doesnt know how to render results. Shortly; response.data.results instead of response.data.

Your searchBar component, it doesnt actually search exact key press, but 1 before. Like when you try searching "dark"; it searches for "dar". When you search for "d" it searches for empty string. You have to type "dark" plus 1 space to actually search for "dark". So, api returns 422 Unprocessable entry error at first character you type because it tries to search for empty string. Its because you update the state, then call search api. But updating state is asynchronous, and state updating doesnt finish before you send state to api fetcher function. So simple solution to this would be sending search fetcher function event.target.value, instead of the state you are updating.

A small reminder: Change your API key now; as its exposed to web.
Comment: I've looked to codesandbox. Firstly in MovieList where you .map movies; the state initializes empty so it throws error; ive just added  `{movies && movies.length > 0` to check if movies is array. Secondly, in your searchMovies function your fetcher call catches errors but only console.logs; this creates problem in searchMovies function. Lastly, your search doesnt show responses in view; because after the call in searchMovies; you need to provide a direct access to results object array `response.data.results` so view knows types. Working: https://codesandbox.io/s/movies-app-angela-forked-ehr9u
Comment: No problem. I am happy to help. If i have time; I would be glad to help in future as well, free mentoring or answering questions; doesnt matter.
Comment: Hello @Emre, thank you for your detailed explanation. OK so from what you have said my issue could come from the fact that I am making my request inside a `useEffect` / `ComponentDidMount` block. I will create a CodeSandbox so you can see what is happening, thank you again!
Comment: hi @Emre, I've created a CodeSandbox: https://codesandbox.io/s/movies-app-angela-liu3j?file=/src/App.js.  My issues is on line 67 where i make an api request to get a list of movie results based on what the user has typed in (line 88 triggers this api request). I then want to pass the response to line 93 `MovieList` but I am unable to.. as I get the error about `"TypeError: Movies.map is not a function"`
Comment: And also in your searchBar component, it doesnt actually search exact key press, but 1 before. Like when you try searching "dark"; it searches for "dar". When you search for "d" it searches for empty string. You have to type "dark" plus 1 space to actually search for "dark". So, api returns 422 Unprocessable entry error at first character because it tries to search for empty string. Its because you update the state, then call search api. But updating state is asynchronous, and state updating doesnt finish before you send state to api fetcher function.I forgot to fix this in codesandbox reply.
Comment: Hello Emre, thank you so much for all of your clear responses. I now understand why I was unable to map over `movies` it was because I was mapping over nothing, i see you did the `&&` check to make sure that movies was in fact defined first before i mapped over it. ...... I also now understand what I did wrong in the `searchMovies` function. I was not accessing the `results` array.
Comment: The part that I need to understand still is the `SearchBar` you explain that when the user first searches that it tries to search for an empty string. Is this because on lines 13 - 22 in the `SearchBar` component I am updating the state with what the user types in (lines 14-17), this is then NOT updating the state straight away, so I am in fact sending up an empty string to the parent component function `searchMovies`(lines 18-21)?
Comment: I have now done what you suggested on lines 23 to 29 of the `searchBar` and passed `event.target.value` to the `searchMovies` function, this makes the search work correctly for the movie title. I just need to figure out now how to make the search work for both movie title and year together. THANK YOU SO MUCH FOR YOUR HELP AND INFO ON HOW THE REACT FLOW WORKS. I need to remember that when i update state in React it doesn't happen straight away so i always need to check if the state is what i want it to be before I continue to display the data i need to the view... Do you offer mentoring? :D
Comment: https://codesandbox.io/s/movies-app-angela-forked-ml153?file=/src/SearchBar.js.  i'll change api key too.
Answer: Solved the issue.
It was to do with the searchMovies api call, when i returned the api response, I have to do a check to see if there is actually a response first of all. If there is a response then I want to access the results array in that response.
Essentially do this when setting the state:
this.setState({ results: response && response.results });
instead of :
this.setState({ results: response.results });


Counting total number of monic irreducible polynomials of all degrees $k$ that divide $m$.

Question: Why is the following relation counting monic irreducible polynomials of all degrees $d$ that divide $m$ true?
\begin{equation}
\sum_{d\ |\ m}\left(\frac{1}{d} \sum_{c\ |\ d} \mu(d/c)\ p^{c}\right) = \frac{1}{m} \sum_{d\ |\ m} \phi\!\left(\frac{m}{d}\right)\ p^{d},
\end{equation}
where $\mu(n)$ is the Möbius function and $\phi(n)$ is Euler's totient function.

Background: one can express the degree of the polynomial $x^{p^m}-x$ over $\mathbb{F}_{p}$ ($p$ = prime) as the sum of the degrees of the monic irreducible factors of $x^{p^m}-x$ as
$$
\begin{equation}
 p^m = \sum_{d\ |\ m} d\ I_d,
\end{equation}
$$
where the sum runs over all divisors $d$ of $m$, and $I_d$ is the number of minimal polynomials of degree $d$ which are factors of $x^{p^m}-x$.
By Möbius inversion on gets the number of monic irreducible polynomials of degree $m$ as,
\begin{equation}
I_m =\frac{1}{m} \sum_{d\ |\ m} \mu(d)\ p^{m/d}= \frac{1}{m} \sum_{d\ |\ m} \mu\!\left(\frac{m}{d}\right)\ p^{d}.
\end{equation}
Now, if I sums up the monic irreducible polynomials of all degrees $d$ that divide $m$ one has,
\begin{equation}
\sum_{d\ |\ m} I_d =\sum_{d\ |\ m}\left(\frac{1}{d} \sum_{c\ |\ d} \mu(d/c)\ p^{c}\right) = \frac{1}{m} \sum_{d\ |\ m} \phi\!\left(\frac{m}{d}\right)\ p^{d},
\end{equation}
where $\phi(n)$ is Euler's totient function counting the number of integers less than $n$ that are relatively prime to $n$ given by,
\begin{equation}
\phi(n) = |{\{0 \leq i < n\ | \gcd(i, n) = 1\}}|.
\end{equation}
I verified the above relation in Matlab. I initially thought that $\sum_{d\ |\ n} \phi(d) = n$ would be of help, but could not come up with a decent proof. Any suggestions are greatly appreciated. Thanks.
Answer: Let's start from :
$$\sum_{d\ |\ m} I_d =\sum_{d\ |\ m}\left(\frac{1}{d} \sum_{c\ |\ d} \mu(d/c)\ p^{c}\right)=\sum_{d\ |\ m} \sum_{c\ |\ d} \left(\frac{1}{d}\mu(d/c)\ p^{c}\right) $$
Then invert the double sum (change of variable $(d,c)\mapsto(c,\frac{d}{c})=(c,e)$), you get
$$\sum_{d\ |\ m} \sum_{c\ |\ d} \left(\frac{1}{d}\mu(d/c)\ p^{c}\right)=\sum_{c\ |\ m} \sum_{e\ |\ \frac{m}{c}} \left(\frac{1}{ce}\mu(e)\ p^{c}\right)  $$
$$\sum_{d\ |\ m} I_d =\sum_{c\ |\ m}\frac{p^c}{c} \sum_{e\ |\ \frac{m}{c}} \left(\frac{\mu(e)}{e}\right) $$
Now this is a well known result that :
$$\phi(n)=\sum_{d\ |\ n}\mu(d)\frac{n}{d} $$
It is just the Moebius formula applied to the identity (you gave us) :
$$\sum_{d\ |\ n}\phi(d)=n$$
So we see in particular that :
$$\sum_{e\ |\ \frac{m}{c}} \left(\frac{\mu(e)}{e}\right)=\frac{c}{m}\sum_{e\ |\ \frac{m}{c}} \left(\mu(e)\frac{m}{ce}\right)=\frac{c}{m}\phi(\frac{m}{c})$$
Finally :
$$\sum_{d\ |\ m} I_d =\sum_{c\ |\ m}\frac{p^c}{c}\frac{c}{m}\phi(\frac{m}{c})=\frac{1}{m}\sum_{c\ |\ m}p^c\phi(\frac{m}{c})$$
Comment: That's great. Didn't think of switching the summation order around. Thanks a lot.


How to web-scraping continually with python selenium, using URL lists in csv file

Question: I need to know how to web-scrape by using csv file. The file I have contains list of 'company name', 'homepage URL', 'address', and so on.
The thing I have to do is:

Scraping 'contact address(e-mail)' by using list of company's homepage URL.
Save as csv file.

I've tried to use pandas, selenium library.
Scraping one e-mail address from one URL was successful.
Here's the problem:

Each of homepage has different HTML structure
Can not find the way scraping continually
(for-? while-?)
Comment: What is your specific problem, error you run into?
Comment: Even though it is obvious what you are referring to, it's spelled "scraping", with 1 p. "Scrapping", with 2 "P"s, has a completely different meaning. That could unfortunately be the reason you are not getting good results with your troubleshooting.
Comment: if every page has different structure then you have to create different code for every page. You can't create one universal code for all pages.
Comment: You can store your data in a `Pandas data-frame` and iterate over it, for web pages use `Beautiful Soup` to find elements with `Email tags, "email" in HTML .etc` using `regex` or `Beautiful Soup` function.
Answer: You could use the Python csv library to parse your file a row at a time and beautifulsoup to parse the HTML. From your question, your URL would be in the second column (i.e. row[1]). With this you can use the requests library to grab the HTML, and BeautifulSoup to parse out all strings.
Next you would need to use a regular expression to try and spot any email addresses inside the text. A simple search for python email regular expression should give you any number of possible solutions.
Next, for any emails that are found, write them as a row to an output CSV file:
from bs4 import BeautifulSoup
import requests
import csv
import re

with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    for row in csv_input:
        if row:
            company = row[0]
            url = row[1]
            print(f'Getting "{company}"')

            req = requests.get(url)
            soup = BeautifulSoup(req.content, 'html.parser')

            for text in soup.stripped_strings:
                emails = re.findall(r'\b([A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*)\b', text)

                if emails:
                    csv_output.writerow([company, *emails])


How to change highlighted warning/error text background color in eclipse?

Question: I'm using Retta color theme in eclipse. The problem is when I hover with the mouse over the warning or error symbols, it gives me a white background and I can't see a thing.
Highlighted text
Where I can change that? I've already tried going to General>Editors>Text Editors>Annotations, but changing the options there didn't solve the problem (like making Text as Underline and so on). The problem only occurs when I hover the mouse over the warning/error symbol.
Comment: Please post your code as actual text content and not as image.
Comment: Why? The code have multiple includes to make it work here, besides, any warning or error have the same behavior no matter the code.
Answer: First you should over the word with the highlighted background and then proceed to right click, then go to Preferences > Appearance color options
Then you should be able to adjust the colors to your liking.
Comment: I've changed everything to black in these options, but still gives me a light background (even disabled every highlight options I've found) =/