Java Factorial GUI

Question: The goal is to create a program which utilizes a GUI to calculate a factorial. I need to create a jPanel or jFrame to display the results of the program. Then I need to get the text from JTextField and parse it to an Integer so it can be passed to a constructor.
Thirdly, an object class needs to be created with an instance variable of type int called factorial. This object class needs a single argument constructor named Factorial that accepts an int and assigns the value to the instance variable. Then it should have a method that calculates the factorial using a for loop with a return type of int. Finally, it should display the value of the object after calling the method that computes the factorial. Here is my work so far.
import javax.swing.JFrame;

public class factorialCalc

{

     public static void main (String[] args)

     {

          JFrame frame=new JFrame ("Factorial Calculator");

          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

          Factorial panel=new Factorial();

          frame.getContentPane().add(panel);

          frame.pack();

          frame.setVisible(true);

     }

}

And my next file is the Object class:
 import java.awt.*;

 import java.awt.event.*;

 import javax.swing.*;

 public class Factorial extends JPanel

 {

          private int factorial;

          private JLabel inputLabel,resultLabel;

          private JTextField factorialText;

          private JButton factButton;

           //Constructor: sets up main GUI components

           public void FactorialPanel(int factorial)

           {

                this.factorial=factorial;

                inputLabel= new JLabel ("Please enter an integer:");

                factButton = new JButton("Compute");

                TempListener listener=new TempListener();

                factButton.addActionListener(listener);

                factorialText = new JTextField();

                factorialText.addActionListener (new TempListener());

                add(inputLabel);

                add(factorialText);

                add(resultLabel);

           }

           //represents a listener for the button

           private class TempListener implements ActionListener

           {

            //performs factorial operation when the 'Compute' button is  pressed

            public int computeFactorial(ActionEvent event)

            {

                 int text=Integer.parseInt(factorial);

                 int f =1;

                 for(int i=text;i>=1;i--)

                 {

                      f = f*i;

                 }

                  resultLabel.setText(Integer.toString(f));

            }

       }

 }

These are the following errors I get when I try to compile:
.\Factorial.java:31: error: Factorial.TempListener is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener
    private class TempListener implements ActionListener
            ^
  .\Factorial.java:37: error: incompatible types: int cannot be converted to String
                    int text=Integer.parseInt(factorial);
                                              ^
  Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
  2 errors

Why does it not let me parse the String factorial into and integer?
Also, how and where can I call the computeFactorial method to display the value of the object?
Thank you! Any help is appreciated!
Comment: `factorial` is already an `int`, so using `Integer.parseInt(String)` won't work, and even if it did it would be useless. Your `TempListener` needs to declare `public void actionPerformed(ActionEvent e)` since it implements `ActionListener`
Comment: `factorial` is declared as an `int`, not a `String`.
Answer: Instead of using factorial here, which is already an int (hence the error)...
int text=Integer.parseInt(factorial);

... I think you meant to get the JTextField value:
int text=Integer.parseInt(factorialText.getText());

Also, if TempListener implements ActionListener, then you must follow the ActionListener interface.  The method is called actionPerformed()...
 public int actionPerformed(ActionEvent event)

You can't just rename it to whatever you want, like you did here:
public int computeFactorial(ActionEvent event)

Finally, based on your comment, another issue is you misnamed your constructor.  If your class is defined as:
public class Factorial extends JPanel

Then your constructor might be:
public Factorial(int factorial)  // note: no void and same name as class

Comment: Thanks! That got rid of both my compilation errors. Now when the program runs the panel is empty. I think there is something wrong with the way my object is being implemented.
Answer: Listen to your compiler:

error: Factorial.TempListener is not abstract and does not override abstract method actionPerformed(ActionEvent) in
  ActionListener

It's easy for a beginner to think "Oh, that's a load of babble, I'll try stuff instead of trying to understand what it says" -- but you need to understand them because they tell you exactly what the compiler is complaining about.
Here's it's telling you that because Factorial.TempListenerimplements ActionListener, it expects it to have a method actionPerformed(ActionEvent).
If ActionListener was abstract, it would be allowed to not have this method -- but then you wouldn't be able to instantiate it, so just adding abstract won't help.
So you need to write actionPerformed(ActionListener).
What that method should do is beyond what SO is for -- read and understand a book or tutorial on Swing.
No doubt once you fix this there will be more compiler errors. Read them; they usually tell you where the problem is.

Java Factorial GUI


Changing two or three bars an octave lower on Guitar

Question: Is it allowed to change two or three bar notes an octave lower in a song (one tab or sheet music) for Guitar?
for this reason some Guitar have 12 frets like mine
and this is link (midnight express) has bars 13-14 15.
Answer: Allowed by whom? If someone asks you to play exactly that tablature, you should play it as it is. If you have any restrictions, it is not illegal to change an octave lower for some notes. So, change it.
It will sound different, and it might not sound exactly like you wanted it, but it is acceptable. Try and see if you can lower the whole song or some mote parts an octave lower .
It is common for guitarists to change the melodies up and down octaves; this might prevent them from getting bored by playing the same thing over and over again.
Comment: And is it proper to change lower from G to F or E?
Comment: There is a difference in changing octaves and changing notes. If you want to lower a G to F or E, you will have to lower all the notes a tone or a tone and a half respectively. This is acceptable, yes
Answer: If you don't have access to play frets past the 12th fret on your instrument, then you will not be able to play the linked tablature as it is written.
You can certainly play the same notes one octave lower.  But if you shift certain measures by an octave, and you don't shift all of the other notes in the tabbed arrangement by the exact same amount (one octave) then your melody will no longer be the same.
An integral and defining feature of any musical work is the direction that the melody moves as it progresses.  In some parts the notes go in an ascending direction (go higher) and in other parts they go in a descending direction (go lower) - often spanning one or more octaves over a given number of measures.  Using the same notes but changing only some notes by an octave without changing the other notes, can potentially change the effect of the entire song and it will no longer be recognizable as the same tune.
Tablature does not attempt to identify notes as much as it attempts to tell you what string and fret combination to play in whichever tuning the author dictates.  Two tabs written exactly the same could indicate completely different notes if one was intended to be used with an alternate tuning of the guitar.
The challenge in lowering a particular arrangement written in tab by one octave, is that you must first identify each note in the original tab.  Then you will have to find where on the guitar you can play that same note one octave lower.  In most cases it will be on a different string.  It's not really an easy thing to do unless you are very familiar with the names of all the notes on the fretboard and all the alternate places each note can be played one octave lower.
If you can't find an alternate tab for the same song that is already written one octave lower, you can create your own tab.  Go to this link Blank Tab Template and download the template and print as many sheets as you need.  Convert the tab you want to your new version by taking each note and finding the same note one octave lower on your guitar and writing it on your blank tab template.  You can do this by ear and trial and error if you don't already know where to find the octave lower note on your fretboard.
Later when your budget allows, if you want to play arrangements that call for notes to be played on the 15th or 16th fret, you might want to get a guitar with more frets and perhaps a cutaway to allow easier access to those higher notes.
Have fun.


Android remove Popmenu scroll option

Question: In portrait mode when the PopupMenu item is pressed a list of 4 items appear. In landscape mode not all the items are visible and scrolling is automatically enabled. Even though there are only 4 items, and there is definitely enough room on the screen. How do i remove the scroll option?
This is the menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools" >

   <item
       android:id="@+id/menu_userGame_uninstall"
       android:title="@string/userGames_gameMenu_uninstall"/>
   <item
       android:id="@+id/menu_userGame_similarGames"
       android:title="@string/userGames_gameMenu_similarGames"/>
   <item
       android:id="@+id/menu_userGame_share"
       android:title="@string/userGames_gameMenu_share"/>
   <item
       android:id="@+id/menu_userGame_rate"
       android:title="@string/userGames_gameMenu_rate"/>
</menu>

Answer: Create different layouts to support both potratit and landscape mode.
eg :
res/layout-land [Landscape Mode]
main.xml
res/layout-port [Portrait Mode ]
main.xml

You can refer further at :
How do I specify different layouts for portrait and landscape orientations?
Different design for landscape and portrait orientation android
http://developer.android.com/guide/practices/screens_support.html
http://developer.android.com/training/basics/supporting-devices/screens.html
Comment: I dont want different layouts. I want cancel the scroll option.

Android remove Popmenu scroll option


Find the extrema of given function $\mathbb{R}^2\to\mathbb{R}$?

Question: Let's consider the function $$f(x,y)=\begin{cases}\arctan(xy)-x^2,& \text{ where }y\leq x\\xy-\arctan(x^2),&\text{ where }y>x\end{cases}$$

Is this function continuous on $\mathbb R^2$?
What are all absolute extrema on the set $M=\{(x,y)\in\mathbb R^2:0\leq y\leq x\leq 1\}$?

As I see it the components of the function are each continuous. The problem however lies in the axis where $x=y$ where it is not continuous. To show that I took two sequences $(x_n,y_n)=(1,1+\frac{1}{n})$ and $(\tilde x_n,\tilde y_n)=(1,1-\frac{1}{n})$ that converge into $(1,1)$ but $f(x_n,y_n)\to \frac{\pi}{4}-1$ and $f(\tilde x_n,\tilde y_n)\to 1-\frac{\pi}{4}$ and I could do the same for every other point on said axis.
Now however I am a bit confused when it comes ot the extrema of $f$. We have $$\nabla f=\left(\frac{y}{x^2+y^2-1}-2x,\frac{x}{x^2y^2+1}\right)^T$$ so there is only one absolute extreme value that can be taken at $(0,0)$. But can I now just take the hessian to determine what kind of point $f$ has? I mean, it is not contiuous in that point so technically I can't compute its derivative there but since $f(0,0)=0$ and in every neighbourhood of $(0,0)$ I find both positive and negative values for $f(x,y)$ it is kind of obvious that it must be a saddle point.
And what is with the rest? Since $\nabla (f)$ has no zeros in $M$ does this mean that all the extreme values are taken on $\partial M$? If so I would look at the borders separately:

$f(x,0)=-x^2$ for all $(x,0)\in M$ so $f$ takes values in between $0$ and $-1$ here.
$f(x,x)=\arctan(x^2)-x^2$ for all $(x,x)\in M$ so $f$ takes values in between $0$ and $\frac{\pi}{4}-1$.
$f(1,y)=\arctan(y)-1$ for all $(1,y)\in M$ so $f$ takes values in between $\frac{\pi}{4}-1$ and $-1$.

All in all I can conclude now that $f$ has the global maximum $0$ which is taken at $(0,0)$ and the global minimum $-1$ which is taken at $(1,0)$. Is that correct?
Answer: A few minor points. There are some computational errors (perhaps typos?): $f(x_n,y_n)\to 1-\frac \pi 4$, $f(\tilde x_n,\tilde y_n)\to\frac \pi 4-1$, and the partial derivatives for the first branch are
$$f_x=\frac{y}{1+x^2y^2}-2x\quad\quad f_y=\frac{x}{1+x^2y^2} $$
Also, the proof you gave for discontinuity works for points $(a,a)$ where $a\ne 0$. That's enough to answer the first question but it looks like the function is continuous at $(0,0)$.
As for the second question, the function restricted to $M$ is continuous, and $M$ is a closed and bounded set. By the extreme value theorem, it has extrema on that set, and they occur either on the boundary or in the interior of $M$. If they were in the interior (where the partial derivatives exist), it would follow that $f_x=0$ and $f_y=0$ which leads us to $(x,y)=(0,0)$ and that's not in the interior. So, you can conclude the extrema occur on the boundary, and you have to check what happens there. You've already done this part. Notice that we didn't need the Hessian here.
Comment: That answered all my questions. Thanks a lot!


sum tow numbers from different sheet via google app scripts

Question: i use this code
function sumValue(){
 return "=Sum(Sheet1!f8,Sheet5!C1)";
}

to add to number from sheet1 and sheet5. but i want to remain that sum result to the same cell(Sheet5!C1) how can this code be edited.
Answer: If you are already in the script editor, we could just use more features of app script, because in your case, formula makes thing more complicated:
function sumValue() {
   var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
   var valueofSheetOne = spreadsheet.getRange("Sheet1!F8").getValue();
   var valueofSheetFive = spreadsheet.getRange("Sheet5!C1").getValue();
   spreadsheet.getRange("Sheet5!C1").setValue(valueofSheetOne + valueofSheetFive);

}

Comment: there are all good people in stack overflow, Carr you made good solution
Comment: @Negativeplus, I'm glad it's helped, welcome to the community, and maybe you could 'accept' or 'vote' the answer matching your question


Armazenar conteúdo de consulta em um array

Question: Olá, tenho uma class que realiza uma consulta no banco de dados:
$itemObra->listarItensObra($_GET['id'], 0);

Preciso usar essa consulta varias vezes e gostaria que a consulta ocorresse apenas uma vez e que os itens fossem armazenados em um array, e posteriormente usar um foreach pra listar.
foreach ($itemObra->listarItensObra($_GET['id'], 0) as $item) {
//....
}

Qualquer ideia é bem vinda!
Comment: É so jogar em uma variável, `$lista = $itemObra->listarItensObra($_GET['id'], 0);`
Comment: [Se pensar na arquitetura você pode usar o singleton Pattern](https://github.com/domnikl/DesignPatternsPHP/tree/master/Creational/Singleton)
Answer: Tem que ver sua arquitetura mas teoricamente se o seu listarItensObra retornar o array já faz assim:
$resultado = $itemObra->listarItensObra($_GET['id'], 0);

Mas não é indicado usar parametros da forma que você está usando indico usar assim:
$id = mysql_real_escape_string($_GET['id']);
$resultado = $itemObra->listarItensObra($id, 0);

Comment: Ele vai armazenar o que sua função retornar. Poste o código do seu metodo listarItensObra
Comment: Obrigado por responder, no caso, se eu usar uma variável ele não estará apenas armazenando a função da consulta? ao invés de armazenar o resultado na consulta? Abraço!
Answer: Se a consulta irá ocorrer várias vezes e se os dados dessa consulta não se alteram facilmente você também pode armazenar em uma sessão.
Por exemplo:
$_SESSION['OBRAS'] = $itemObra->listarItensObra($id, 0);

Com isso você poderá utilizar em qualquer parte do seu código a $_SESSION para fazer a listagem.


How do I get the email of the one submitting contact form in the "reply to"?

Question: Drupal 8 site. I'm using the core Contact module for basic "Contact Us" form.
How can I get the email of the person submitting the form to be in the From field? And a follow-up: How do I get the email of an authenticated user to show in the body along with the username?
Site and users:
The site is an association website. There are about 100 user accounts.
Domain and email:
The site domain is not the same as the email domain in account settings: the site is theirsite.org and the email is firstname.lastname@example.com
From & To in email
When the email came in from authenticated user or anonymous user, the From and the To are both showing firstname.lastname@example.com - the site email.
What shows in body of email:
The email from the authenticated user does not show in the body of email; only the user name and the link to their user account /user/[user-number]
When I submit a form as an anonymous user the email does show in the body.
P.S. I do not want to use the Webform module.
Comment: Your observation is correct, in the body of the email an admin gets from the site when someone uses the contact form the email address of the visitor who sent the message is shown only when the visitor is anonymous, but if the visitor is authenticated then a link to their profile is shown instead. I'm guessing this is because the profile link provides a lot more information about the visitor (including their email), but you have to visit their profile to get the address. The code responsible for this is in contact.module, so you need custom code to to override it, or maybe use email templates.
Answer: If the person submitting the form is an anonymous visitor the form will be empty and the visitor will have to fill in every field.
If the visitor is logged in (authenticated user) the name and email address are already pre-filled from their user profile.
Are you sure you're not testing this while being logged in as an admin account that has the same email address as the site? Then it's expected to see that email there.
Try to login as a different user, and also test as anonymous to see that the email is now from that different user/empty respectively for those two cases.
If you're constantly seeing the site email as From in all three cases then it's a bug and you should try to see where it's coming from. I haven't seen any problems with the Contact module, it's showing the correct "From" value every time.
Comment: Answer to your question: "Are you sure you're not testing this while being logged in as an admin account that has the same email address as the site?"

The answer is No.

FYI:  I made some improvements to my question and some details to the original submission.
Comment: This answer assumes you're asking about displaying the "From" information on the form on the site before it's being used, while it's now clear you're asking about the email message you get as an admin or user receiving a message from the site.
Comment: The From issue was the most pressing. I wouldn't care if the email was in the body of the email if the From email was the email of the person submitting the form.


WebStorm keeps treating JSX as XML

Question: My WebStorm keeps treating any JSX code as XML which then results in dozens of unwanted inspection errors, see screenshots.

Also it keeps saying "Unresolved variable or function" for most of the object keys in files, for example for props keys in ReactJS etc.

Plus other inspection warnings I have no idea how to fix.

I've never had these problems on my old Macbook, but this is a fresh install of WebStorm and its causing me headaches.
Thanks for any help
Comment: Here's an issue related to the unresolved properties: https://youtrack.jetbrains.com/issue/WEB-20884
Please follow the updates on that.

How Item and Control are exported in components/dropdown?

What testing framework do you use? Adding a TypeScript definition file for it via Preferences | Languages and Frameworks | JavaScript | Library - Download should solve the issue with the warnings for `describe`.
Answer: You need to enable JSX harmony. Most of the time webstorm proposes it to you automatically when you work with react, but you can set it manually in the options.
Go to Preferences > Language & Frameworks > Javascript
and then switch Javascript language version to JSX Harmony

WebStorm keeps treating JSX as XML


xpath preceding-sibling not working

Question: I am trying to click on the first button which deletes the item which is the second button.

       <button class="btn btn btn-danger" name="delete" type="button">

     <button class="btn" name="item" type="button">

XPath

//button[contains(.,'${ITEM}')]/preceding-sibling::button[@name='delete']
Answer: I'm going to assume you're just not showing us the button text in your example HTML, since neither of your buttons seems to have any content.
preceding-sibling would not work here, since the two buttons are not siblings. However preceding::button should work in this case. Note the [1] at the end which is needed in order to select the closest match:
//button[contains(.,'${ITEM}')]/preceding::button[@name='delete'][1]

The following should also work, and is in my opinion a bit cleaner:
//tr[.//button[contains(., '${ITEM}')]]//button[@name  ='delete']

Comment: Thanks a lot! Using preceding::button didn't work for me as it was selecting the first delete button that it found on the page but the second worked well.
Comment: Ah, yes. You would need a `[1]` at the end if you're using `preceding::`. Updated my answer just to be thorough.
Comment: Does  `preceding::button[1]` select the first match, or the *closest* match (i.e. the last match)?
Comment: @jpaugh It selects the closest one. The `preceding...` and `ancestor...` axes are known as "reverse axes": https://www.w3.org/TR/xpath/#predicates
Comment: Thanks for clarifying. I knew that `preceding-sibling` worked that way, which is why I asked. I'll edit in "closest," because it seems less confusing to refer to document-order unambiguously.

xpath preceding-sibling not working


Select next element of a given class

Question: I want to hide and show some form in my page.
For each form theres a link, and i want that, when i click on this link,
it hide and show the nearest form of the link.
My code looks like this :
    $$('.flagLink').each(function(s){
        $(s).observe('click', function(event) {
            // here i want to hide and show the nearest form
        });
    });

I've tried this :
    $$('.flagLink').each(function(s){
        $(s).observe('click', function(event) {
            $(s).next('form').toggle();
        });
    });

It works but, i would like to be more precise like :
    $$('.flagLink').each(function(s){
        $(s).observe('click', function(event) {
            $(s).next('.flagForm').toggle();
        });
    });

but the .flagForm selector doesnt work.
My code looks like this :
flag
First I hide all the form in the page :
          $$('.flagForm').each(function(s){
             $(s).hide();
          });

Then i add the onclick event on them:
$$('.flagLink').each(function(s){
        $(s).observe('click', function(event) {
            $(s).next('.flagForm').toggle();
        });
    });

But with the .flagForm selector, it does not work
Comment: The `.flagForm` selector should work. Something must be wrong with your code.
Comment: Alsciende is right, it should work. Are you sure you gave the flagForm class to your form elements?
Answer: To avoid hazardous DOM traversal, I recommend using element ids to bind a form to its link, like so:
<form id="myform1">...</form>
...
...

Then you can match the id of your A element against a regexp /link_(.*)/ to get the id of your form:
$$('.flagLink').invoke('observe', 'click', function(event) {
    if(event.element().id.match(/link_(.*)/)) $(RegExp.$1).toggle();
});

If you can't use this solution, then you have to be more specific about what you mean by "nearest". If the link and the form always have a common ancestor, then you can use a css selector to find the form wherever it is. Say the link and the form always have a common ancestor that is the grand-parent of the link, you can do:
$$('.flagLink').invoke('observe', 'click', function(event) {
    var form = event.element().up(2).select('form').first();
    if(form) form.toggle();
});

Select next element of a given class


SQL Query to distance traveled in a day based on timestamp and lat long

Question: I have a table with Date and latitude, longitude values in each row. I want a sql query to calculate the distance travailed in a day.
Say for date 2013-03-01 I want the total distance traveled,
ID      DATE                  LAT     LONG    V_ID
---------------------------------------------------
123     2013-03-01 06:05:24   45.544  86.544   1
124     2013-03-01 06:15:17   45.676  86.676   1
125     2013-03-01 06:25:24   46.544  86.544   2
126     2013-03-01 06:38:14   46.651  86.651   2
127     2013-03-02 07:12:04   46.876  86.876   1
128     2013-03-02 10:38:14   46.871  86.871   1
129     2013-03-02 10:56:14   46.871  86.671   2
130     2013-03-02 15:28:02   46.243  86.871   2

To calculate the distance what I wrote a sql function :
CREATE FUNCTION [dbo].[fnCalcDistanceKM](@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
 RETURNS FLOAT
AS
BEGIN

RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
END

but I want the total distance traveled in a day and for day 2013-03-01 I have top four row and I want total distance traveled in 2013-03-01
and similar to this date 2013-03-02 has last four row , how do I calculate distance for these rows.
Comment: please remove the mysql tag or the sql-server tag. Can't be both
Comment: GROUP BY DATE and then SUM(dbo.fnCalcDistanceKM(...))?
Comment: which version of sql server are you using? you may be able to use `STDistance` if you are using SQL Server 2008 +
Comment: Making use of LEAD too. https://msdn.microsoft.com/en-us/library/hh213125.aspx
Comment: @ughai I am getting the distance with above mentioned query.. I am looking for query to get distance traveled in first four and last four rows (as  first four has one date and other has one)
Comment: which version of sql server are you using?. like Alex said you can use `LEAD` if you are using sql server 2012 or above
Comment: @ughai  I am using the 2008 version and trying the LEAD..thanks
Comment: it won't work on 2008, you'll have to do a self join and then use your function
Answer: You can use self join with ROW_NUMBER() to get distance travelled like this.
SQL Fiddle
Query
;WITH CTE AS
(
SELECT *,CONVERT(DATE,[Date]) as tday,ROW_NUMBER()OVER(PARTITION BY CONVERT(DATE,[Date]) ORDER BY [Date] ASC) rn
FROM Travel
)
    SELECT T1.tday,SUM([dbo].[fnCalcDistanceKM](T1.lat,T2.lat,T1.long,T2.long)) as dist
    FROM CTE T1
    INNER JOIN CTE T2
        ON T1.tday = T2.tday
        AND T1.rn  = T2.rn -1
    GROUP BY T1.tday

Output
|       tday |               dist |
|------------|--------------------|
| 2013-03-01 | 129.40048639456964 |
| 2013-03-02 |  87.36216677343607 |

Comment: Thanks lot for this .. but i am getting error` Msg 3623, Level 16, State 1, Line 1
An invalid floating point operation occurred.`
Comment: I have converted string values to float as `SELECT T1.tday,SUM([dbo].[fnCalcDistanceKM]( CONVERT(float,T1.lat),CONVERT(float,T2.lat),CONVERT(float,T1.long),CONVERT(float,T2.long) )) as dist`
Comment: why is your lat and long `VARCHAR`? Might be a conversion issue but error seems to be something else.
Comment: every column is in varchar
Comment: check out  [bad habits to kick - choosing the wrong data type by Aaron Bertrand](https://sqlblog.org/2009/10/12/bad-habits-to-kick-choosing-the-wrong-data-type)
Comment: Hi If i need to query based on column `V_ID` 1 and 2 travelled on date 2013-03-01 and 2013-03-02 .. then what should i add
Comment: just add respective filters as `WHERE`
Comment: This works in fiddle with small data http://sqlfiddle.com/#!3/98904d/1 but not with thousand of record.. one V_ID appears only for once (means for one date only)
Comment: If i understand your changes, you want to group distance based on `V_ID`s now, then add `V_ID`s in join condition, change the partition by to include `V_ID` as the first column and then add the respective date columns and add the `V_ID` in `group by`


Mapping Wavefront .obj's vt to OpenGL texture coordinates

Question: an artist friend has sent me an .obj file exported by 3DS Max 2009 which contains three texture coordinates as parameters to the vt command. And that's correct according to .obj specification. However, I'm not sure how to map U-V-W coordinates that are provided for a regular 2D .jpg texture.
This is relatively important for me, since I've played with 3DS Max trying to figure out how to force it to export just U-V coordinates, but there appears to be no straightfoward way. In this case this is just a skybox, but in other cases it might be something way more complex and not hand-fixable.
Thanks!
Answer: There's a section in the article What Is UVW Mapping? that explains:

You might question why you need a
  depth coordinate like W for a 2D
  plane. One reason is because it's
  sometimes useful to be able to flip
  the orientation of a map, relative to
  its geometry. To do this, you need the
  third coordinate. The W coordinate
  also has a meaning for 3-dimensional
  procedural materials.

In your case, you can simply ignore the W coordinate and only read the first two floats of lines that begin with vt. This assumes that you're not very worried about the extra space taken by the W coordinate since .obj is quite an inefficient file format to begin with.
Personally I don't like using .obj in OpenGL because it provides vertex normals per face instead of per vertex. To light an object properly you must either duplicate vertices or calculate normals by averaging the surrounding vertex normals in a face. If you want to explore more efficient alternatives, take a look at binary formats, such as the thoroughly documented .md2 format. Also consider using glDrawElements if you're not utilizing it already.
Comment: When I was using .obj files I found that the number of "vn" entries always exceeds the number of "v" entries. Export a simple model and check this for yourself. This is because .obj provides several normals per vertex for different faces. That means that an 8 vertex cube could have up to 24 "vn" entries, one for each vertex's adjoining face. To have a one-to-one correspondence with vertices and their normals, you must do the calculation I mentioned previously. Alternatively, you can duplicate a vertex for every face it shares and then use all 24 "vn" entries. I hope that's clearer!
Comment: Here's some reputation for you :)

Ah yes, that's right. But it MUST provide several normals in case of sharp objects, such as cubes. I don't want a cube mapped smoothly, I want it to be mapped sharply! And that's what OBJ allows you to do. Averaging them is a completely wrong way to approach it; so yes, you must duplicate them and optimize them (if you wish). But the real reason why OBJ is problematic for OpenGL is that you need several indices for single face vertex; yet OpenGL doesn't support this. You'd need index array for indices... you see my point. THat's what annoys me; normals are ok
Comment: Yes, we're on the same page :D I'm glad that I'm not the only one who person who's somewhat annoyed with the .obj format in Open GL, but if sharp edges is what you want then it makes sense. Good luck!
Comment: BTW I think the .obj file has the concept of smoothing groups to address what you're discussing here.
Comment: Thanks! I'm utilizing vertex arrays + display lists already (a space sim needs very little animation). I'll mark your answer as accepted, as soon as you EDIT one little thing: You're WRONG about .obj not providing VERTEX NORMALS :-) See the "vn" command and usage of vertex normals in "f": you specify a normal per vertex, not per face. You're mixing up .obj with .3ds in this case. Besides, I'm going with .obj for now, but I'll make a transition later on to something else. Perhaps I'll even use .obj as an intermediate format: another reason to know all the details of it.
Comment: @Kai, @Ivan, is there are format that supports both sharp and smooth objects that's convenient for OpenGL?  I'm stuck with .obj for now, but I'm still curious...
Answer: sorry if I misunderstand your question. But could't you simply ignore the third parameter, w?
As I understand it, w is just a coordinate in a plane perpendicular to the plane described by u and v, so it is rarely needed for simple 2d texture mapping.
hope this helps.
Comment: That's also the way I understand it, however, it may contain some more semantic information. Otherwise, why export it if it's clearly visible it's 2D mapping, like 3ds max 2009 does?


Converting old makefile to CMake

Question: I'm trying to convert my old makefile code to CMake. Can you help me? This is the part where I'm currently stuck. I don't know how to pass these arguments to the compiler.
COMPILE_FLAGS = -c -m32 -O3 -fPIC -w -DSOMETHING -Wall -I src/sdk/core

ifdef STATIC
    OUTFILE = "bin/test_static.so"
    COMPILE_FLAGS_2 = ./lib/ABC.a
else
    OUTFILE = "bin/test.so"
    COMPILE_FLAGS_2 = -L/usr/lib/mysql -lABC
endif

all:
    g++ $(COMPILE_FLAGS) src/sdk/*.cpp
    g++ $(COMPILE_FLAGS) src/*.cpp
    g++ -fshort-wchar -shared -o $(OUTFILE) *.o $(COMPILE_FLAGS_2)
    rm -f *.o

Thank you!
Answer: Let's try to map Makefile syntax to CMake:
COMPILE_FLAGS = -c -m32 -O3 -fPIC -w -DSOMETHING -Wall -I src/sdk/core

This statement directly maps to:
SET( COMPILE_FLAGS "-c -m32 -O3 -fPIC -w -DSOMETHING -Wall" )
INCLUDE_DIRECTORIES( src/sdk/core )

A conditional of the type:
ifdef STATIC
  # Do something
else
  # Do something else
endif

is translated in CMake in this way:
OPTION(STATIC "Brief description" ON)
IF( STATIC )
  # Do something
ELSE()
  # Do something else
ENDIF()

To modify the default compilation flags you can set the variables CMAKE_<LANG>_FLAGS_RELEASE, CMAKE_<LANG>_FLAGS_DEBUG, etc. , appropriately.
Finally the compilation of an executable requires you to use the ADD_EXECUTABLE command, which is explained in many CMake tutorials.
In any case I suggest you to refer to the online documentation for further details, as it is quite explanatory and complete.

Converting old makefile to CMake


Overriding existing CSS files

Question: I want to use a css file for applying a theme. I am using myfaces that has one custom component named Scheduler.
Scheduler component is using its own css file that is within jarfile(tomahawk12-1.1.10.jar)
named schedule.css and has three theme(default , outlook, and evelutionary) but I want to use my own css file for applying theme in my project.
How can I overwrite that css file?
Comment: If you create your own css file with the same css classes and include after those other files, your rules will overwrite the previous ones.
Answer: Well it depends on if you want to completely overwrite the CSS files by changing their contents (just save over the files and possibly keep a backup copy), or if you want to just use the !important feature with your own custom stylesheet in CSS, exampled below:
leftSide {
    background-color: #0f0 !important;
}

When the !important declaration is used on a specific property/value pair, it will cause that particular value to escape the cascade and become, as the name suggests, the most important value for that property, overriding any others.
Here is more information on CSS's !important feature: http://www.impressivewebs.com/everything-you-need-to-know-about-the-important-css-declaration/
Comment: In most cases one don't need the `!important`-rule to overwrite CSS statements. Just repeat the selector and add it after the original (file). »[`!important` can be highly abused and make for messy and hard to maintain CSS](http://css-tricks.com/9462-when-using-important-is-the-right-choice/)«

Overriding existing CSS files


Meaning of 'Section Work'?

Question:
Arturo O'Farrill's Afro Latin Jazz Orchestra is one of the best jazz
  orchestras in existence, a powerhouse outfit whose precise section
  work is enhanced by thrilling soloists.

Please define 'section work' in this context.
Answer: They are talking about sections in the sense of a group of related instruments, such as a horn section.
Precise section work refers to their capability of playing together in a tight and groovy way. This section work is contrasted to the soloists, who would usually play (often improvised) melodies backed by one or more sections accompanying them.
Answer: When a large group splits into smaller sections, there will be maybe 4,5,6 players in that section. It could be a sax section, a rhythm section,, etc., who work well together and play 'in the pocket'. Arrangements may involve a soloist, or several soloists, in a longer piece, playing solos being backed by a section.

Meaning of 'Section Work'?


How can I predict a value like this from a bayesian network model?

Question: Let $\theta$ be the set of parameters for a Bayesian Network model. The model observes some data $D$. I want to then predict the values of some new data $D$. Why is the following true?
$$
p(D'|D) = \int p(D'|\theta)p(\theta|D) d\theta
$$
Does it stem from some manipulation of Bayes rule? Or the formula for expected value?
Answer: Assuming the dependency of $D'$ on $D$ is only through $\theta$, then $p(D' | \theta) = p(D' | \theta, D)$.
Now you can see all probabilities on the right hand side are simply conditional on $D$:
$$
p(D' | D) = \int p(D' | \theta, D) p(\theta | D) d\theta)
$$
This behaves exactly as if the condition on $D$ wasn't there, so for educational purposes, let's just forget about it:
$$
p(D') = \int p(D' | \theta) p(\theta) d\theta) = \int p(D', \theta) d\theta
$$
This last equation just shows the default way of integrating out one variable from a common distribution. As indicated above, this just works the same way if all distributions are conditional.


Why can't I check the sizeof a struct in C? (undeclared error)

Question: I am trying to figure out the sizeof(p) where p is the struct defined below; but, when I try and run the following code:
#include <stdio.h>

struct p
{
    char x;
    int y;
};

int main()
{
    printf("%d", sizeof(p));
    return 0;
}

I receive this error:
main.c: In function 'main':
main.c:19:25: error: 'p' undeclared (first use in this function)
     printf("%d", sizeof(p));
                         ^

I am a beginner in C and I tried to move p's definition into the main function, changing the definition of p, looking the error up online (none of the posts with the same error answered my question), etc., but I couldn't seem to get it to work. Any suggestions are appreciated.
Comment: `sizeof (struct p)` and use `printf ("sizeof struct p: %zu\n", sizeof (struct p));` (e.g. `p` is a struct tag name, not a declared instance of the struct, so to determine the size of the type `struct p` the entire type must be used and enclosed in parenthesis)
Comment: You can also define your struct like this:
typedef struct { char x;int y;} p; and then sizeof(p) should work. This behavior is different between C and C++ so it can be confusing
Comment: ah thanks that works! If someone could add that as an answer ill accept, i had no idea i was missing something so simple. Btw why do you need to say `struct` before `p` in the `sizeof` call?
Answer: In C (unlike in C++), the struct p... construct does not define a new type of variable. It only defines p as a particular type of struct. So, in order to get the size of that structure, or to declare a variable of that type, you need to use struct p to refer to it.
Like this:
#include <stdio.h>

struct p {
    char x;
    int y;
};

int main()
{
    printf("%zu\n", sizeof(struct p));
    // Alternatively ...
    struct p q;
    printf("%zu\n", sizeof(q));
    return 0;
}

Also, note that you should use the %zu format specifier for the size_t type.
Comment: @JohnD Yes, again. The structure is padded (by default) so that the `int` member is aligned on a 4-byte boundary. You can turn that off in most compilers, or change the padding size.
Comment: Hmm I was just looking into the `%zu` format specifier, i saw that it mentioned `size_t`, so C has its own data type `size_t` for holding the `sizeof` of a data structure?
Comment: @JohnD Yes. See [here](https://en.cppreference.com/w/c/types/size_t).
Comment: This is probably meant for another question but seeing as it's probably trivial, the answer it prints out is `8` instead of `5` (shouldnt it be `1` byte from the `char x` and `4` bytes from the `int y`). Is this an error in the above code or is that because of padding? Do structs pad the `char x` to 4 bytes from 1 byte?
Comment: `size_t` is an alias for another integer type
Comment: @JohnD See [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)


Notação Big O - Complexidade O(log n)

Question: Tenho algumas perguntas acerca dessa complexidade, qual base é usada nesse logaritmo, 2 ou 10? e por quê? Buscando no google vi alguns comentários falando que a base não importava.. O logaritmo está profundamente ligado a essa complexidade ou ele é utilizado apenas para dar uma ideia do quão pouco a complexidade cresce a medida que n aumenta?
Última pergunta, sabendo apenas que, enquanto n cresce exponencialmente, a busca cresce apenas linearmente, seria o suficiente para entender todos os outros casos de complexidade envolvendo logaritmo?
Comment: Possível duplicata de [Definição da notação "Big O"](https://pt.stackoverflow.com/questions/56836/defini%c3%a7%c3%a3o-da-nota%c3%a7%c3%a3o-big-o)
Answer: A base realmente não importa muito, porque um logaritmo de uma base pode ser convertido para outra base multiplicando-se por uma constante. Por exemplo: log2 10 = log10 10 / log10 2 (sendo que log10 2 é uma constante), e a notação "Big O" existe justamente para que possamos desprezar constantes.
Em se tratando de computadores, você pode pensar em termos de logaritmo base 2, porque casa bem com algoritmos no estilo "dividir e conquistar", como procura numa árvore binária, onde dobrar o número de elementos aumenta a árvore em apenas 1 nível.
Dificilmente importa o trabalho absoluto que um algoritmo exerce para um certo valor de "n". O que importa é a proporção entre diferentes valores de "n", por exemplo n=10 e n=1000000. Se você fizer log(1000000)/log(10), o resultado é sempre igual a 6, não importa a base do logaritmo, então qualquer que seja a base, O(log n) expressa corretamente a ideia de que n=1000000 custa apenas seis vezes mais trabalho que n=10 para um algoritmo O(log n).

Notação Big O - Complexidade O(log n)


MYSQL Como deletar uma linha de uma tabela com dependências?

Question: É possível deletar uma linha de uma tabela com dependências?
Eu tentei o comando
ALTER TABLE MinhaTabela NOCHECK CONSTRAINT ALL

Mas aparece o erro

Error Code: 1064. You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'NOCHECK CONSTRAINT ALL

O que está de errado?
Comment: Essa sintaxe é do SQL Server e não do MySQL, o ideal é você identificar os registros que fazem referencia a ele e tirar essa referencia antes de deletar, senão sua base vai ficar cheio de inconsistências
Comment: Entendi, obrigado, mas é possível deletar assim mesmo?
Comment: Sim, porém se você deletar somente desativando a validação da Fk, seu banco vai ficar inconsistente para sempre, até vc arrumar esses dados e isso só vai te gerar problemas no futuro
Comment: Ok, obrigado, é mais para efeito de aprendizado
Answer: A sintaxe correta para desativar e ativar FKs no MySQL é
Para desativar:
SET FOREIGN_KEY_CHECKS=0;

Para ativar:
SET FOREIGN_KEY_CHECKS=1;

O ideal é não utilizar isso para deletar os registros, pois seu banco de dados vai ficar inconsistente, e sim procurar os registros que estão relacionados com o registro que você deseja deletar e remover essa ligação, após isso você poderá deletar seu registro sem problemas.
Comment: Obrigado pela resposta


How do the hex numbers after a jump instruction translate into a memory address?

Question: I have this in my code disassembly:

I see the jump instruction code E9, but how the numbers after E9 translate into the memory address shown?
Answer: The bytes in the instruction are an offset that are added to the address of the next instruction to get the destination address.
7ffbdba881c5 + 2ab125ff = 7ffc0659a7c4
Additional information about the encoding of jumps
Near jumps with the destination in the instruction are always encoded with an signed offset relative to the address of the next instruction. In 32 or 64 bit mode, the offset can be 8 or 32 bits. (In 16 bit mode it can be 8 or 16 bits. Near jumps with an 8-bit offset are also called short jumps.) Indirect near jumps have the destination address in a register or memory location; the destination is absolute (the value to be loaded into [ER]IP).
Far jumps can have the destination either in the instruction or in a memory location; the destination has both the CS and [ER]IP values.
For more details, see an x86 instruction reference, such as the Intel SDM, Volume 2. https://software.intel.com/en-us/articles/intel-sdm


Confidence limits on a curve fit with algebraically related parameters

Question: I suspect that the required techniques for my question already exist, but I don't know what the correct nomenclature is - if so apologies, and can someone point me at the right resources?
I have a number of curves that piecewise describe a experimental data set. Some of the constants for these curves are related to each other via analytic forms. For example if I fit two sections of my data using the linear equations $y=m_1.x+c_1$ for one part, and $y = m_2.x+c_2$ for the second part, then $m_2 = m_1^2$ relates the gradients of the two lines.
Fitting $y=m_1.x+c_1$ thus defines $m_2$, and this is easy enough to implement in a fitting algorithm, however the confidence limits on $m_2$ are more problematic. Directly propagating the confidence limits on $m_1$ produces unrealistically large limits, so what do I do instead?
Edit - Sample Data added
I fit the data below x = 2 with a quadratic and above with a linear curve, enforcing continuity (including the first differential) at the intersection.
x = [1.7011 1.7234  1.7266  1.7505  1.8049  1.806   1.8592  1.862   1.8625  1.8663  1.8668  1.9239  1.9565  1.9571  1.962   2.1304  2.1739  2.1739  2.1848  2.1902  2.1902  2.1902  2.2011  2.2717  2.2717  2.288   2.2989  2.3098  2.3098  2.3207  2.3315  2.3533  2.3533  2.3913  2.4674  2.4674  2.4728  2.4728  2.625   2.6304  2.6304  2.6304]
Y = [1.2998 1.3166  1.3233  1.3491  1.3802  1.3891  1.4064  1.4094  1.4214  1.4245  1.4802  1.4843  1.4874  1.5193  1.5209  1.5729  1.6131  1.6214  1.6265  1.6281  1.6298  1.6399  1.6533  1.6667  1.6851  1.7002  1.7052  1.7102  1.7119  1.7119  1.7203  1.727   1.7353  1.7387  1.7437  1.7454  1.7538  1.7755  1.8241  1.8291  1.8325  1.8375]
Comment: It's just the delta-method.
Comment: Would you please post the data, or a link to the data?
Comment: Data added, sorry for the delay,  I was outside cell reception all day.
Answer: As an alternative answer, I found that a quadratic logarithmic equation "y = a + b * log(x) + c * pow(log(x), 2.0)" (where log is the natural log) seems to fit the entire range of the posted data fairly well, with parameters a = 3.0496816334683524E-01, b = 2.2339160821508095E+00, and c = -6.8066648613654057E-01 yielding R-squared = 0.9914 and RMSE = 0.01457


Solve for $x$: $\frac{\sqrt{x}}{2} = -1$

Question: I recently saw in the Thread on Mathematical Misconceptions a post which implied that the following equation has no known solutions: $$\frac{\sqrt{x}}{2} = -1$$
Why does this not have any solutions? It seems to me that $\sqrt{x} = -2$, so $x = (-2)(-2) = 4$. Does it not have any solutions because $\sqrt{x}$ is explicitly defined as $-2$, and if $x$ were $4$, then $\sqrt{x}$ would have to equal $\pm 2$?
Answer: The symbol $\sqrt{x}$ refers to the unique non-negative number whose square is $x$. There is no ambiguity in terms of signs for the symbol $\sqrt{x}$.
Comment: My algebra book went to great lengths to ensure that people knew $\sqrt{x}\ge0$...  I'm sort of the opposite of Betty--I thought that *everyone* knew $\sqrt{x}$ was the principal 2nd root...
Comment: Finally someone who gives the only right answer. No, it's not context dependent.
Comment: A good reason on why the square root is defined as positive: http://math.stackexchange.com/questions/158566/is-it-wrong-to-say-sqrtx-times-sqrtx-pm-x-forall-x-in-mathbbr?rq=1
Comment: Is it widely known that the symbol $\sqrt x$ is so narrowly defined?  I wasn't aware of that, and I'll bet many others aren't either.  Is there a good reason for limiting the definition of this symbol?
Comment: I don't think I ever had the need to name $-2$ has $\sqrt 4$, in fact $-\sqrt 4$ suffices.
Comment: @BettyMock : there's no good reason _not_ to limit the definition of $\sqrt{x}$.  If you want both roots, then write $\pm \sqrt{x}$.  No need to mess with confusing "branches" until you're dealing with complex numbers.
Comment: Wonderfully definitive. Cheers
Comment: @BettyMock Without this restriction, $x \mapsto \sqrt{x}$ isn't even a function, since it's not single-valued. In lower level courses, many people skim over this fact and simply emphasize that the equation $x^2 = ...$ will always have two solutions.
Comment: Just read the very lengthy discussion on the link above provided by anorton; the length alone tells me that there is a lot of ambiguity floating around. That discussion mostly focuses on $\sqrt x$ as a function; T Bongers discusses it as a symbol.  I think we all agree that a function must map each element of its domain to a unique value.  Now if we say the domain is the complex numbers surely f(z) = $\sqrt z$ is defined, but it has "branches", thus dealing with the multiple value issue. (continued)
Comment: Would it not be consistent to say that when the domain is real x > 0 the function has two branches ? This allows us to be complete, to avoid arbitrary definitions, and to introduce the idea of "branch" to less advanced students in an easy to understand example.  Those that go on to complex variables will understand "branch" right away.
Comment: @anorton  You REMEMBER your algebra book?  Are you a young person?  I don't remember mine at all, let alone what it said about square roots.  Although I do remember the names of my pet dinosaurs, Slinky and Blinky.
Comment: @BettyMock haha... yeah, I am a fairly young user.  ;) my age is in my profile.
Comment: @stephan smith -- of course whatever the community thinks is the right definition will prevail.  But sometimes we should ask questions.  Re branches, I at first found them confusing in complex analysis; if someone had just pointed out the real sqrt function, all would have been clear.
Comment: @anorton glad you found it funny; I was a little worried I might have offended you.  I've spent much of my life programming, including currently. Use this site to take breaks from it. I know for sure I never had a textbook.


Integer array column having more than one value

Question: This column is an integer array type:
log_session
-----------------------
 {105683,105694}
 {111833}
 {120285}
 {108592}
 {84659,84663}

I want to know how many log_session have just 1 value (3 in this case), and how many have more than 1 value (2 here).
EDIT:
select
    count(*) filter(where array_length(log_session, 1) = 1) as cnt_length_1,
    count(*) filter(where array_length(log_session, 1) > 1) as cnt_length_more_than_1
from mytable;

ERROR:  function array_length(integer[]) does not exist
LINE 2:     count(*) filter(where array_length(log_session) = 1) as ...
                                  ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

select version();
                                                               version
-------------------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.6.20 on x86_64-pc-linux-gnu (Ubuntu 9.6.20-1.pgdg18.04+1), compiled by gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0, 64-bit
(1 row)

Answer: You can use array_length:
select
    count(*) filter(where array_length(log_session, 1) = 1) as cnt_length_1,
    count(*) filter(where array_length(log_session, 1) > 1) as cnt_length_more_than_1
from mytable

cnt_length_1
cnt_length_more_than_1

3
2

fiddle
Comment: @arilwan: `array_length` was already available in version 9.6: https://www.postgresql.org/docs/9.6/functions-array.html. However, the `filter` clause of aggregate funtions such as `count()` was not. Probably you need to rephrase the counts, as in: `sum(case when array_length(log_session, 1) = 1 then 1 else 0 end) as cnt_length_1`
Comment: Ah, I guess this fuction is only available in recent versions of PGSQL. Currently I have access to a remote, older version `PostgreSQL 9.6.20 on x86_64-pc-linux-gnu`.
Comment: HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
Comment: `CASE`-based `filter` clause emulation should work too, but it shouldn't be necessary as `filter` support [reaches all the way back to 9.4](https://www.postgresql.org/docs/release/9.4.0/#AEN124521). OP's [edit](https://stackoverflow.com/revisions/75815373/3) isn't a clean paste because it first shows a copy of your (correct) code, but then the error message suggests they skipped the [`array_length(anyarray, int)`](https://www.postgresql.org/docs/9.6/functions-array.html#ARRAY-FUNCTIONS-TABLE) second argument (dimension) when they ran it: "`filter(where array_length(log_session) = 1)`".


Minimally working end-to-end example of drush batch job execution

Question: I'm trying to make drush run my batch jobs. There's some amount of documentation at Processing batch jobs with drush, however, I can make no sense of it.
I would like to see real code, and the CLI requirements/instructions for running it, that when called by Drush, prints something trivial, such as "Hello world", once per operation.
Answer: I've written drush CLI commands. I've also written some Batch API processes. On each individual topic you've asked about there is alot of documentation.
I'm not sure why you want to use the Batch API specifically via Drush. The Batch API in part is used to avoid HTTP request timeout in long PHP processes. If you're using Drush from the command line -- you have no max_execution_time to worry about from php.ini essentially ...

How to use the Queue API (and Batch) from DrupalCampLA2012 I attended

which goes to the actual link for the slides

A batch tutorial from March 2012 I have have referenced in creating my own BatchAPI stuff in the past (site db was down so I linked to a google cache page)

EDIT: Have you looked into the Migrate source to see how they run Batch stuff from drush cli?
Comment: For one use case, see the recent blog post on Drupal Planet about getting ~8x speedup on batch jobs by running them through Drush using Drush backend_invoke_concurrent: http://dominiquedecooman.com/blog/drupal-7-tip-concurrent-indexing-search-api-concurrent-queues-using-concurrency-capabilities-dr See also: http://drupal.org/node/1797900
Comment: Re: "I'm not sure why you want to use the Batch API specifically via Drush" – Another use case: Let's say you are developing a batch script for updating all nodes on a site, and you want to find the optimal number of nodes to process per page request. Then you could write drush scripts with and without batch API, and time or profile those.
Answer: Look at the Drush core updatedb command - this uses the batch system. You can also look at the Drupal 7 content_migrate Drush command that is part of the CCK project.
The main reason you would want to use the batch system from Drush is that it runs each batch in a separate command line process. This gives some ability to manage fatal errors (very handy when developing upgrade/migrate type systems, so you can still complete as much as possible and then go back and review errors!), as well as to constrain memory - even with an unlimited timout and unlimited memory in php.ini, Drupal static caches and other things will eventually use up all the memory on a server (I have used 8GB or more in the past) on runs that are long/complex enough.


Setting Click Event for LinkButton

Question: I have a LinkButton within a Datagrid.  I am having trouble setting a Click event for it.  I will add the OnClick="Remove_Click" attribute in the HTML. But when I go to write the actual event, VB isn't finding the LinkButton.  Therefore nothing happens.
Here is the code for it.
<asp:DataGrid ID="StandardsDataGrid" runat="server" ShowHeader="false"
    ShowFooter="false"
    AutoGenerateColumns="false" CellPadding="2" CellSpacing="0"
    ItemStyle-VerticalAlign="middle"
    DataKeyField="Id" Width="100%" BorderColor="#000">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>

            </ItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:LinkButton ID="Remove" OnClick="Removed_Click" runat="server"
                    Text="" />
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

Any ideas on why VB isn't recognizing it? Or is there a different way I should go about performing a click event?
Answer: Check this out, took me excactly one second to find it!
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemtemplate.aspx
You have to use
<asp:LinkButton ID="EditButton" runat="Server" Text="Edit" CommandName="Edit" />

and handle the Command Event of the grid
this is a common usage:
<asp:DataGrid id="DataGrid1"
   runat="server" CssClass="grid"
   AutoGenerateColumns="False">
   <Columns>
      <asp:EditCommandColumn
         EditText="Edit" CancelText="Cancel"
         UpdateText="Update" />
      <asp:BoundColumn
         DataField="OrderID" ReadOnly="True"
         HeaderText="Order ID" />
      <asp:BoundColumn
         DataField="ShipName" HeaderText="Ship to"
         ReadOnly="True" />
      <asp:BoundColumn
         DataField="ShipCountry" HeaderText="Country"
         ReadOnly="True" />
      <asp:TemplateColumn HeaderText="Ship Method">
         <ItemTemplate>
            <%#Container.DataItem("ShipVia")%>
         </ItemTemplate>
         <EditItemTemplate>
            <asp:DropDownList runat="server" ID="Dropdownlist1"/>
         </EditItemTemplate>
      </asp:TemplateColumn>
   </Columns>
</asp:DataGrid>

And here how you can handle it
Private Sub DataGrid1_UpdateCommand(ByVal source As Object, _
   ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
   Handles DataGrid1.UpdateCommand

End Sub

Setting Click Event for LinkButton


Does same image implies the same preimage?

Question: Assume $A_0$ and $A_1$ are two subsets of $A$.
If $f(A_0)= f(A_1)$ for some function $f: A \to B$, can we conclude that $f^{-1}f(A_0)=f^{-1}f(A_1)$, so that $A_0 = A_1$? Thanks!!
Comment: Of course, we get $f ^{-1}(f(A_0))=f^ {-1}(f(A_1))$. But that does not imply $A_0=A_1$.
Comment: Thanks! Is it because f might not be an injective function?
Comment: Yes, try using the definition of injective that "f(a) = f(b) implies a = b" to show this!
Answer: Let $A$ be a grocery store.
Let $A_0$ and $A_1$ be two bowls of fruit on display in the store.
$A_0$ contains cherries and oranges.
$A_1$ contains strawberries, pomegranates, and oranges.
Let $f$ be the function that takes a fruit and tells you what color it is.


How to upload a blob form in Javascript to Django backend

Question: I have an audio blob with the following code I'm looking to send to a form with javascript
function sendData(blob) {
  let fd = new FormData;
  fd.append('fname', 'test.wav');
  fd.append("recording", blob);
  let token = '{{csrf_token}}';

  $.ajax({
    url: 'landing/submit/',
    type: 'POST',
    headers: { 'X-CSRFToken': token },
    data: fd,
    cache: false,
    processData: false, // essential
    contentType: false, // essential, application/pdf doesn't work.
    enctype: 'multipart/form-data',
  });
}

I am trying to send this to a django form, but i'm getting a 403 error. Here is the view it's being sent to:
views.py

def post_new(request):
    if request.method == 'POST':
        form = PostAudio(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            return redirect('landing-home')
    else:
        form = PostAudio()
    return render(request, 'landing/submit.html', {'form': form})

What am I missing? Most other folks posting online say this has to do with not using CSRF tokens, but I included them in my headers.
Answer: Try using the @csrf_token decorator in django . I had a  similar problem that solved it.
try this
@csrf_exempt
def post_new(request):

Comment: got it. where would I put the token decorator?


Hilbert Spaces and Orthogonality

Question: $H$ is a Hilbert spaces and $M \subset H$ so $M^{\bot\bot}$ prove that it is the smallest closed subspace that covers M.
($M^\bot=\{x\in X|x\bot M \}$ and $M \subset M^{\bot\bot}$ and $x\in M \Rightarrow x \bot M^\bot \Rightarrow x\in M^{\bot\bot}$ )
Comment: What are your thoughts on this problem?
Comment: I have no idea.
Answer: One thing you can do is show that $(M^{\perp}) ^{\perp}=cl(M)$, and by definition the closure of the set is the smallest closed set containing it, one thing that is help full to use is that for a closed subspace $B$ we have $(B^\perp)^{\perp}=B$ and since $cl M^{\perp}=M^{\perp}$, basically because the inner product is continuous, we will have that $(M^{\perp})^{\perp}=(clM^{\perp})^{\perp}=clM$.

Hilbert Spaces and Orthogonality


Force-enable write cache on an AX150 disk array or fake APC SmartUPS communication

Question: I have a Dell-branded EMC AX150i disk array that refuses to enable its write cache.  After calling Dell support, it turns out that the system will refuse to enable its write cache unless an APC SmartUPS is connected to the system.
However, the AX150 is in a data center and the data center won't allow UPSes to be installed in a customer cabinet; that is, to be attached to their UPSes.  (I'm not an electrical engineer, but there's something about UPSes confusing the main DC UPS to think that there's a power fault.)
So I need to know if there is a way to force-enable the write cache on an AX150. (The Dell tech says no.)
Failing that, does anyone know of a SmartUPS communication emulator that I can use to fake the AX150 into thinking that there's a UPS there?
Comment: FWIW, the data center is installing an unprotected power circuit for us to attach the UPS to.
Answer: For anyone that is still looking for a program to Emulate the APC SmartUPS for the AX150. Here is a link to one that is done in C#. You will need .Net installed on you system to run this (4.0 it may work with 3.5). I have it running on my system right now and it has allowed for Write Caching to be enabled without the UPS. The program is based on Serial Comm program found here (http://www.dreamincode.net/forums/topic/35775-serial-port-communication-in-c%23/)
The program i am using can be found @ http://slaterhouse.com/AX150_APC.zip
I will be making some changes to it as the program right now has alot more to it then needed, but for right now it does work. (do not use the HEX option as it has not been finished.)
If you would like the source for this let me know.
jon dot slaterhouse at gmail dot com
Answer: You can try to build your own, but I don't think there's a way to force the machine to act like there was a UPS enabled.
If this costs more than 10,000$ of your time, you might be better off buying a low end replacement for the AX150 that doesn't try to force you to connect a small UPS when you have a large one feeding the whole rack.


HTML5 Video recording and automatically uploading video on server

Question: I am trying to develop a test taking website for students. In this website, students should be able to answer the questions(displayed in text format) by using webcam in one go. Currently I have implemented this feature using Flash, it captures the frames and simultaneously sends it to the server. The problem with this technique is that the quality(FPS) of my video is restricted and is dependent on the bandwidth of the internet connection. Also I am not in favor of using flash.
I want that as soon as student clicks on the start button, a timer should start to record the video. The video should get saved on the client's machine (without asking the client to mention the path) and on completion of video, it should automatically get uploaded on the server and when uploading gets completed, the video should be automatically deleted from the client's machine.
In short can anyone give me a starting point, so as to I can proceed with the work. Any helo will be highly appreciated.Thanks!
Answer: Here is a good example how to get webcam working on html5:
http://blog.teamtreehouse.com/accessing-the-device-camera-with-getusermedia
It doesnt tell how to upload the video to the server.
Comment: It is an amazing example! I am able to stream the video, however, I am not getting any lead to upload it on the server.
Answer:
Currently I have implemented this feature using Flash, it captures the frames and simultaneously sends it to the server. The problem with this technique is that the quality(FPS) of my video is restricted and is dependent on the bandwidth of the internet connection.

That is actually incorrect.
The fps you're getting depends 100% on:

the webcam quality
the light available in the room (the more light the better)
The resolution you're recording at (lower res results in higher fps even with low quality webcams in low light)

The video should get saved on the client's machine (without asking the client to mention the path) and on completion of video, it should automatically get uploaded on the server and when uploading gets completed, the video should be automatically deleted from the client's machine.

Flash records by streaming (through rtmp) the audio/video data to a media server (Red5, AMS, Wowza). After the recording is stopped you could move the file to a web server and trigger a http download.
In what regards HTML the Media Recording API has been implemented by Firefox and Chrome 49 and it allows you to record to local RAM and download the file as .webm (the audio video codecs might differ btwn browsers).
Disclaimer: I work at Pipe which handles video recording.


I want to create a column that "anonymizes" the countries column for each product

Question: Each row in my table specifies a product and country that bought it. Like this:
Product 1, Country A
Product 1, Country B
Product 1, Country C
Product 2, Country A
Product 2, Country B

I want to add another column that basically counts up each country per product. Each time starting at one for a new product.
    Product 1, Country A, Country 1
    Product 1, Country B, Country 2
    Product 1, Country C, Country 3
    Product 2, Country A, Country 1
    Product 2, Country B, Country 2

In the past this was done in a vba script simply running a loop comparing the product name with the product name from the previous row adding +1 if its the same and 1 if its not. I was wondering if there is a way to achieve this via SQL.
Answer: use row_number()
select *, row_number() over(partition by product order by country) as rn
from tablename

Answer: CREATE TABLE #Table1
    ([col1] varchar(9), [col2] varchar(9))
;

INSERT INTO #Table1
    ([col1], [col2])
VALUES
    ('Product 1', 'Country A'),
    ('Product 1', 'Country B'),
    ('Product 1', 'Country C'),
    ('Product 2', 'Country A'),
    ('Product 2', 'Country B')
;
select *, concat('Country',' ',row_number() over(partition by [col1] order by [col1])) as rn_column
from #Table1

output
col1         col2       rn_column
Product 1   Country A   Country1
Product 1   Country B   Country2
Product 1   Country C   Country3
Product 2   Country A   Country1
Product 2   Country B   Country2


Basketball Throw In

Question: When is the ball technically in play? In other words, can the defensive team 'steal' the ball from the inbounding players hands?
A ref allowed this to open stating the ball was over the baseline and therefore in play. And if this is legal, does the ball have to be fully over the baseline, otherwise would the defensive player not be breaking the plane of the line?
Comment: Did this happen in an NBA game? NCAA? A local league? There are a lot of different rules for different organizations, so some clarification may help us suss out why this may have been allowed. And welcome to Sports.SE!
Answer: According to FIBA rules this is clearly not OK; in summary, the rules state it in simple terms that until the ball has left the hands of the thrower it is still out of play and it's the defenders responsibility to stay out of contact with the ball or the thrower.
Below is an excerpt from FIBA Official Basketball Rules 2012 (Article 17)

Statement 1
  Before the thrower-in has released the ball on a
  throw-in, it is possible that the throwing-in motion  could cause that
  player's hand(s) with the ball to break the plane of the boundary line
  separating the  in-bounds area from the out-of-bounds area. In such
  situations, it continues to be the responsibility  of the defensive
  player to avoid interfering with the throw-in by contacting the ball
  while it is still in  the hands of the thrower-in.
Example:  A4 is
  awarded a throw-in. While holding the ball, A4's hand(s) crosses the
  plane of the boundary  line so that the ball is above the in-bounds
  area. B4 grabs the ball that is in A4's hand(s) or taps the  ball out
  of A4's hand(s) without causing any physical contact against A4.
Interpretation:  B4 has interfered with the throw-in, thereby delaying
  the resuming of the game. A warning shall be  given to B4 and
  communicated to coach B and this warning shall apply to all team B
  players for the  remainder of the game. Any repetition of a similar
  action by any team B player may result in a  technical foul

I could not find an explicit description of this situation in the NBA rulebook, particularly Rule #8 which governs out-of-bounds and throw-ins. However, it is clearly stated that the ball is out-of-bounds if it's in contact with a player who's out-of-bounds, which the thrower has to be. Thus the ball is not in play until the thrower releases the ball, thus a "sneak-steal" should presumably not be allowed.

Section I-Player
  The player is out-of-bounds when he touches the floor
  or any object on or outside a boundary. For location of a player in
  the air, his position is that from which he last touched the floor.
Section II-Ball
  a. The ball is out-of-bounds when it touches a player
  who is out-of-bounds or any other person, the floor, or any object on,
  above or outside of a boundary or the supports or back of the
  backboard.

It is worth noting that, according to FIBA rules, the player who's given the ball to throw in may not bounce (or drop) the ball inbounds and touch it again, before the ball is touched by another player. In other words if the ball slips out of the hands of the thrower, and bounces inbounds, it's fair game for the defender to take the ball and advance. (see Article 17, Statement 7)

Basketball Throw In


How do I change find result highlight color with VS2010 and Resharper?

Question: I just installed Resharper and it's changed the highlight color for find results. Normally when I place my cursor on a particular symbol, say a variable called 'goat', all onscreen references to goat will be highlighted with a gray background. When I hit Ctrl+F to move through all references to goat in the document the current find result has the same gray background as all others on screen. So I have no idea which goat I'm currently at until I close the find dialog at which point the currently selected goat highlights in blue.
This makes it really difficult for me to quickly check all references to a given variable in file. I know you can change color settings in Tools->Options->Environment->Fonts And Colors, however I've been unable to find a setting that corresponds to the currently selected find result.
If the currently selected find result was any color other than gray, it would stand out, but as it is it makes Find as effective as simply clicking on a variable and having VS2010 highlight all current onscreen references.
Comment: ReSharper has its own menu item at the top. Check its options.
Comment: I've checked there. ReSharper color settings are embedded in Tools->Options->Environment->Fonts And Colors
Answer: The setting to change is "Inactive Selected Text". It is in Tools->Options->Environment->Fonts And Colors, Show Settings for Text Editor, third option down.
Comment: That's it, but what I can't figure out is why ReSharper changes how the native VS Find dialog box highlights things.


How to create a lightweight domain access alternative in Drupal 7

Question: I have a password protected site mainly used for internal management of projects, but have regularly the need to publish some of its content for clients.
For simplicity sake, I would prefer to keep all content in the same database and site. However, the published content should be viewable from another domain name.
The contrib module 'Domain access' is too heavy for my needs. I'm looking for an alternative that 'simply' allows content to be published to a second domain using something like a setting or toggle per entity.
Experiences in this area are very welcome.
Comment: How do you propose to define what another site is in order to publish across to it? This is a core feature that makes DA clutch. Are these other sites Drupal based?
Comment: Hey @yuri which way did you go? I have the same issue and am reluctant to implement domain_access.
Answer: Out of the box drupal 7 installs are domain agnostic (don't save absolute urls in content or as paths). Assuming you haven't got any custom server directives or alternate domain with a need for a different relative url, you could try either:
A) Create a separate content type, if content managers know up front what content will need to be visible.
B) But if they don't know up front (and since you can't easily convert a node from one type to another), you could try using a taxonomy field to tag content for visibility. Then use taxonomy access lite module (https://www.drupal.org/project/tac_lite) to grant access to nodes tagged with a specific term to anonymous users.


Where are secant, cosecant, and cotangent applied?

Question: The textbook we use says:

The cosecant function and the secant function are the reciprocal
  functions of the sine function and the cosine function, respectively,
  and thus are also periodic functions. Their graphs are not as useful
  and are seldom encountered because the cosecant is undefined at values
  of theta where the sine has a value of zero and the secant is
  undefined where the cosine has a value of zero.

I don't know of any applications for these functions outside pure mathematics. Where are they applied outside pure mathematics (if they are applied)?
Comment: I don't know why we have a special name for $1/\cos{\theta}$ when we have $\cos{\theta}$ already, but personally I think it's kind of stupid.  These arise everywhere trig functions occur (which is pretty much everywhere).
Comment: They may be applied each time a reciprocal trig function appear somewhere. Secant and cosecant are not much used nowadays, but cotangent still appears quite often (it can arise when computing integrals for example).
Comment: I'm not sure what you mean by 'outside of pure mathematics' - the reciprocal trig functions are very useful for calculating integrals, which are pure mathematics. However, these integrals can be applied in mechanics and otherwise - would this count?
Comment: By outside pure math I mean where is it applied? Mechanics would count. Where in mechanics though?
Answer: Their graphs are often useful... though maybe not in rectangular coordinates.  Plot $r=\sec(\theta) $ or $ r=\csc(\theta)$ in polar coordinates - you get a straight line a distance $1$ from the origin.  Consequently, they are useful when you want to solve "straight line" problems in polar coordinates.
In general, polar equations are nice in physics problems because macroscopic force laws often are dependent only on the distance between two particles.  You might end up using secant if you are calculating electrical interactions between a point charge (the origin) and an infinite straight charged wire at a distance $d$, parametrized by $r=d\sec(\theta)$.  The contribution of any point on the wire to the electric field will depend on its distance $d\sec(\theta)$ from the origin.
Another example: if you are standing a distance $d$ from a long straight road watching a car go along, and you want to find the rate $d\theta/dt$ you have to turn your head to watch the car at a certain point, I believe you will find yourself differentiating $\sec$ or $\csc$ if you solve it as a related rates problem.
Answer: Using sec and csc is an anglo saxon tradition: In France for instance, we use ONLY cos and sin (cot occasionaly appears). I got an engineering degree in France without seeing sec and csc ever but they are averywhere in American and Australian textbooks.
I wonder what they do in other countries?
Laure
Comment: What a space with $sin = 0$ and $cos = 0$ looks like…? Now I wanna to visit France.


net-snmp on start says - "Error opening specified endpoint " in Raspberry pi - Jessica

Question: My raspberry pi - jessica has got snmpd --version
NET-SNMP version:  184.108.40.206
Web:               http://www.net-snmp.org/
Email:             email@example.com
Now, I am trying to make a subagent application and running it.
When I try to run this I get the following error -
$ sudo snmpd -f -Lo -C --rwcommunity=public --master=agentx --agentXSocket=tcp:localhost:1705
pcilib: Cannot open /proc/bus/pci
pcilib: Cannot find any working access method.
pcilib: pci_init failed
error on subcontainer 'ia_addr' insert (-1)
Turning on AgentX master support.
Error opening specified endpoint ""
Server Exiting with code 1

Why I get this error? Here is my snmpd.conf file.
###############################################################################
#
# EXAMPLE.conf:
#   An example configuration file for configuring the Net-SNMP agent ('snmpd')
#   See the 'snmpd.conf(5)' man page for details
#
#  Some entries are deliberately commented out, and will need to be explicitly activated
#
###############################################################################
#
#  AGENT BEHAVIOUR
#

#  Listen for connections from the local system only
agentAddress  udp:127.0.0.1:161
#  Listen for connections on all interfaces (both IPv4 *and* IPv6)
#agentAddress udp:161,udp6:[::1]:161

###############################################################################
#
#  SNMPv3 AUTHENTICATION
#
#  Note that these particular settings don't actually belong here.
#  They should be copied to the file /var/lib/snmp/snmpd.conf
#     and the passwords changed, before being uncommented in that file *only*.
#  Then restart the agent

#  createUser authOnlyUser  MD5 "remember to change this password"
#  createUser authPrivUser  SHA "remember to change this one too"  DES
#  createUser internalUser  MD5 "this is only ever used internally, but still change the password"

#  If you also change the usernames (which might be sensible),
#  then remember to update the other occurances in this example config file to match.

###############################################################################
#
#  ACCESS CONTROL
#

                                                 #  system + hrSystem groups only
view   systemonly  included   .220.127.116.11.2.1.1
view   systemonly  included   .22.214.171.124.126.96.36.199

                                                 #  Full access from the local host
#rocommunity public  localhost
                                                 #  Default access to basic system info
 rocommunity public  default    -V systemonly

                                                 #  Full access from an example network
                                                 #     Adjust this network address to match your local
                                                 #     settings, change the community string,
                                                 #     and check the 'agentAddress' setting above
#rocommunity secret  10.0.0.0/16

                                                 #  Full read-only access for SNMPv3
 rouser   authOnlyUser
                                                 #  Full write access for encrypted requests
                                                 #     Remember to activate the 'createUser' lines above
#rwuser   authPrivUser   priv

#  It's no longer typically necessary to use the full 'com2sec/group/access' configuration
#  r[ow]user and r[ow]community, together with suitable views, should cover most requirements

###############################################################################
#
#  SYSTEM INFORMATION
#

#  Note that setting these values here, results in the corresponding MIB objects being 'read-only'
#  See snmpd.conf(5) for more details
sysLocation    Sitting on the Dock of the Bay
sysContact     Me <firstname.lastname@example.com>
                                                 # Application + End-to-End layers
sysServices    72

#
#  Process Monitoring
#
                               # At least one  'mountd' process
proc  mountd
                               # No more than 4 'ntalkd' processes - 0 is OK
proc  ntalkd    4
                               # At least one 'sendmail' process, but no more than 10
proc  sendmail 10 1

#  Walk the UCD-SNMP-MIB::prTable to see the resulting output
#  Note that this table will be empty if there are no "proc" entries in the snmpd.conf file

#
#  Disk Monitoring
#
                               # 10MBs required on root disk, 5% free on /var, 10% free on all other disks
disk       /     10000
disk       /var  5%
includeAllDisks  10%

#  Walk the UCD-SNMP-MIB::dskTable to see the resulting output
#  Note that this table will be empty if there are no "disk" entries in the snmpd.conf file

#
#  System Load
#
                               # Unacceptable 1-, 5-, and 15-minute load averages
load   12 10 5

#  Walk the UCD-SNMP-MIB::laTable to see the resulting output
#  Note that this table *will* be populated, even without a "load" entry in the snmpd.conf file

###############################################################################
#
#  ACTIVE MONITORING
#

                                    #   send SNMPv1  traps
 trapsink     localhost public
                                    #   send SNMPv2c traps
#trap2sink    localhost public
                                    #   send SNMPv2c INFORMs
#informsink   localhost public

#  Note that you typically only want *one* of these three lines
#  Uncommenting two (or all three) will result in multiple copies of each notification.

#
#  Event MIB - automatically generate alerts
#
                                   # Remember to activate the 'createUser' lines above
iquerySecName   internalUser
rouser          internalUser
                                   # generate traps on UCD error conditions
defaultMonitors          yes
                                   # generate traps on linkUp/Down
linkUpDownNotifications  yes

###############################################################################
#
#  EXTENDING THE AGENT
#

#
#  Arbitrary extension commands
#
 extend    test1   /bin/echo  Hello, world!
 extend-sh test2   echo Hello, world! ; echo Hi there ; exit 35
#extend-sh test3   /bin/sh /tmp/shtest

#  Note that this last entry requires the script '/tmp/shtest' to be created first,
#    containing the same three shell commands, before the line is uncommented

#  Walk the NET-SNMP-EXTEND-MIB tables (nsExtendConfigTable, nsExtendOutput1Table
#     and nsExtendOutput2Table) to see the resulting output

#  Note that the "extend" directive supercedes the previous "exec" and "sh" directives
#  However, walking the UCD-SNMP-MIB::extTable should still returns the same output,
#     as well as the fuller results in the above tables.

#
#  "Pass-through" MIB extension command
#
#pass .184.108.40.206.4.1.8072.2.255  /bin/sh       PREFIX/local/passtest
#pass .188.8.131.52.4.1.8072.2.255  /usr/bin/perl PREFIX/local/passtest.pl

# Note that this requires one of the two 'passtest' scripts to be installed first,
#    before the appropriate line is uncommented.
# These scripts can be found in the 'local' directory of the source distribution,
#     and are not installed automatically.

#  Walk the NET-SNMP-PASS-MIB::netSnmpPassExamples subtree to see the resulting output

#
#  AgentX Sub-agents
#
                                           #  Run as an AgentX master agent
 master          agentx
                                           #  Listen for network connections (from localhost)
                                           #    rather than the default named socket /var/agentx/master
#agentXSocket    tcp:localhost:705

Answer: It's probably too late for Bali Vinayak, but might help others with like issue.
On an Ubuntu 16.04.5 LTS, NET-SNMP version: 5.7.3 I solved the same error setting snmpd to use TCP instead instead of UDP.
So edit /etc/snmp/snmpd.conf:
agentAddress  tcp:127.0.0.1:161

Then I got no error running the startup command:
systemctl start snmpd.service

Comment: You probably should do a restart. Start did nothing for me, I assume because it thought it was already running even though it was not, but it gave no error and did not start until I stopped it.
Comment: After trying 10 different things this worked for me. I wish snmpd properly logged this issue so it would be properly debuggable.
Comment: Happy to see my experience helped you out.
I agree, many error messages and log entries are too vague, generic and of little help.
Answer: I resolved it by edit /etc/snmp/snmpd.conf to this:
# agentaddress  127.0.0.1,[::1]
agentaddress  127.0.0.1

Comment: This resolved my case since I got an error message from snmpd when it tried to open a IPv 6 connection on "[::1]"
Answer: There is a bug in the /etc/snmp/snmpd.conf file.
Search for
trapsink localhost public

and add :162 after localhost, such as
trapsink localhost:162 public

Reference: https://github.com/net-snmp/net-snmp/issues/34
Answer: There is also another, simpler case which results in the "Error opening specified endpoint" message. Because other posts seem to be referencing to this at least indirectly, I will post it under this topic also. See my case:
root@am335x-evm:~# /etc/init.d/snmpd stop
Stopping network management services: snmpd snmptrapd.

Then trying to start snmpd manually:
root@am335x-evm:~# /usr/sbin/snmpd -Lo -a -f
Error opening specified endpoint "127.0.0.1"
Server Exiting with code 1

But look:
root@am335x-evm:~# ps aux | grep snmp
root       562  0.4  3.7  30944  9168 ?        Ssl  18:17   0:00 /usr/sbin/snmpd -Ls0-6d -a -f
root       570  0.0  1.9   8880  4792 ?        Ss   18:17   0:00 /usr/sbin/snmptrapd -Lsd -f
root       692  0.0  0.6   2352  1636 pts/0    S+   18:21   0:00 grep snmp

So, the init script did not actually stop it. Stopping it properly:
root@am335x-evm:~# systemctl stop snmpd
root@am335x-evm:~# ps aux | grep snmp
root       570  0.0  1.9   8880  4792 ?        Ss   18:17   0:00 /usr/sbin/snmptrapd -Lsd -f
root       708  0.0  0.6   2352  1520 pts/0    S+   18:24   0:00 grep snmp

Then trying running:
root@am335x-evm:~# /usr/sbin/snmpd -Lo -a -f
NET-SNMP version 5.8

It works.
Comment: For me, this suggestion helped me find a snap snmp daemon still running. Killed it, removed snap, and restarted the snmpd daemon. Thanks for the suggestion.


Implementar ProgressBar

Question: <code> //cria conexao com o DB
        OleDbConnection aConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Casa\Desktop\Inventario.mdb");

        //comando SQL
        OleDbCommand aCommand = new OleDbCommand("INSERT INTO Inventario (CodProd, Qtd, ValorUnit, ValorMerc)" + "Values (@CodProd,Qtd, @ValorUnit, @ValorMerc)", aConnection);

        aConnection.Open();
        try
        {
            //percorro o DataGridView
            for (int i = 0; i < vGrade.Rows.Count - 1; i++)
            {
                //limpo os parâmetros
                aCommand.Parameters.Clear();
                //crio os parâmetro do comando
                //e passo as linhas do dgvClientes para eles
                //onde a célula indica a coluna do dgv
                aCommand.Parameters.AddWithValue("@CodProd",
                     vGrade.Rows[i].Cells[0].Value);
                aCommand.Parameters.AddWithValue("@Qtd",
                    vGrade.Rows[i].Cells[1].Value);
                aCommand.Parameters.AddWithValue("@ValorUnit",
                    vGrade.Rows[i].Cells[2].Value);
                aCommand.Parameters.AddWithValue("@ValorMerc",
                   vGrade.Rows[i].Cells[3].Value);
                //executo o comando
                aCommand.ExecuteNonQuery();
            }

            MessageBox.Show("Concluído");

            //fecha a conexao
            aConnection.Close();
        }

        catch (FormatException)
        {
            MessageBox.Show("Houve um erro");

        }
    }
</code>
Como posso implementar o progressbar no código acima?
Eu estava usando o código abaixo para realizar uma tarefa semelhante ( exibir o progresso da ação), mas não sei como implementar no código acima, o que devo fazer?
<code> try
     {
         aConnection.Open();
         //cria objeto datareader  para conexao com a tabela
         OleDbDataReader aReader = aCommand.ExecuteReader();

         while (aReader.Read())
         {
             progressBar1.Increment(1);
             label1.Text = progressBar1.Value.ToString() + "%";
         }

         //fecha o reader
         aReader.Close();
         //fecha a conexao
         aConnection.Close();
     }

     finally { }
 }*/
</code>
Comment: WPF ou Windows Forms?
Answer: Veja se o código te ajuda
<code>//cria conexao com o DB
    OleDbConnection aConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Casa\Desktop\Inventario.mdb");

    //comando SQL
    OleDbCommand aCommand = new OleDbCommand("INSERT INTO Inventario (CodProd, Qtd, ValorUnit, ValorMerc)" + "Values (@CodProd,Qtd, @ValorUnit, @ValorMerc)", aConnection);

    aConnection.Open();
    try
    {
        //define o valor maximo da toolbar com o total de iterações
        progressBar1.Maximum = vGrade.Rows.Count;

        progressBar1.Minimum = 0;

        var percent = 0.0;

        //percorro o DataGridView
        for (int i = 0; i < vGrade.Rows.Count - 1; i++)
        {
            //limpo os parâmetros
            aCommand.Parameters.Clear();
            //crio os parâmetro do comando
            //e passo as linhas do dgvClientes para eles
            //onde a célula indica a coluna do dgv
            aCommand.Parameters.AddWithValue("@CodProd",
                 vGrade.Rows[i].Cells[0].Value);
            aCommand.Parameters.AddWithValue("@Qtd",
                vGrade.Rows[i].Cells[1].Value);
            aCommand.Parameters.AddWithValue("@ValorUnit",
                vGrade.Rows[i].Cells[2].Value);
            aCommand.Parameters.AddWithValue("@ValorMerc",
               vGrade.Rows[i].Cells[3].Value);
            //executo o comando
            aCommand.ExecuteNonQuery();

           progressBar1.Increment(1);

           //verifica a porcentagem de completude para exibir no label
          percent = ((double)progressBar1.Value / (double)progressBar1.Maximum) * 100;

          //existe o valor no label
          label1.Text = string.Concat(percent.ToString(),"%");
        }

        MessageBox.Show("Concluído");

        //fecha a conexao
        aConnection.Close();
    }

    catch (FormatException)
    {
        MessageBox.Show("Houve um erro");

    }
}
</code>
Answer: Insira esse trecho de código abaixo da linha
aCommand.ExecuteNonQuery();
...
<code>      //Calcula a porcentagem que i representa do total
      int percent = (int)(100 * (i+1)/vGrade.Rows.Count);

      // atualiza a progressbar
      progressbar1.value = percent;
   ...
</code>

Implementar ProgressBar


MongoDB // nodemon crash when i POST in postman

Question: When i run nodemon file.js it show this (cmd) :
(node:23816) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:23816) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

And then when i POST in Postman show this (cmd) :
events.js:287
      throw er; // Unhandled 'error' event
      ^

ReferenceError: response is not defined
    at D:\Desktop\swag-shop-api\server.js:21:7
    at D:\Desktop\swag-shop-api\node_modules\mongoose\lib\model.js:4889:16
    at D:\Desktop\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    at D:\Desktop\swag-shop-api\node_modules\mongoose\lib\model.js:4912:21
    at model.<anonymous> (D:\Desktop\swag-shop-api\node_modules\mongoose\lib\model.js:493:7)
    at D:\Desktop\swag-shop-api\node_modules\kareem\index.js:315:21
    at next (D:\Desktop\swag-shop-api\node_modules\kareem\index.js:209:27)
    at D:\Desktop\swag-shop-api\node_modules\kareem\index.js:182:9
    at D:\Desktop\swag-shop-api\node_modules\kareem\index.js:507:38
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted 'error' event on Function instance at:
    at D:\Desktop\swag-shop-api\node_modules\mongoose\lib\model.js:4891:13
    at D:\Desktop\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
[nodemon] app crashed - waiting for file changes before starting...

but when i do db.products.find({}) it shows everything i POST form postman
Please can someone help me...
server.js file:
Comment: Can you show the code from your `server.js`? It says `response` is not defined in that file.
Comment: Can you show your events.js file as well? Seems that it is causing the error.
Comment: The two warnings above can be removed by slightly modifying your connect method:
```mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })```
Comment: Welcome to the Stackoverflow community, here is some tips for a better experience when asking. https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question
Comment: @VedantBang where to modify this  "mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })"  (I'm new to MongoDB)
Answer: If you need some directions to list your documents in a collection in mongodb, just use this code as a starting point:
In line 13 you must change the code to:
app.post("/product", function(request, response) {

The name of the parameter must be response.
Comment: thank you man but now the nodemon app crash in cmd when i run 'nodemon server.js' :( btw  im new to Mongodb and stackoverflow ...
Comment: SyntaxError: Unexpected token ')'
    at wrapSafe (internal/modules/cjs/loader.js:1070:16)
    at Module._compile (internal/modules/cjs/loader.js:1120:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
    at Module.load (internal/modules/cjs/loader.js:1000:32)
    at Function.Module._load (internal/modules/cjs/loader.js:899:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
[nodemon] app crashed - waiting for file changes before starting...
Comment: I found the problem but know shows this: (node:18836) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:18836) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Swag Shop API running on port 3000...
Comment: Yes, that's already commented in original post. There is a comment with a solution.
Comment: where do i have to do that ? CMD // mongo and than > mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })  ?
Comment: In mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }), line 5. Where you do your database connection.
Comment: Line 5: var db = mongoose.connect("mongodb://localhost/swag-shop"); after this or in this.
Comment: nvm i got it, thank you so much is there any way i can review you?
Comment: We are a community of developers, we are here to help. Thanks.
Answer: Solution:
Line 5: var db = mongoose.connect("mongodb://localhost/swag-shop", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
Line 16: app.post("/product", function (request, response) {
Credits to: @Danizavts and @VedantBang.