Vertex of a pentagon-Does the algorithm always stop?

Question: To each vertex of a pentagon,we assign an integer $x_{i}$ with sum $s=\sum x_{i}>0$.
If x,y,z are the numbers assigned to 3 successive vertices and if $y<0$,then we replace $(x,y,z)$ by $(x+y,-y,y+z)$.This step is repeated as long as there is a y<0.Decide if the algorithm always stops.
Comment: If you're not willing to do any part of the work yourself but want random strangers on the internet to provide you with a "detailed solution", then why are you even in the contest?
Comment: Well I found this question in a book.I tried a lot,but couldn't figure out a solution.
Answer: This is IMO 1986 Q3.
Consider the  monovariant $S=\sum_{i=1}^{5}{(x_{i+2}-x_i)^2}$, where $x_6=x_1, x_7=x_2$.
WLOG suppose we perform an operation to get from $(x_1, x_2, x_3, x_4, x_5)$ to $(x_1+x_2, -x_2, x_2+x_3, x_4, x_5)$, and $S$ changes to $S'$. Then
\begin{align}
S-S' &=(x_3-x_1)^2+(x_4-x_2)^2+(x_5-x_3)^2+(x_1-x_4)^2+(x_2-x_5)^2 \\
& -(x_3-x_1)^2-(x_4+x_2)^2-(x_5-x_2-x_3)^2-(x_1+x_2-x_4)^2-(-x_2-x_5)^2 \\
&=-2x_2(x_1+x_2+x_3+x_4+x_5) \\
& <0
\end{align}
since $s=\sum{x_i}>0$ and $x_2<0$.
Now $S$ is clearly a non-negative integer, and is strictly decreasing in each step, so the algorithm will always stop.
There is another solution using a different monovariant here.
Comment: Thanks!Didn't realize it was an IMO question though.


Help Planning DIY Butcher Block Desk

Question: For context, I'm no professional but I'm comfortable figuring things out with advice/instructions. I'm planning on building an L-shaped desk for my kids. I've already selected the important materials, but I have some questions on assembly. First, here are the pieces I am using (I will put pictures at the end of the post).

3 Pottery Barn cabinets/pedestals (link)

All three are 16" wide x 20" deep x 29" high

2 butcher block slabs (link) and (link)

One is 74" x 25" x 1.5"
The other is 98" x 25" x 1.5"

Here is a diagram of how I plan to configure these pieces:

Here are my questions. I'm super excited to receive any advice you are willing to offer, but assume if you suggest something I will need a good reference (e.g. if you suggest a ledger board and you know of a good reference, can you point me to it or tips?). Again, I'm no pro.

Obviously the longer butcher block needs something to support it on the side with no cabinet. I suppose I could add a couple pipe legs? What is my best bet for getting something the exact right height as the other cabinet? See my wall desk question below, maybe that is my best bet?
On the longer butcher block, I'm going to have some weight there including a computer and heavy hutch. What should I do to support this length? I want to stay away from legs in the front of the desk.
On the shorter butcher block, will the two cabinets be enough to support the butcher block?
I assumed I would make this a wall desk, but I suppose it doesn't have to be. It might help with supporting the desk at the back (especially on the 98" piece). I've seen there are options such as adding a ledger board on the wall. Pros/cons of making this a wall desk?
How should I attach the two pieces of butcher block?
How should I attach the cabinets to the butcher block?
Obviously the cabinet depth is 5" shorter than the depth of the butcher block. I'd like to have the front of the cabinets flush with the front of the desk. Therefore, I'll have a 5" gap at the back. Aesthetically, do you think this will be an issue? Any suggestions on how to address this?

Here are pictures of the pedestals I am using:

Thank you in advance for your time and help!
Comment: Is there some reason you've decided to run the top supported by just one cabinet through? You'd save some hassle by doing the reverse. That and ledgers ("cleats", actually) would take care of things nicely.
Comment: I've had unsupported butcher block break.  I would support it on something like plywood, which rests on the pedestals.  The plywood can be a little smaller so that the edge isn't visible, and you can further hide the edge by painting it black or matching the pedestal color.
Answer: I would add a fourth cabinet to support the long run of the top pieces but at about 27" from the end that is in the corner. This would put two cabinet faces at right angles to each other and preclude opening drawers from both at the same time but should be of the most minor inconvenience.
The extra cabinet idea would eliminate any need to attach things to the walls.
My take is that I would set the cabinet faces an inch from the front edge of the top. That will make it look a lot better.
The top is attached to the cabinets by placing screws up through the top of the cabinet from inside the cabinet and into the bottom of the top pieces.
Joining the two top pieces together can be as simple as using several flat metal strap pieces placed across the joint and screwed into each piece up from the bottom. You can get these strap pieces at a hardware store in the same area where angle and corner brackets are found. Here is an example:

(Picture captured from Home Depot web site)

Help Planning DIY Butcher Block Desk


SQL Injection input validation

Question: I have an API built on Ruby on Rails and I DO NOT use string interpolation in ActiveRecord methods like where, find_by,.... and this prevents my code to execute any SQL injection and treat the SQL injection as String.
However, I would like to find a way to validate the params before processing the request. If any string values from the params contain SQL Injection, I would like to reject the request right away.
I have been searching for a gem to help with SQL Inject Input validation but I couldn't find any. I could use REGEX to valid the string value by looking for any select and from keyword in the string, but this is not quite a good approach because if the string value (a comment) contain text like "We select this item from the collection A", this value could be rejected if I use REGEX for select and from keyword.
What is the best I can validate SQL Injection input? Thanks! If this post happens to be duplicate, please give me the link to the similar post and I will remove this post.
Answer: This is hard to answer because it depends on how you define if a string is dangerous or not.
Typically, a string can only cause harm if it contains a single quote, so this SQL condition should be good enough:
'''' || string || '''' <> quote_literal(string)

But any way to check for single quotes should do.
Comment: if the value in the input is `(select email from customers where 1 = 1 limit 1)`, this could cause harm if the code is written like `Customer.where("email = #{email}")`, and of course no harm if the code is `Customer.where(email: email)`. What I tried to do is that I would like to reject the request if the input value is **"(select email from customers where 1 = 1 limit 1)"**, however using regex may accidentally reject **"The item (select it from the collection A)"** which is a legit comment, not a sql insject string
Comment: The example you are showing is not what is normally called SQL injection, because your string does not contain single quotes like `"WHERE email ='" + user_input + "''"`. In the case you show, the user input has to be SQL code anyway, that is, the user input would have to contain its single quotes to form a correct SQL statement. In the classical SQL injection scenario I show in this comment, any single quote is wrong.

SQL Injection input validation


Wiring light switch with 9 wires

Question: I am trying to install a single pole rocker switch in a bedroom. It has 3 sets of wires coming out. One each with a black, white and copper ground. I put all 3 black on the top pole, all 3 white on the bottom pole and all 3 copper on the ground screw. When I turn the switch off the breaker kicks. Any ideas?
Comment: you are shorting all of the black wires to all of the white wires when you turn on the switch .... just connect it same as the old switch
Comment: Bet you didn't take pictures of how it was wired, either, eh? Fun times ahead.
Comment: What do I do?  The switch I replaced is different than the old one. Both single pole but the old one was a trailer switch that you push the wires in. I thought you would put all 3 together but on the different screws??
Comment: Since the old switch was definitely not wired that way, why would you think that.  Busting into the neutral bundle when the old switch never connected to it, was just dumb.  If you don't know, find out, don't experiment with electrical.
Answer: The blacks are hot and switched hot. The whites are all neutral. Put them together on the switch and turn it on and the breaker should trip.
In the future, before disconnecting the old switch or receptacle, take a picture and mark the wires as you disconnect them. Don't disconnect/move/unbundle any wires not connected to the old switch or receptacle. *
* Exception: If the old switch didn't need neutral and the new switch needs neutral then you need to tap into the neutral bundle, if there is one.

You most likely have 3 cables with different purposes:

Incoming Power
Light Fixture
Outgoing Power to the next switch or receptacle

Figuring out which is which is the tricky part. To do this properly, you need some tools. Ideally a Non-Contact Voltage Tester, a Multimeter, some wire nuts and colored electrical tape (typically a pack of black/white/red/yellow/blue). All of which should be UL or ETL listed for safety.

Connect the white wires together with a wire nut. They will stay that way.
Connect the ground wires together with a wire nut, with a short pigtail (bare or green wire) to the switch ground screw.
Separate the black wires. Put a wire nut on each one for safety.
Turn on the breaker. Use the NCVT to determine which black wire is incoming hot. If more than one shows hot, testing with a multimeter may be needed.
Turn off the breaker. Connect the incoming hot to one screw of the switch.
Connect one of the other black wires to the other screw of the switch. This will be switched hot.
Turn on the breaker. See if the switch works to turn the light on/off. If it does, mark the switched hot wire with a piece of red tape. Connect the third black wire, outgoing hot, to the black incoming hot wire.
If the switch has no effect then the third black wire is the switched hot. Turn off the breaker. Swap it with the second wire on the switch. Turn on and test. If it works, mark it with red tape and connect the other wire to the black hot wire.

Note that you can't necessarily connect two wires to a switch screw. But what you can always do is add a pigtail, a short piece of black wire (12 AWG for a 20A circuit, 12 AWG or 14 AWG for a 15A circuit) to the two wires (incoming hot and outgoing hot) and connect the pigtail to the switch screw.
Comment: Thank you!! That's turned out to be the issue. The 3 white actually went together on a wire nut and didn't hook to switch at all. The 3 black hooked to the switch and the ground. Thank you!!
Comment: @Chris the black wire should not connect to ground

Wiring light switch with 9 wires


How can I prevent Chrome from "remembering" the scrollbar position of a container when children are re-expanded?

Question: I'm having trouble with a "feature" of Chrome where it remembers the scrollbar position of a container when it's height is re-expanded to a prior state. This feature is interfering with my application's ability to scroll an expanded item into view.
To reproduce the problem, open Chrome and run the code snippet below (or check it out on CodePen if you prefer)

* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  body: 0;
  height: 100%;
}

body {
  background: darkslategray;
}

.container {
  height: 300px;
  width: 500px;
  background: rgba(255, 255, 255, 0.2);
  margin: auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  overflow-y: auto;
  font-family: sans-serif;
  padding: 20px;
}

.item {
  display: block;
  margin-bottom: 20px;
}

.item>input {
  display: none;
}

.item>input:checked+.item-header:before {
  content: '-';
}

.item>input:checked~.item-content {
  display: block;
}

.item .item-header {
  display: block;
  padding: 20px;
  color: white;
  background: rgba(0, 0, 0, 0.8);
}

.item .item-header:before {
  display: inline-block;
  content: '+';
  width: 20px;
}

.item .item-content {
  display: none;
  padding: 20px;
  color: lightgray;
  line-height: 20px;
  background: rgba(0, 0, 0, 0.4);
}

    <input type="checkbox"/>

      Item

      Here is a bunch of content for this item. Lorem ipsum is no fun to use because it doesn't look like English. So I like to type text randomly, straight from the top. It's a nice activity to just let loose every now and then while developing.

    <input type="checkbox"/>

      Item

      Here is a bunch of content for this item. Lorem ipsum is no fun to use because it doesn't look like English. So I like to type text randomly, straight from the top. It's a nice activity to just let loose every now and then while developing.

    <input type="checkbox"/>

      Item

      Here is a bunch of content for this item. Lorem ipsum is no fun to use because it doesn't look like English. So I like to type text randomly, straight from the top. It's a nice activity to just let loose every now and then while developing.

    <input type="checkbox"/>

      Item

      Here is a bunch of content for this item. Lorem ipsum is no fun to use because it doesn't look like English. So I like to type text randomly, straight from the top. It's a nice activity to just let loose every now and then while developing.

(1)
Scroll to the bottom of the container, so the scrollbar is at the very end.

(2) Click on the last item to expand its contents. Notice how the view stays anchored in the same place while the item expands vertically. This is the desired behavior.

(3) Now scroll to the very bottom with the item still expanded.

(4) Now collapse the expanded item by clicking on it. At this point, the view will look exactly as it did in Step 1.
The trouble I'm having is that Chrome "remembers" the expanded state. Expanding the item now reverts the view to the same state as in Step 3. I'd like to "reset" the scroll position so that it instead behaves as if you were on Step 1.
I tried calculating the difference in offset().top between the item and the container before and after expansion so that I could manually adjust the scrollbar position post-expansion, but Chrome gives me identical offset values both pre and post expansion, so it's definitely doing something weird.
Can any of you brilliant minds find a way to counteract this behavior in Chrome using JavaScript? Thanks!
Comment: When did Chrome start doing this? They recently introduced Scroll Anchoring, intended to improve the user experience on mobile devices. It would also be good to see some actual code here as to how you were getting back.
Comment: https://blog.chromium.org/2017/04/scroll-anchoring-for-web-developers.html
Answer: If this is a recent bug, then it likely has to do with the roll out of "Scroll Anchoring", Chrome's newest feature intended for Mobile devices.
https://blog.chromium.org/2017/04/scroll-anchoring-for-web-developers.html
Now, before you cry bloody murder, they were nice enough to allow us to opt out of this new behavior. You need to specify the overflow-anchor CSS rule.
https://css-tricks.com/almanac/properties/o/overflow-anchor/
.your-container-which-has-the-scrollbar-in-it {
  overflow-anchor: none;
}

Let me know if that helps.
Comment: That was it! You are a hero. Thank you so much.


How can I get the sum of all the values from a dynamically generated column?

Question: So I have this code where I get the values from an XML file and dynamically create a table displaying the data. Where I am getting stuck at is when I am trying to get the totals from a specific column and then displaying them at the bottom. For example;
Column 3
3
5
6
Total 14
I can actually create and console.log a listNode but I can't necessarily do anything with that list. Thanks for your help.
This is the HTML code:
   `

                Week
                Date Range
                Appointments
                Tested Drive Through
                Positive Drive Through
                Positive Tested Offsite
                Cumulative Positive Rate
                Hospitalized Drive Through
                Hospitalized Tested Offsite

`

This is the JavaScript code:

This is an XML Example:
    <?xml version="1.0" standalone="yes"?>
<RECORDS>
    <RECORD>
        <week>3/16-20</week>
        <appointments>6</appointments>
        <empStdsTested>2</empStdsTested>
        <empStdsPositive>0</empStdsPositive>
        <empStdsPosHospital>0</empStdsPosHospital>
        <patientsTested>4</patientsTested>
        <patientsPositive>0</patientsPositive>
        <empStdsPosOffsite>1</empStdsPosOffsite>
        <empStdsPosHospitalOffsite>0</empStdsPosHospitalOffsite>
        <weekNumber>1</weekNumber>
    </RECORD>
    <RECORD>
        <week>3/23-27</week>
        <appointments>9</appointments>
        <empStdsTested>5</empStdsTested>
        <empStdsPositive>1</empStdsPositive>
        <empStdsPosHospital>0</empStdsPosHospital>
        <patientsTested>4</patientsTested>
        <patientsPositive>1</patientsPositive>
        <empStdsPosOffsite>1</empStdsPosOffsite>
        <empStdsPosHospitalOffsite>1</empStdsPosHospitalOffsite>
        <weekNumber>2</weekNumber>
    </RECORD>
    <RECORD>
        <week>3/30-4/3</week>
        <appointments>4</appointments>
        <empStdsTested>3</empStdsTested>
        <empStdsPositive>1</empStdsPositive>
        <empStdsPosHospital>0</empStdsPosHospital>
        <patientsTested>1</patientsTested>
        <patientsPositive>1</patientsPositive>
        <empStdsPosOffsite>1</empStdsPosOffsite>
        <empStdsPosHospitalOffsite>0</empStdsPosHospitalOffsite>
        <weekNumber>3</weekNumber>
    </RECORD>
</RECORDS>

Comment: If this were mine, I'd make an object array from that xml so I could just use that to generate the table and add up any fields or sort or whatever on it.
Answer: You're using query selector already, but not to its full potential. You can use it to fetch the child elements by name, which makes your code a lot more readable and maintainable.
If you use Àrray.from() to convert the records into an array, you get access to the reduce() method. This allows you to reduce the list of XML elements into specific totals.

const xmlString = getXMLString();
const dataDocument = (new DOMParser()).parseFromString(xmlString, 'text/xml');
// fetch records from XML and store them in an array
const records =  Array.from(dataDocument.querySelectorAll('RECORD'));

// get the HTML elements and remove their contents
const tableFootRow = document.querySelector('#record tfoot tr');
tableFootRow.textContent = '';
const tableBody = document.querySelector('#record tbody');
tableBody.textContent = '';

// iterate the records
records.forEach(
  (record) => {
    // add a row
    const tr = tableBody.appendChild(document.createElement('tr'));

    // read data into variables
    const empStdsTested = +record.querySelector('empStdsTested')?.textContent || 0;
    const empStdsPositive = +record.querySelector('empStdsPositive')?.textContent || 0;
    const empStdsPosHospital = +record.querySelector('empStdsPosHospital')?.textContent || 0;
    const patientsTested = +record.querySelector('patientsTested')?.textContent || 0;
    const patientsPositive = +record.querySelector('patientsPositive')?.textContent || 0;
    const empStdsPosOffsite = +record.querySelector('empStdsPosOffsite')?.textContent || 0;
    const empStdsPosHospitalOffsite = +record.querySelector('empStdsPosHospitalOffsite')?.textContent || 0;

    tr
      // create and append table cell
      .appendChild(document.createElement('td'))
      // fetch and assign column specific value
      .textContent = record.querySelector('weekNumber')?.textContent || '';
    tr
      .appendChild(document.createElement('td'))
      .textContent = record.querySelector('week')?.textContent || '';
    tr
      .appendChild(document.createElement('td'))
      .textContent = record.querySelector('appointments')?.textContent || '';
    tr
      .appendChild(document.createElement('td'))
      .textContent = empStdsTested;
    tr
      .appendChild(document.createElement('td'))
      .textContent = empStdsPositive;
    tr
      .appendChild(document.createElement('td'))
      .textContent = empStdsPosHospital;
    tr
      .appendChild(document.createElement('td'))
      .textContent = ((empStdsPositive + empStdsPosHospital) / empStdsTested * 100).toFixed(2) + '%';
    tr
      .appendChild(document.createElement('td'))
      .textContent = empStdsPosOffsite;
    tr
      .appendChild(document.createElement('td'))
      .textContent = empStdsPosHospitalOffsite;
  }
);

// add spacer cell for the first two columns
tableFootRow
  .appendChild(document.createElement('td'))
  .setAttribute('colspan', 2);

// sum up appointments and add total
tableFootRow
  .appendChild(document.createElement('td'))
  .textContent = records.reduce(
    (carry, current) => carry + (+record.querySelector('appointments')?.textContent || 0),
    0
  );

// read totals into variables
const totals = records.reduce(
  (carry, record) => ({
    empStdsTested: carry.empStdsTested + (+record.querySelector('empStdsTested')?.textContent || 0),
    empStdsPositive: carry.empStdsPositive+ (+record.querySelector('empStdsPositive')?.textContent || 0),
    empStdsPosHospital: carry.empStdsPosHospital+ (+record.querySelector('empStdsPosHospital')?.textContent || 0),
    patientsTested: carry.patientsTested+ (+record.querySelector('patientsTested')?.textContent || 0),
    patientsPositive: carry.patientsPositive+ (+record.querySelector('patientsPositive')?.textContent || 0),
    empStdsPosOffsite: carry.empStdsPosOffsite+ (+record.querySelector('empStdsPosOffsite')?.textContent || 0),
    empStdsPosHospitalOffsite: carry.empStdsPosHospitalOffsite+ (+record.querySelector('empStdsPosHospitalOffsite')?.textContent || 0)
  }),
  {
    empStdsTested: 0,
    empStdsPositive: 0,
    empStdsPosHospital: 0,
    patientsTested: 0,
    patientsPositive: 0,
    empStdsPosOffsite: 0,
    empStdsPosHospitalOffsite: 0,
  }
);
tableFootRow
  .appendChild(document.createElement('td'))
  .textContent = totals.empStdsTested;
tableFootRow
  .appendChild(document.createElement('td'))
  .textContent = totals.empStdsPositive;
tableFootRow
  .appendChild(document.createElement('td'))
  .textContent = totals.empStdsPosHospital;
tableFootRow
  .appendChild(document.createElement('td'))
  .textContent = ((totals.empStdsPositive + totals.empStdsPosHospital) / totals.empStdsTested * 100).toFixed(2) + '%';
tableFootRow
  .appendChild(document.createElement('td'))
  .textContent = totals.empStdsPosOffsite;
tableFootRow
  .appendChild(document.createElement('td'))
  .textContent = totals.empStdsPosHospitalOffsite;

function getXMLString() {
  return  `<?xml version="1.0" standalone="yes"?>
    <RECORDS>
        <RECORD>
            <week>3/16-20</week>
            <appointments>6</appointments>
            <empStdsTested>2</empStdsTested>
            <empStdsPositive>0</empStdsPositive>
            <empStdsPosHospital>0</empStdsPosHospital>
            <patientsTested>4</patientsTested>
            <patientsPositive>0</patientsPositive>
            <empStdsPosOffsite>1</empStdsPosOffsite>
            <empStdsPosHospitalOffsite>0</empStdsPosHospitalOffsite>
            <weekNumber>1</weekNumber>
        </RECORD>
        <RECORD>
            <week>3/23-27</week>
            <appointments>9</appointments>
            <empStdsTested>5</empStdsTested>
            <empStdsPositive>1</empStdsPositive>
            <empStdsPosHospital>0</empStdsPosHospital>
            <patientsTested>4</patientsTested>
            <patientsPositive>1</patientsPositive>
            <empStdsPosOffsite>1</empStdsPosOffsite>
            <empStdsPosHospitalOffsite>1</empStdsPosHospitalOffsite>
            <weekNumber>2</weekNumber>
        </RECORD>
        <RECORD>
            <week>3/30-4/3</week>
            <appointments>4</appointments>
            <empStdsTested>3</empStdsTested>
            <empStdsPositive>1</empStdsPositive>
            <empStdsPosHospital>0</empStdsPosHospital>
            <patientsTested>1</patientsTested>
            <patientsPositive>1</patientsPositive>
            <empStdsPosOffsite>1</empStdsPosOffsite>
            <empStdsPosHospitalOffsite>0</empStdsPosHospitalOffsite>
            <weekNumber>3</weekNumber>
        </RECORD>
    </RECORDS>`;
}
table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid silver;
  padding: 4px;
}

      Week
      Date Range
      Appointments
      Tested Drive Through
      Positive Drive Through
      Positive Tested Offsite
      Cumulative Positive Rate
      Hospitalized Drive Through
      Hospitalized Tested Offsite


alert box not showing asp.net

Question: here is my code
ASPX Code:
<asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="Insert" />

C#:
public void MsgBox(String MessageToDisplay)
    {
        Label lblForMsg = new Label();
        lblForMsg.Text = "";
        Page.Controls.Add(lblForMsg);
    }

protected void Button4_Click(object sender, EventArgs e)
    {
SqlCommand com = new SqlCommand("insert into employe values(@id,@pass)", con);

            SqlParameter obj1 = new SqlParameter("@Id", DbType.StringFixedLength);
            obj1.Value = TextBox4.Text;
            com.Parameters.Add(obj1);

            SqlParameter obj2 = new SqlParameter("@pass", DbType.StringFixedLength);
            obj2.Value = TextBox5.Text;
            com.Parameters.Add(obj2);

            com.ExecuteNonQuery();

            con.Close();

            MsgBox("Account Created");

            if (Session["regis"] == null)
            {
                Response.Redirect("Profile.aspx");
            }
            else
            {
                Response.Redirect("Login.aspx");
            }
      }

i want that when i click on button4, msgbox show, after that when i click ok on msgbox then it check the condition and response to the page.
i am using visual studio 2010,asp.net/c#
Comment: You call MsgBox but then you redirect to other pages. The user's browser will just go to the other page and never see the message.
Comment: @JBrooks yes u r right
Answer: To display a javascript alert message you should use RegisterClientScriptBlock
public static void ShowMessageAndRedirect(string message, string lpRedirectPage)
{
   string cleanMessage = MessageToDisplay.Replace("'", "\'");
   Page page = HttpContext.Current.CurrentHandler as Page;
   string script = string.Format("alert('{0}');", cleanMessage);
   script += " window.location.href='" + lpRedirectPage+ "';"
   if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
   {
       page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
   }
}

Similar question here: JavaScript: Alert.Show(message) From ASP.NET Code-behind
 if (Session["regis"] == null)
 {
     ShowMessageAndRedirect("Account Created","Profile.aspx");
 }
 else
 {
    ShowMessageAndRedirect("Account Created","Login.aspx");
  }

Comment: adding ScriptManager.GetCurrent(page).IsInAsyncPostBack check would make this usable for an ajax postback if you RegisterClientScriptBlock on ScriptManager instead of page.ClientScript if true
Comment: @Rick S how to call that msgbox
Comment: Show("Account Created");
Comment: @RickS i am using that but msgbox was not showing and it response on another page
Comment: Because you are calling Response.Redirect. I will update my answer to include a client redirect. You need to take out your Response.Redirect code.
Comment: @RickS how to add yes no or cacel button in that msgbox
Answer: I think if you want to display "Account Created to the User then do the following =
Response.Write("window.alert('" + MessageToDisplay + "');");
Answer: In your server-side code, you're attempting to add the message box, but immediately after that, either way your method ends with a Response.Redirect - so you're sending the user off to a new page (even if one of those pages is the same URL as the page you came from).
If you want the message box to show if the process was successful (your "account created" scenario), then whichever page you redirect to needs to include that javascript message box when it renders.
Answer: Since you like to use MsgBox.show() like that of windows form. This class will help you (vb.net)
Imports Microsoft.VisualBasic
Public Class MsgBox
Public Shared Sub Show(ByRef page As Page, ByVal strMsg As String)
    Try
        Dim lbl As New Label
        lbl.Text = ""

        page.Controls.Add(lbl)
    Catch ex As Exception

    End Try
End Sub
End Class

From within aspx.page, it can be called like this
 Msgbox.show(Me,"Alert something")

alert box not showing asp.net


How do I apply a learning rate scheduler lr_scheduler_cls to a DARTS RNNmodel?

Question: I am trying to create an RNN with learning rate scheduler using DARTS and start fitting:
rnn_model2_cov = RNNModel(model= 'GRU',
    hidden_dim=30,
    input_chunk_length=200,
    output_chunk_length=100,
    random_state=42,
    n_rnn_layers=4,
    batch_size=1024,
    dropout= 0.1,
    optimizer_kwargs={'lr': 1e-3},
    optimizer_cls = torch.optim.Adam ,
    lr_scheduler_cls = torch.optim.lr_scheduler.ReduceLROnPlateau ,
    log_tensorboard=False,
    nr_epochs_val_period = 5
)

rnn_model2_cov.fit(series=z[:15000]],
    future_covariates=[covary],
    num_loader_workers=0,
    epochs = 100,
    verbose=True
)

Fitting starts up and crashes with an error:

  File "C:\Users\micha\anaconda3\envs\darts_env\lib\site-packages\darts\utils\torch.py", line 65, in decorator
    return decorated(self, *args, **kwargs)

  File "C:\Users\micha\anaconda3\envs\darts_env\lib\site-packages\darts\models\forecasting\torch_forecasting_model.py", line 436, in fit
    self.fit_from_dataset(train_dataset, val_dataset, verbose, epochs, num_loader_workers)

  File "C:\Users\micha\anaconda3\envs\darts_env\lib\site-packages\darts\utils\torch.py", line 65, in decorator
    return decorated(self, *args, **kwargs)

  File "C:\Users\micha\anaconda3\envs\darts_env\lib\site-packages\darts\models\forecasting\torch_forecasting_model.py", line 530, in fit_from_dataset
    self._train(train_loader, val_loader, tb_writer, verbose, train_num_epochs)

  File "C:\Users\micha\anaconda3\envs\darts_env\lib\site-packages\darts\models\forecasting\torch_forecasting_model.py", line 827, in _train
    self.lr_scheduler.step()

TypeError: step() missing 1 required positional argument: 'metrics'

How & where can I pass the missing metric and how do I formulate the other arguments with lr_scheduler_kwargs={ } ? It seems to need an optimizer class as argument?
The documentation is quiet good, but very brief on this particular topic.
Answer: You are passing optimizer_kwargs and lr_scheduler_cls as you should. See a toy example with another model from darts which trains without any problem at all:
from darts.models.forecasting.nbeats import NBEATSModel

# Generic architecture
model_nbeats = NBEATSModel(
  input_chunk_length=32,
  output_chunk_length=1,
  generic_architecture=True,
  num_stacks=2,
  num_blocks=2,
  num_layers=2,
  layer_widths=256,
  n_epochs=50,
  nr_epochs_val_period=1,
  batch_size=128,
  random_state=0,
  optimizer_cls = torch.optim.Adam,
  optimizer_kwargs={'lr': 1e-3},
  lr_scheduler_cls = torch.optim.lr_scheduler.ReduceLROnPlateau,
  torch_device_str="cuda:0",
  model_name="nbeats_run",
)
model_nbeats.fit(series=train, val_series=val, verbose=True)

Notice that the lr_scheduler_cls is the Torch scheduler, i.e. torch.optim.lr_scheduler._LRScheduler. The problem is that your Darts library version was outdated and didn't support that functionality. Upgrading to version 0.16 fixes this.
Comment: I think `ReduceLROnPlateau` is only handled correctly in the most recent version of darts (see [here](https://github.com/unit8co/darts/commit/60121e494a65d229ad7e8fb62ca53990e1c1a66a)). Can you confirm what version you used?
Comment: @myrtlecat 0.16 is my darts version, didn't think of that! Hopefully the OP can confirm if that's the case!
Comment: Thanks! After the update of darts  the lr_scheduler is working. Yet, only without arguments. When I try to pass arguments to it using 'lr_scheduler_kwargs={ ... }' the ReduceLROnPlateau requires an optimizer as first positional argument. While this seems clear within the PyTorch logic what do I write when using darts?
Comment: @Micha336 not sure, can you share an example of what you have tried and what you would like to do please? :)
Comment: I have tried to setup the RNN as follows: `rnn_model2_cov = RNNModel(model= 'LSTM', ..., optimizer_cls = torch.optim.Adam , lr_scheduler_cls = torch.optim.lr_scheduler.ReduceLROnPlateau , lr_scheduler_kwargs= {threshold: 0.0001,  verbose : True}, log_tensorboard= True, ...}, ...)` Non of the arguments in the  lr_scheduler_kwargs dictionary are accepted.( I have tried all together and each separately.) According to torch.optim.lr_scheduler.ReduceLROnPlateau class I read that the first argument always must be the optimizer.
Comment: @Micha336 thank you for providing your effort. You need to quote the keys of the dict and also pass an optimizer, like this: `lr_scheduler_kwargs= {"optimizer": torch.optim.Adam, "threshold": 0.0001, "verbose": True},`, as described in https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ReduceLROnPlateau.html#torch.optim.lr_scheduler.ReduceLROnPlateau.
Answer: Using ReduceLROnPlatuea in DARTS forecast models was not correctly handled in previous versions of DARTS, and was fixed only a few weeks ago: see this commit
Updating DARTS to the latest version should fix the issue.


MDX query to filter dimension on metric values

Question: I want to filter out dimensions if the metric values not exist over that dimension, but I have some metric containing some raw data ie, Infinity, 1.#NN.
I am using NON EMPTY() but it is not filtering data correctly as it filter the dimension if all metrics are null but in my case it fetch 'Infinity' dimensions too:
Mdx Query:
SELECT
{
 [Measures].[1],
 [Measures].[2],
 [Measures].[3]
} DIMENSION PROPERTIES PARENT_UNIQUE_NAME ON COLUMNS

, NON EMPTY Hierarchize (
 {
  DrilldownLevel ( { [Roles].[Dimension].[All] } )
 }
) DIMENSION PROPERTIES PARENT_UNIQUE_NAME
, [Roles].[Roster Role].[Roster Role].[Roster Role - Enterprise]
, [Roles].[Roster Role].[Roster Role].[Roster Role - Group] ON ROWS
FROM [Cuve]
WHERE ( [Dates].[Calendar].[Calendar Year].&[2013], [Markets].[Market].&[1], [Areas].  [Area].&[8], [Roles].[Enterprise Role].&[2] )

I can not NONEMPTY() as it remove dimension if any of metric is null while I want to remove if all are null.
I want that I can filter out dimension, ie if metric value is not an integer (eg, "Infinity" or other data) or filter it out by NOT IN() kind of function.
Thanks
Comment: The equivalent of not in is basically to use Except
Answer: First, it sounds like you are dividing by 0 in the calculations for your measures.  If you can, I would rewrite them to return null where the denominator is 0.
This would look something like:
IIF([Measures].[denominator] = 0, Null, [Measures].[Numerator/[Measures].[Denominator])

Then you can use Filter. I'm not quite sure I know enough about your cube's structure to write your query, but try something like this:
Select {
[Measures].[1],
[Measures].[2],
[Measures].3]} on COLUMNS,
{ Filter([Roles].[Dimension].[Dimension].members, CoalesceEmpty([Measures].[1],[Measures].[2],[Measures].[3], 0) <> 0)
* ({[Roles].[Roster Role].[Roster Role].[Roster Role - Enterprise], [Roles].[Roster Role].[Roster Role].[Roster Role - Group]})} on ROWS
FROM [Cuve]
WHERE ( [Dates].[Calendar].[Calendar Year].&[2013], [Markets].[Market].&[1], [Areas].  [Area].&[8], [Roles].[Enterprise Role].&[2] )


Where can I see how many relics another empire has?

Question: I have seen notifications that other empires have relics. Thanks to a tech advantage I have a decent level of intel on most other empires; in the espionage screen it says I have "High" intel about their governments, and explicitly lists "Number of Relics Owned" as one of the pieces of information available to me. Where in the UI can I find this information?
Comment: I do not think this is possible at the moment
Answer: While this is not the information suggested in the tooltip and not reliant on intel, this is a way to figure out how many relics an empire has.
You can see relic score on the victory screen.
Unfortunately the relic score is different for each relic, so it won't give you an exact number with full certainty.
The score for each relic can be found in the wiki.
There are some options to limit the potential combinations:

The Galatron (20000 score) gives all other empires a wargoal which makes it easy to spot.
There will be at most one Precursor relic worth 5000 score (and if you know where the homeworld is, you'll know who most likely holds the relic).
You'll probably also know who defeated the crisis, making these relics (5000 score) easy to spot as well.

That leaves the following relics:

Relic
Score

Surveyor
200

Head of Zarqlan
200

Blade of the Huntress
200

Omnicodex
500

Rubricator
1000

Scales of the Worm
1000

Defragmentor
1000

Ether Drake Trophy
1000

Vacuum Flower
1000

Miniature Galaxy
2000

Khan's Throne
3000

Maw of the Toxic Entity
3000

Crystal of Odryskia
3000

The possible combinations lead to the following conclusions (assuming it has none of the special relics listed above, if it does, substract that value):

If the empire has a relic score of 0, it has no relics
If the empire has a relic score of 200, it has one of the first three relics
If the empire has a relic score of 400, it has two of the first three relics
If the empire has a relic score of 500, it has the Omnicodex
If the empire has a relic score of 600, it has three of the first three relics
If the empire has a relic score of 700, it has the Omnicodex and one of the first three relics
If the empire has a relic score of 900, it has the Omnicodex and two of the first three relics
If the empire has a relic score of 1100, it has the Omnicodex and three of the first three relics

All other possible combinations can be made from one of the above plus some thousands. There, the combinations become more complicated, you'll just have to calculate the possibilities.
Keep in mind that one empire can have a maximum of 8 relics and you can still check the prerequisites for a lot of them (if the Ether Drake is still around or the Khan hasn't been defeated, no one will have the corresponding relic).


Is there an alternative to rEFIt?

Question: Is there an alternative to rEFIt as a bootloader where you can choose between OS X and Ubuntu? I already installed Ubuntu on my Mac with rEFIt, so if there's a better option, I can remove it now.
I'm exploring, mainly because I want one with a more appealing UI. Other improvements are still very much welcome, though.
Comment: You should also consider asking this question on [SuperUser.com](http://superuser.com). They **may** not be able to tell you how to do it using Ubuntu, but they might know more.
Answer: It's been over two years since rEFIt has been updated, which is why I forked the rEFInd project from rEFIt. rEFInd includes a number of improvements, many of them related to directly booting Linux kernels with EFI stub loader support.
Comment: Just an fyi - rEFInd does not work on the latest MacBook Pro.
Comment: Given when you posted this, you probably ran into a bug in the 0.6.3 release. It's fixed in 0.6.4.
Comment: I managed to get rEFIt working. The only problem I have at this point is getting Linux to play nice with the hardware.
Comment: @RodSmith I've installed rEFInd as per the manual instructions for Mac OSX at http://www.rodsbooks.com/refind/installing.html#osx, but now my Mac Mini is stuck in a boot loop and the startup sound repeating over and over (the first sound is fine, but all subsequent sound distorted). What do I do now?
Comment: Also, I do not have a mac keyboard, so it doesn't recognize any boot commands.
Comment: Also, I did not use the `bless --info` command.
Comment: Try holding down the Option key at boot time; that should bring up the Mac's built-in boot manager, which should enable you to get into OS X. If the problem persists or if that doesn't work, try resetting the PRAM, as described at http://support.apple.com/kb/ht1379. You can then try installing again.
Answer: There's elilo

elilo (the efi linux loader), is the EFI equivalent of LILO, a linux boot-loader like grub. This seems to be very modern and functional software, but it's not all that easy to use. There are some installation instructions, they're rather technical.
Note that the rEFIt page on Myths and Facts About Intel Macs says that you won't be able to use accelerated  graphics when using a straight EFI boot, you need to use rEFIt for that.

I think this is the only one. Not 100% sure though.
Comment: ELILO won't enable switching between Linux and OS X; ELILO is strictly a Linux boot loader, not a boot manager (except insofar as it lets you select which Linux kernel to boot).
Comment: The rEFIt documentation is very much out of date, and the claim that accelerated graphics can't be used from a direct EFI-mode boot is quite dubious. It's probably still true of some specific Mac models, but such problems have been overcome (or never existed) for many others.
Comment: @RodSmith Is it possible to install rEFInd on a CD and use it like that, instead of installing it on my OSX hard disk?
Answer: Grub is also EFI aware.
You may find more information here:-
http://www.insanelymac.com/forum/index.php?showtopic=85508
Personally I would use Grub if possible.
Considering the amount of trouble I had getting my PC to boot from GPT partitions and the lack of documentation regarding EFI/GPT and Grub/Lilo I would say you are going to have a few hours banging your head against a brick wall before you are successful. Best of luck with it.

Is there an alternative to rEFIt?


Child element (tooltip to an image) is clipped inside a parent div which has fixed width and overflow hidden

Question: I have a parent div with fixed width with overflow hidden. The parent div has several images which I scroll using custom Javascript. For each image I have a tooltip which I want to show when I mouseover the images. The tooltips are big and are clipped when I mouseover the images since the parent div has overflow hidden. What is the best solution to this problem. I have been looking around a lot and haven't found a single feasible solution.
Any help is really appreciated. Thanks
Comment: If something's inside an "overflow: hidden" ``, then it'll be clipped; that's what the style property means. The only thing you can do is place the tooltip element absolutely as a child of the `` or something.
Answer: I suggest you to that tooltip elements will be children of the BODY, so they won't be clipped.
In order to display the tooltip in a position relative to the image, you will have to know the position of the image relatively to the BODY. Here is a method I use:
<code>function getPosition(element)
{
var position = {x:-1, y:-1};

// no element //
if (element === null) return position;

// getting offset parent
var offsetParentNode = document.body;

// calculating position //
position.x = 0;
position.y = 0;
var _parent = element;
while (_parent !== offsetParentNode && _parent !== document.body && _parent !== null)
{
    position.x += _parent.offsetLeft;
    position.x -= _parent.scrollLeft;
    position.y += _parent.offsetTop;
    position.y -= _parent.scrollTop;
    _parent = _parent.offsetParent;
}

if (offsetParentNode !== document.body && (_parent === document.body || _parent === null))
{
    position.x = -1;
    position.y = -1;
}

return position;
}
</code>


Access to excel through VBA, number display error

Question: I have created a small VBA code to export data from access to excel, when it is exported all the number formats are displayed as date in excel. I checked format in Access database its right. Could you please tell me how to display them as numbers. All the columns which are number are displayed as Date so it would be great if that code line checks for all the columns and display the correct/default format.
For reference my code,
<code>Private Sub Command4_Click()

 'Defining database variable
  Dim dbnxair As DAO.Database
  'Defining Excel variable
   Dim excelnxair As Excel.Application
  'Defining workbook variable
  Dim wrkbooknxair As Excel.Workbook
 'Defining Worksheets
 Dim wrksheetnxair As Excel.Worksheet
'Defining recordset
 Dim recsetnxair As Recordset
'Defining Querydef
 Dim querynxair As QueryDef
 'Defining query as string
 Dim strSQL As String
 'Defining condition string
Dim strlistcondition As String

'Opening the database
 Set dbnxair = CurrentDb()

'Creating the Excel object
Set excelnxair = CreateObject("Excel.Application")
 'Opening the worksheet
  excelnxair.Visible = True

  'Creating a new workbook
 Set wrkbooknxair = excelnxair.Workbooks.Add
 wrkbooknxair.SaveAs "C:\Users\z003cnxt\Desktop\new1.xls"

  'Creating a new worksheet
 Set wrksheetnxair = excelnxair.Sheets(1)

 'Creating a query
Set querynxair = dbnxair.CreateQueryDef("")

 For Each varItem In Me!List2.ItemsSelected
   strlistcondition = strlistcondition & ",'" & Me!List2.ItemData(varItem) & "'"
Next varItem

strlistcondition = Right(strlistcondition, Len(strlistcondition) - 1)

strSQL = "SELECT * FROM [Std Table] WHERE ([Std Table].Country IN(" & strlistcondition    & "));"

'Adding Sql statement
 querynxair.SQL = strSQL

'Creating and opening the recordset
 Set recsetnxair = querynxair.OpenRecordset()

  'Copying data to excel sheet
  excelnxair.Cells.CopyFromRecordset recsetnxair

  'Adding field names in each columns
 For lvlcolumn = 0 To recsetnxair.Fields.Count - 1
   excelnxair.Cells(1, lvlcolumn + 1).Value = recsetnxair.Fields(lvlcolumn).Name
 Next

 wrksheetnxair.Cells.AutoFilter
wrksheetnxair.Cells.EntireColumn.AutoFit

  Set dbnxair = Nothing
 Set recsetnxair = Nothing
  Set querynxair = Nothing
 Set wrkbooknxair = Nothing
Set wrksheetnxair = Nothing
Set excelnxair = Nothing

For Each varItem In Me!List2.ItemsSelected
  Me!List2.Selected(varItem) = False
Next varItem

End Sub
</code>
Comment: Why don't you just use `DoCmd.TransferSpreadsheet`? For parameter `TableName`, you would be able to use your `SELECT` query.
Comment: Could you please give me the exact syntax for transferspreadsheet bcoz it gives me error when i use with the recordset
Comment: TransferSpreadsheet does not work on recordsets. You can use instead of implementing your own code.
Answer: I solved my problem by setting all the numberformat as sFormat in my code that worked. But still I am yet to find the solution for dateformat.
Regards,
jeeva


it says that it cant find symbol refering to arraylist commands, like ".get" ".add" yes im very new to java

Question: It says that it cant find symbol referring to arraylist commands, like ".get" ".add".
import java.util.ArrayList;
import java.util.Iterator;

public class ProductPrices {

        private ArrayList<String> products = new ArrayList<String>();
        private ArrayList<Double> prices = new ArrayList<Double>();

        public ProductPrices(String products, double prices) {

            //this.products() = products();
            //this.prices() = prices();
        }

        public void put(String products, double prices) {

            for(int i=0; i<products.size(); i++){
                products.add(i);
            }
            for(int i=0; i<prices.size(); i++){
                prices.add(i);

                ArrayList<String> mergePriceProduct = new ArrayList<String>(products.get(i) + prices.get(i));

            }
            products() = mergePriceProduct();

        }
        public double get(String products) {

            Iterator<String> productIter = products.iterator();
            while (proditer.hasNext()){
            System.out.println(prodIter.nextString());
            }

        }
}

Comment: Your method parameters are shadowing the instance variables. Ie you have a list called products, but you also have a variable callled products of type string. and string doesn't have add. if you add this.products.add() it will work
Comment: Actually there are a lot of other mistakes in your code as well. but its not so easy to understand what you want to achieve here... It's probably best you study up a bit more on Java.
Answer: Your code has couple of issues, but specifically in context of get and add methods, you are facing variable shadowing.

Shadowing refers to the practice in Java programming of using two
variables with the same name within scopes that overlap. When you do
that, the variable with the higher-level scope is hidden because the
variable with lower-level scope overrides it. The higher-level
variable is then "shadowed."

In your case the class level variable name to ArrayList of products and prices is same as your local variable of method put and get. If you want to refer class level variable:

Either rename one of the variable
Or use class level variable with this keyword as this.prices


Map SYS_REFCURSOR parameter from stored procedure

Question: I have stored procedure in Oracle DB. It's output parameters are Number ("RETURN_VALUE") and three parameters of SYS_REFCURSOR type ("ONE", "TWO"...). I know how to call this procedure and to get numeric parameter:
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
        .withProcedureName("NAME")
        .withReturnValue();
Map<String, Object> response = call.execute(new MapSqlParameterSource(...));
Integer responseCode = (Integer) response.get("RETURN_VALUE");

But how to map SYS_REFCURSOR parameter to some List of DesiredClassType?
List<DesiredClassType> list = (List<DesiredClassType>) response.get("ONE");

Answer: I found a solution for this problem by using a CallableStatement instead of SimpleJdbcCall.
@Component
public class DaoExample {

    private static final String PROCEDURE_CALL_SQL = "{call SCHEME.PROC_NAME(?,?,?,?,?,?,?,?,?)}";

    private DataSource dataSource;

    DaoExample(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void callProcedure() {

        try (Connection con = dataSource.getConnection();
             CallableStatement stmt = con.prepareCall(PROCEDURE_CALL_SQL)) {
            con.setAutoCommit(false);

            // set input parameters
            stmt.setInt("input_parameter_name1", 1);
            stmt.setString("input_parameter_name2", "2");
            stmt.setNull("input_parameter_name3", OracleTypes.VARCHAR);
            stmt.setDate("input_parameter_name4", Date.valueOf("2021-04-23"));

            // set output parameters
            stmt.registerOutParameter("output_parameter_name1", OracleTypes.NUMERIC);
            stmt.registerOutParameter("output_parameter_name2", OracleTypes.CURSOR);
            stmt.registerOutParameter("output_parameter_name3", OracleTypes.CURSOR);
            stmt.registerOutParameter("output_parameter_name4", OracleTypes.CURSOR);
            stmt.registerOutParameter("output_parameter_name5", OracleTypes.CURSOR);

            stmt.execute();

            // example of getting an int parameter value
            Integer responseCode = stmt.getInt("output_parameter_name1");

            // example of getting a set of values and mapping them to a List<Account>
            ResultSet accountsRs = (ResultSet) stmt.getObject("output_parameter_name2");
            List<Account> accounts = new ArrayList<>();

            while (accountsRs != null && accountsRs.next()) {
                accounts.add(new Account()
                    .setAccountNumber(accountsRs.getString("STRING"))
                    .setAccountCloseDate(accountsRs.getDate("DATE") == null
                        ? null
                        : accountsRs.getDate("DATE").toLocalDate())
                    .setAccountBalance(accountsRs.getBigDecimal("BIG_DECIMAL")));
            }

            //...
        } catch (Exception e) {
            //...
        }
    }
}


Segmentation fault (core dumped) in pyqt5

Question: I tried to make pyqt5 application with QWebEnginePage rebootable. But got segfault. Here is code sample:
import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import qApp
#from PyQt5.QtWebEngineWidgets import QWebEnginePage

from PyQt5.QtCore import QTimer

from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView

class MainWindow(QMainWindow):
    EXIT_CODE_REBOOT = -123
    def __init__(self,parent=None):
        QMainWindow.__init__(self, parent)
        self.timer = QTimer()
        self.timer.timeout.connect(self.restart)
        self.timer.start(3 * 1000)

        self.qwe = QWebEngineView()
        #self.qp = QWebEnginePage()  # uncomment this will cause Segmentation fault (core dumped)

    def restart(self):
        print('restart')
        qApp.exit(MainWindow.EXIT_CODE_REBOOT)

if __name__=="__main__":
    currentExitCode = MainWindow.EXIT_CODE_REBOOT
    while currentExitCode == MainWindow.EXIT_CODE_REBOOT:
        print('next..')
        a = QApplication(sys.argv)
        w = MainWindow()
        w.show()
        currentExitCode = a.exec_()
        a = None

With this comments - it works fine. But if remove comment's 'Segmentation fault (core dumped)' appears.
Can you give me an advice for this?
EDIT
Reproduced on PyQt 5.9.3 and Ubuntu 14.04
Comment: I tried it in Qt 5.9.3 in Arch Linux and it does not generate that error.
Comment: @eyllanesc you are talking about version without comments? It has to print 'next' several times.
Comment: That's why I say it works well, it does not generate Segmentation fault (core dumped), it prints `next` every time the timer fires.
Comment: I just saw your code better and I see that I have to uncomment a line, I'm going to try again.
Comment: @Raj. Put the `a = QApplication(sys.argv)` line before the while loop and remove the `a = None` line. It is never safe to create more than one QApplication (even if you try to delete the old one).
Comment: @ekhumoro I know about that QApplication should be created only once. But behavior in my example is quite strange. I expected that it wouldn't work in both cases.
Comment: @Raj. If you know that, why did you have that expectation? And why would care about it, anyway? What *practical* use-case do you have for re-creating application objects? What *specific* problem are you trying to solve?
Answer: Same error when I used anaconda PyQt5
I installed PyQt5 by
conda install -c anaconda pyqt

error result:
>>> from PyQt5 import *
>>> from PyQt5.QtGui import *
Segmentation fault (core dumped)

solved by:
pip install PyQt5

result:
>>> from PyQt5 import *
>>> from PyQt5.QtGui import *
>>>

Hope it works!


Excel, Trying to use Row() to reference cell for Indirect() pull of data from other tab

Question: <code>Target Tab Name     Data (date)     Formula used to grab it

1   RTP SVC MCU         01/31/15        ='RTP SVC MCU'!G1
2   RTP SVC MCU         01/31/15        =INDIRECT("'" & B2 & "'!G1")
3   RTP SVC MCU         #REF!           =INDIRECT("'" & ("B" & ROW()) & "'!G1")

Row test        B5  ="B" & ROW()
</code>
On my worksheet I'm creating a summary tab that will pull various bits of information from other tabs. The example marked 1 grabbed the date from tab "RTP SVC MCU", cell G1, simple and straight-forward.
Example 2 does the same, but I removed the explicitly defined tab name and replaced it with a reference to the tab name which already exists for the summary in B14.
Example 3 attempts to do the same, but without explicitly defining the cell containing the Tab name. Basically I'd like to grab the tab name from the Target Tab Name column for it's own Row number so that all the date columns (and others) can be populated without just dragging the formula down with Auto Fill because there need to be blank rows between the summaries.
Long story short, I'm trying to combine the effects of my rows marked 2 and "Row Test".
Answer: You need another INDIRECT:
<code>=INDIRECT("'" & (INDIRECT("B" & ROW())) & "'!G1")
</code>
Comment: Holy hell you're awesome. Thank you.


Absolute method to find the domain of a composite function

Question: Let two functions $  h:\mathbb R → \mathbb R , g:\mathbb R → \mathbb R $ be defined by the formulas $ h(x)=\sqrt{x-1} $, $ g(x)=3x^{2}-1 $ with
$ D(h)=\{x \in
\mathbb R:x≥1\} $
What is the domain of $ g \circ h $ ?
There are two ways to solve this question. One is using the definition of $ D(g \circ h) $ which is,
$D(g \circ h)=\{x \in D(h) : h(x) \in D(g)\} $
Here,$ D(g) = \mathbb R$ . So, $ h(x) \in \mathbb R \ \ \forall x≥1  \implies  D(g \circ h)=\{x \in
\mathbb R:x≥1\} $
Another way is to get the composite function and then finding the domain manually.
So, we get, $ g \circ h=g(h(x))=g(\sqrt{x-1}) = 3(\sqrt{x-1})^2 -1=3x-4
 $ . It's clear that for all $ x \in \mathbb R \ \,  g \circ h $ holds . So $ D( g \circ h) = \mathbb R $ .
What is correct then?
Comment: The 1st one is correct. Not the 2nd one, because $(\sqrt{x-1})^2$ is equal to $x-1$ only when it is defined, i.e. when $x-1\ge0.$ Btw, "for all $ x \in \mathbb R \ \,  g \circ h $ holds" is meaningless. I think you meant the (however wrong) statement "for all $ x \in \mathbb R \ \,  g \circ h (x)$ is defined.
Answer: The second method is not correct.
Consider a simpler example,
$$\begin{align*}
&f : \mathbb{R}_{\ge 0} \to \mathbb{R} \\
&g : \mathbb{R}  \to \mathbb{R} \\
&f(x) = \sqrt x\\
&g(x) = x^2
\end{align*}$$
How does one find $g(f(x))$ for a particular $x$, e.g. how does one find $g(f(2))$? Well, you find $f(2)$ first, and plug that into $g(x)$. You do not simplify first. (Remember your discussions on removable discontinuities from Calculus I?)
Hypothetically, say we expanded the domain of $f$ to include, say, $-1$. But then we have $(\sqrt{-1})^2$ as $g(f(-1))$. Interpreting the square root as a function of real numbers, then, this is nonsensical: $\sqrt{-1}$ isn't defined, so how can we square it? We can claim to leverage properties about $i^2=-1$, but we're not dealing with complex numbers and you would have to thoroughly justify the use of exponent properties.
Another framing is that you can only claim $g(f(x)) = x$ for $x$ for which $f(x)$ is defined, and in turn that $g(f(x))$ is defined. At every step along the way you need to ensure that.
Another framing is that, into $g(f(x))$, look at what numbers you plug in to find $f(x)$ first. You have to be able to plug them into $f$ first and foremost, so you're looking at its domain, not a "sensible widening" of the domain as your second method tries to use.
Answer: The first method is correct. Not the second one, because $(\sqrt{x-1})^2$
is equal to $x−1$
only when it is defined, i.e. when $x−1≥0.$ Therefore, "$3(\sqrt{x-1})^2 -1=3x-4$" does not hold for every real number $x,$ but only for $x\ge1.$
By the way, "for all $ x \in \mathbb R \ \,  g \circ h $ holds" is meaningless. I think you meant the (however wrong) statement "for all $ x \in \mathbb R \ \,  (g \circ h)(x)$ is defined".
Comment: I just tried to improve this answer, but without any explanation from  the downvoter, it is difficult to know how do do better.


Maximum number of cyclic quadruplets in tournament

Question: Consider a tournament with $n$ contestants - that is, a complete graph directed graph $K_n$ where each edge is pointed one way or the other. We call a subset $\{a,b,c\}$ a "cyclic triplet" if each of the three wins one of the two games against the other two. It is not hard to find a maximum number of cyclic triplets.
We can argue by considering the triplets involving a particular contestant that the maximum number of "cyclic triplets" among such triplets occurs when he beats  half of the remaining contestants. Hence the global maximum occurs when everyone beats half the remaining ones.
Now, define a subset $\{a,b,c,d\}$ to be a "cyclic quadruplet" if two contestants win two games against the other two, while the remaining two win one game. What is the maximum number of cyclic quadruplets?
Answer: The following article contains the desired result:
The answer for your question


Simple Django validation with multiple parameters issue

Question: I've been playing with Django for a couple of days and stumbled upon the following issue. I have the following models:
Employee = (id, employeeName)
Project = (id, projectName)
Assignment = (fk_employee, fk_project, from_date, to_date)

What I want to do is to create a validator that won't allow assignment periods to overlap. The algorithm is very simple, but I don't know how to properly set it using validators.
What I thought is to have something like:
class Assignment(models.Model):
    ...
    from_date = models.DateField(
        validators=[DateInRangeValidator(%theFromDateValue%, %aReferenceToTheEmployee%)])
    to_date = models.DateField(
        validators=[DateInRangeValidator(%theToDateValue%, %aReferenceToTheEmployee%)])

def DateInRangeValidator(dateValue, employee):
    ...

BTW, I wrote these %theDateValue% and %aReferenceToTheEmployee% because I don't know how to send those parameters. Would it be 'self', 'from_date' or something else?
So, am I close to the solution? Thanks in advance! :)
Answer: You need access to more than one field of the model, and that's a model validation rather than a field validation.
So you may consider overriding the clean method of the Assignment class.
This part of the Django document may be helpful for you.
Comment: Thanks for answering :) As per the documentation this seems to be the solution. I'll play with it for a while and I'll post back later.


Installing Times New Roman font

Question: How can I install the Times New Roman font?  This video illustrates what I want to do, but I do not have the same options - I'm running Ubuntu 12.10.
I have also tried running the following from the terminal:
sudo apt-get install msttcorefonts
sudo apt-get install ttf-mscorefonts-installer

This is the message I receive:
Reading package lists... Done
Building dependency tree
Reading state information... Done
ttf-mscorefonts-installer is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 4 not upgraded.

Any suggestions?
Comment: @burnsmicro Your comments links to this qestion... :/
Comment: The above did not work for me. Fortunately, http://askubuntu.com/questions/210680/installing-times-new-roman-font worked fine.
Answer: Your best bet may be the --reinstall option.
Force a reinstallation with:
sudo apt-get --reinstall install ttf-mscorefonts-installer

which will force the preinst and postinst scipts that actually install the fonts to be re-run.
Comment: This worked on my Ubuntu 12.04. I must remove and reinstall that package and reconfigure it. Now Times New Roman can be added into my Libreoffice. It works.
Comment: After running `sudo apt-get --reinstall install ttf-mscorefonts-installer` the directory `/usr/share/fonts/truetype/msttcorefonts/` is empty. Where to look for the `.ttf` files?
Answer: Ubuntu 18.04 LTS
I didn't find msttcorefonts  in the apt pool, so I installed only ttf-mscorefonts-installer. It works for me
sudo apt install ttf-mscorefonts-installer

Comment: Since `msttcorefonts` is not in any current release (including 14.04), I just removed it from the top answer.
Answer: Ubuntu 16.04
Single Font Install
If you already own a copy of the Times New Roman Font (and any other fonts you want to install) and have it on your local Download directory (unzipped) and ready to install, then I have a simple solution that does not require the apt-get.... command line or internet connection. It is a simple off-line graphical solution.
Warning! You do have to use your wrist, finger, and mouse! But not the Terminal :-)
Also! You have to do this manually for each font you want to install, so it could take a little time if you want a bunch of fonts junking up your system. But you did indicate you wanted one Specific Font.... Times New Roman. (This might work on other versions of Ubuntu as well)
Assuming the font is in your download directory.....

Open the Ubuntu file manager and go to the unzipped Times.ttf file in your download directory and
double-click the file.
The Font Viewer window will open and display
the various sizes of example font texts. eg...The quick brown fox
..... whatever.......
Look at the top right corner of the Font Viewer screen and you will
see a button that says Install.
Click it and you are done!

When I did this, no reboot was required, with the exception of closing whatever app you were currently running like LibreOffice Writer. Just close and re-open Libre.
If you dont have a local copy on your machine, any WindowZ machine should have it available.
Open the file manager and go to windows, then the Fonts sub-folder/directory. Its down there somewhere listd as:

times.ttf- normal
timesbd.ttf-bold
timesbi.ttf- bold italic
timesi.ttf - italic

If it's considered stealing from Bill G/MS "I dunno", but that is your call.
By the way, per the synaptic install information notes,
ttf-mscorefonts install more than just the Times New Roman fonts, and I believe you still have to download them.
Comment: What a long answer just to say "If you already have the TTF, you can just double click it to open in Font Viewer and click 'install' in the top right"

Installing Times New Roman font


What do 'hitbox' and 'hurtbox' mean?

Question: I've heard of hitboxes, then I heard of hurtboxes. They seem most relevant to fighting games. What do each of them mean and how do they differ?
Answer: In most games Hitboxes and Hurtboxes are the same thing. They both refer to the area on the entity in which you (or more specifically, your own hitbox/hurtbox) can come into contact with for selection (talk to, or to interact with), or dealing damage. When getting specific, the Hitbox is the area that you can interact with on another entity, and the Hurtbox is the area on an entity that when interacted with (generally as part of combat), causes the entity to take damage.
As an example, Minecraft hitboxes are indicated by the white wire-frames surrounding the mobs, and items. (The hitbox representation for the player is glitched in this image - caused by the 3rd person camera offset):

Technically, this is the same "area" that can also deal damage to you (when a player punches another player, or swings at them with a weapon), it is based on this same area. Depending on how you interact with another entity however, determines if you interact with the Hitbox, or the Hurtbox - anything the can receive damage from you with a left click will take damage if it hits, making it a Hurtbox. Otherwise, if you right click, it turns back into a Hitbox.
As you can see: interacting/swinging at the pig's head will yield nothing, as it is not within the bounds of the hitbox.
However, in other games, mainly fighting games, like Street Fighter or Tekken, they are different. The hitbox is the area that will hit the opponent (red area), while the hurtbox is the area that you can take damage from an enemy attack during your attack (green box):

In addition to this, there are also some games that can have multiple versions of hitboxes on the same entity. For example, in games like CoD, the head has a different hitbox to the body, and limbs, as hitting an enemy in each specific area would do more or less damage (I.e. a "headshot" would do the most, body less, and the limbs would do the least amount of damage per "hit").
Comment: How is it the same thing in Minecraft? You don't take damage for walking into a pig.  Swinging your sword doesn't check for collision with your character.
Answer: In fighting games, in particular, a hitbox is the area of the screen that will do damage if it touches an enemy hurtbox. A hurtbox is the area of the screen where a character is vulnerable to attack.

In this image, the blue box is the hurtbox, while the red is the hitbox.
In other genres, hitbox is often used to refer to both the area of an attack, and the outline of a character used in hit detection.
Comment: I think in modern games, there can be multiple hit and hurt boxes, all with different damage calculations. Shooters definitely have multiple hit boxes for headshots and stuff, and knowing the details of that hit box is even crucially important for playing competitively
Comment: They are usually no longer "boxes" either, but follows the sprite.  The detection is no longer just a box anyways, but the concept is still the same.
Comment: @Nelson This depends on the game, but generally speaking, visuals and hit/hurtboxes do not directly correspond to the actual visuals, in my experience. Some games might be closer, but most have a separation between what shows up on screen and how damage works.

What do 'hitbox' and 'hurtbox' mean?


Windows Authentication User.Identity.Name to email address

Question: I have already tried to use How to obtain email address with window authentication, but a question remains:
I know how to ask for email address for John Smith, but what I get as authentication name is like INTRA\\JohnSmith3 or DEP21\\JohnSmith
How can I map INTRA\\JohnSmith3 or DEP21\\JohnSmith to the correct John Smith in AD?
Answer: What you get from Windows Authentication is the SAM Account Name. You need to look this up in Active Directory.
You can query Active Directory for users like this:
<code>(&(objectCategory=person)(objectClass=user)(sAMAccountName=JohnSmith3))
</code>
In code:
<code>string filter = "(&(objectCategory=person)"
     + "(objectClass=user)"
     + "(sAMAccountName=" + samAccountName + "))";
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = filter;
SearchResult result = search.FindOne();
DirectoryEntry de = result.GetDirectoryEntry();
</code>
Comment: If I omit the domain, aren't DEP21\\JohnSmith and HQ\\JohnSmith pointing to the same AD entry?
Comment: The SAM Account Name does not include the domain. You can do a search where you don't do a `FindOne()` but a `FindAll()` and then filter the results on domain. To see how to find the domain of a given user, check out this other question on SO: http://stackoverflow.com/questions/4249139/c-sharp-active-directory-get-domain-name-of-user
Comment: So best would be to extract the domain name from the User.Identity.Name and use it to connect to the AD for that domain?


create autocomplete combobox and textbox without distinct the result C#.net

Question: <code>    private void LoadData()
    {
        MedicalCustomersDBEntities db = new MedicalCustomersDBEntities();
        CustomerList = db.Customers;
        AutoCompleteStringCollection completeSource = new AutoCompleteStringCollection();

        completeSource.AddRange(CustomerList.Select(ar => " " + ar.FirstName).ToArray());
        completeSource.AddRange(CustomerList.Select(ar => ar.FirstName).ToArray());
        this.AutoCompleteMode = AutoCompleteMode.Suggest;
        this.AutoCompleteSource = AutoCompleteSource.CustomSource;
        this.AutoCompleteCustomSource = completeSource;
    }
</code>
I use this code to load all my customers. But when I have two customers with the same name the autocomplete  textbox make distinct for result.
Is there a way to show all result.
Answer: Why don't you make use of distinct in the query itself.
CustomerList = db.Customers.Name.Distinct();
I don't have a PC, but you can try something like that....The above code is not right
Comment: thanks Pankaj Upadhyay , but I need some things opposite of distinct


How can I troubleshoot faulty carbon monoxide and fire alarms that give false positives?

Question: This is kind of an odd one. Recently, my alarms have been going off. It started a couple weeks ago where my neighbor said the carbon monoxide alarm was going off for 10-15 minutes then stopped. Last Saturday, it seemed like only one of the carbon monoxide alarms was going off, so I changed the battery and everything was fine. Last night, everything started going off, carbon monoxide and fire alarms. I unplugged all the carbon monoxide alarms in the house ( excluding the one in the basement above the boiler ).
I checked the manufacture date, January 2015. They were probably installed by the fire department when I bought the house last year.
How can I debug this? I was planning on trying to clean them and change all the batteries. I can't imagine they need to be replaced they're still too new.
Comment: You seem to be assuming that the devices are malfunctioning. Why?
Comment: CO alarms don't age like smoke alarms. You don't have any other way of testing whether there's CO present so you have to assume it is. At the very least you need to shut off the gas supply (to stop all gas-burning appliances) including to the floor below if it's a flat. And ventilate. And that's mainly so it's safe for someone to come in and check properly.
Comment: Are these standalone battery only units? Or line voltage interconnected with battery backup?   What make/model are the detectors?
Comment: @Tyson Yes, they're interconnected. Update to this, so I checked the manual and the LED flashing and beeps match up with the CO alarm receiving a signal from the fire alarm that there's smoke. Trust me there's no smoke, and the fire alarms are not going off. Every time I plug the CO alarms in they sound with this the above mentioned status.

I can't imagine a fire alarm sending a signal without it going off itself.

My plan now is to buy a new CO alarm and plug it in. If it goes off like the others than it has to be the fire alarm(s) sending bad signals.
Comment: @isherwood, I'm a programmer, I assume everything has bugs. Also, this just started happening. There hasn't been a rhyme or reason to it. Many of my windows are cracked all the time. And last night, when I got home I left the door open. Plenty of air flow but the alarms went off.
Comment: Unless the one in the basement has been setting the others off. It's right above the boiler and close to the hot water heater.
Comment: @Quirk -- do you have a multimeter? And are these alarms using an interconnect wire, or some sort of wireless interconnect?
Comment: Final update to this, I believe I figured out the problem. In short, faulty connection. Since I have an interconnected system, I unplugged everything. I plugged in the 2nd floor CO alarm which didn't sound. I moved to the 1st floor and preceded to plug that in, as I was connecting it to the wires in the ceiling, I noticed the positive lead was loose. I pushed it in tight and plugged the second CO alarm in. Everything was silent, so I pulled the loose wire back out and the alarm started to sound, same status as before. Voila! Thanks everything for providing some insight.
Answer: You can procure carbon monoxide test gas with a known PPM (parts per million) concentration. Place your CO detector in a small plastic bag that can be sealed tight but squeeze the bag down to reduce the amount of air that is in the bag with your detector before sealing it. Spray the carbon monoxide test gas into the bag that houses the alarm and seal the bag. Wait... Without testing with a known quantity of gas you may always wonder. A short Youtube video demonstrating this can be viewed at www.coexperts.com
Comment: The test gas canister is around $20 + HAZMAT shipping. for that amount one can replace their CO alarm :-)
Answer: You can debug this by getting another CO alarm preferably a different manufacturer and putting it adjacent to your existing one. If both alarms go off, then you can be certain that CO is detected.
If only your existing (old) alarm sounds and new one remains quiet, call the manufacturer of the old alarm.
Do not unplug your CO alarms as there could be a real danger that you are trying to mute!
Even while debugging heed to the warning all the time. When the warning alarm sounds, move to fresh air.


Conflicting types and previous declaration of x was here...what?

Question: I've been teaching myself C for a few months when I have time, and I have run into a problem I am not sure how to fix.
Specifically, when I try to compile this using gcc, I get:

geometry.c:8: error: conflicting types for 'trapezoid'
geometry.c:7: note: previous declaration of 'trapezoid' was here
geometry.c:48: error: conflicting types for 'trapezoid'
geometry.c:7: note: previous declaration of 'trapezoid' was here
geometry.c:119: error: conflicting types for 'trapezoid_area'
geometry.c:59: note: previous implicit declaration of 'trapezoid_area' was here
geometry.c: In function 'cone_volume':
geometry.c:128: error: called object '3.14100000000000001421085471520200371742248535156e+0' is not a function
geometry.c: In function 'cylinder_volume':
geometry.c:136: error: called object '3.14100000000000001421085471520200371742248535156e+0' is not a function

Now, I think I may need to typecast the functions, but again, I am not sure.
It looks like it wants to read PI, which I had defined as 3.141, as a function. Is there a way I can avoid using the magic number 3.141 (though it's much less of a magic number than others)?
//Geometric formulae
#include <stdio.h>
#include <math.h>

#define PI 3.141

float trapezoid(float b1, float b2, float h);
int trapezoid();
float sphere_volume(float r);
int sphere();
float cone_volume(float r, float h);
int cone();
float pyramid_volume(float b, float h);
int pyramid();
float cylinder_volume(float r, float h);
int cylinder();

int main(void) {
        char selection = 0;

        while(selection != 'q') {
                printf("\t--Geometric Formulas--\n");
                printf("\tSelection an option from the menu: ");
                scanf("%c", & selection);
                switch(selection) {
                        case 1: //Trapezoid area
                                printf("%d", trapezoid());
                                break;
                        case 2: //Sphere volume
                                printf("%d", sphere());
                                break;
                        case 3: //Cone volume
                                printf("%d", cone());
                                break;
                        case 4: //Pyramid volume
                                printf("%d", pyramid());
                                break;
                        case 5: //Cylinder volume
                                printf("%d", cylinder());
                                break;
                        default:
                                break;
                }
        }
}
//      --Shape Menus--
//Trapezoid
int trapezoid() {
        float h = 0, b1 = 0, b2 = 0;
        float traparea;

        printf("\tTrapezoid base 1: ");
        scanf("%3f", &b1);
        printf("\tTrapezoid base 2: ");
        scanf("%3f", &b2);
        printf("\tTrapezoid height: ");
        scanf("%3f", &b2);

        traparea = trapezoid_area(b1, b2, h);

        printf("\tTrapezoid Area: %3f\n", traparea); }

//Sphere
int sphere() {
        float r = 0;
        float spherevol;

        printf("\tSphere radius: ");
        scanf("%f", &r);

        spherevol = sphere_volume(r);

        printf("\tSphere volume: %3f\n", spherevol); }

//Cone
int cone() {
        float r = 0, h = 0;
        float conevol;

        printf("\tCone radius: ");
        scanf("%f", &r);
        printf("\tCone height: ");
        scanf("%f", &h);

        conevol = cone_volume(r, h);

        printf("\tCone volume: %3f\n", conevol); }

//Pyramid
int pyramid() {
        float b = 0, h = 0;
        float pyramidvol;

        printf("\tPyramid base: ");
        scanf("%f", &b);
        printf("\tPyramid height: ");
        scanf("%f", &h);

        pyramidvol = pyramid_volume(b, h);

        printf("\tPyramid volume: %3f\n", pyramidvol); }

//Cylinder
int cylinder() {
        float r = 0, h = 0;
        float cylindervol;

        printf("\tCylinder radius: ");
        scanf("%f", &r);
        printf("\tCylinder height: ");
        scanf("%f", &h);

        cylindervol = cylinder_volume(r, h);

        printf("Cylinder volume: %3f", cylindervol); }

//      --Geometric Formulas--
//Trapezoid Area Computation
float trapezoid_area(float b1, float b2, float h) {
        return ((b1 + b2) * h) / 2; }

//Sphere Volume Computation
float sphere_volume(float r) {
        return ((pow(r,3)) * (4 * PI)) / 3; }

//Cone Volume Computatioin
float cone_volume(float r, float h) {
        return ((PI(pow(r,2)) * h)) / 3; }

//Pyramid Volume Computation
float pyramid_volume(float b, float h) {
        return (b * h) / 3; }

//Cylinder Volume Computation
float cylinder_volume(float r, float h) {
        return (PI(pow(r,2))) * h; }

Answer: Any of them that say there was an 'implicit' definition: this can be solved by pre-declaring it.  As an example, you pre-declared float trapezoid and int trapezoid, but you didn't pre-declare trapezoid_area.  As others pointed out, you also can't overload in C as you can in C++.
In a few areas you're trying to do implicit multiplication -- eg, PI(pow(r,2)) should be PI * (pow(r,2)).
Comment: Not that I mind the nomination, but ... I only answered a very small portion of the question.  Are you sure you meant to select mine as the correct answer?
Answer: The errors you're seeing are because you're defining the same function twice with different signatures
float trapezoid(float b1, float b2, float h);
int trapezoid();

Based on your other definitions it looks like the first trapezoid functions should be named trapezoid_volume
float trapezoid_volume(float b1, float b2, float h);
int trapezoid();

Comment: The different signature generates this type of error (confirmed).
Answer: C does not support function overloading. C++ does.
And since you accidentally declared trapezoid_volume as trapezoid, you get a compiler error.
Answer: you defined twice function trapezoid.
C isn't C++. You can't define the same function with different signatures like you do in C++ using overloading features.
Comment: Thank you...fixed...but now it displays
/tmp/ccn6YvQ0.o: In function `sphere_volume':
geometry.c:(.text+0x39d): undefined reference to `pow'
/tmp/ccn6YvQ0.o: In function `cone_volume':
geometry.c:(.text+0x3d0): undefined reference to `pow'
/tmp/ccn6YvQ0.o: In function `cylinder_volume':
geometry.c:(.text+0x41b): undefined reference to `pow'
collect2: ld returned 1 exit status
Comment: @Bowlslaw: you haven't linked math library. Try gcc with -lm option if you are using linux.
Comment: The -lm option worked, even though I have linked the math.h library.
Comment: I know this is a 12 year old post, but you aren't "linking" math.h, it's not an object or library file. It's a header file, and you're INCLUDING it in your .c file to provide various definitions to the compiler.

Linking is the process of combining your compiled object file(s) into either an executable or library file.
Answer: #define PI 3.141

float trapezoid(float b1, float b2, float h);
int trapezoid();

I think you want
float trapezoid_volume(...);
/*             ^^^^^^^                 */

Answer: To answer your question about defining PI - pi is usually defined in math.h (as M_PI), but since it's not part fo the actual standard you might need to do some configuration to get it.
For example, when using MSVC you need to define _USE_MATH_DEFINES to get it. See

http://www.gnu.org/s/hello/manual/libc/Mathematical-Constants.html

http://www.gnu.org/s/hello/manual/libc/Trig-Functions.html#Trig-Functions
for the GNU C library's information.

If your platform doesn't have it, you might want to throw something like the following into a header:
#ifndef
#define M_PI 3.14159265358979323846264338327
#endif


Overload operator >> for all enum types

Question: I have enumeration type , for which I overload the operator>>.
std::istream& operator >>(std::istream &is,MyEnum& enumVar)
{
  int intVal;
  is>>intVal;
  enumVar = intVal;
  return is;
}

How to avoid writing this code for all future enum types, i.e how to write the function so it is applicable to all enum types?
Comment: You could use `templates` to achieve a genericity for your method, but you will need to use a constraining-mechanism to ensure that only your enums are accepted as arguments. Unfortunately, `constraints` are not supported by C++ that easily.
Comment: I know that I can do something with templates and boost::enable_if but I can't really understand how it actually works
Comment: http://www.boost.org/doc/libs/1_53_0/libs/utility/enable_if.html
Comment: Tough one... I don't know about `boost`, sorry...
Answer: Make the operator a template and enable it only if the template parameter is an enum (using enable_if):
#include <type_traits>

template<typename T>
typename std::enable_if<std::is_enum<T>::value, std::istream&>::type
operator >>(std::istream &is, T& enumVar)
{
  std::cout << "enum\n"; // just to see it is this one that gets used
  int intVal;
  is >> intVal;
  enumVar = static_cast<T>(intVal); // note the explicit cast to make it legal
  return is;
}

If you don't have C++11 avaliable, you can use boost's type_traits library.
Seeing your comment that you don't know exactly how enable_if works, here is a link with a detailed explanation.
In short, enable_if templates come in pairs - one with a member typedef of second template parameter to type when the condition (first template parameter) is true, and one without that typedef when condition is false. Template instantiations with false condition are invalid, because the member typedef does not exist. Such instantiation is then (instead of being a hard compiler error) discarded from overload set for later overload resolution. Read also about SFINAE.
EDIT: boost's enable_if works slightly differently than the standard one. Use either:
boost::enable_if < boost::is_enum<T>, std::istream& >::type
                // ^^^^^^^^^^^^^^^^^
                // expects a type

or
boost::enable_if_c < boost::is_enum<T>::value, std::istream& >::type
                  // ^^^^^^^^^^^^^^^^^^^^^^^^
                  // expects a value

Comment: Thank you. I use boost, so I replaces std:: with boost:: in your code. And unfortinetaly I am getting compiler errors : error C2923: 'boost::enable_if' : 'boost::is_enum::value' is not a valid template type argument for parameter 'Cond'
Comment: template
typename boost::enable_if::value, std::istream&>::type
operator >>(std::istream &is, T& enumVar)
{
    std::cout << "enum\n";
    int intVal;
    is >> intVal;
    enumVar = static_cast(intVal); // note the explicit cast to make it legal
    return is;
}

Overload operator >> for all enum types


How to resolve JavaScript 'Unxpected Token Error'?

Question: I have written some JavaScript code which, when run, produces the following error:
"error"
"SyntaxError: Unexpected token ILLEGAL

I don't know what does this error mean. I tried googling it but couldn't find anything useful.
Here's my code:

HTML:

$(document).ready(function(){
   $('#fostering').on('click', function(){
       $(this).animate({
           width : 50px;
       });
   });
});

<!DOCTYPE html>

        <meta charset="utf-8">
        <title> Something </title>

So,

What's causing this error?
How do I resolve it?
Comment: It's ok, well it arises when you have a character at a place where it shouldn't  be. Basicaly if you want to read more on how JS parses the given code then  here is a good article about it: http://stackoverflow.com/questions/12719859/no-visible-cause-for-unexpected-token-illegal
Comment: width : 50px;  remove the semicolon
Comment: The error is thrown because you don't put `50px` inside quotes. Also there shouldn't be a semicolon after `width: "50px"`
Answer: Remove the semicolon and put it in a quotation (width attribute value):
  $('#fostering').on('click', function(){
     $(this).animate({
      width : "50px"
     });
    });

This error arises when you have a character at a place where it shouldn't be. Basically, if you want to read more on how JS parses the given code then here is a good article about it,
URL: No visible cause for "Unexpected token ILLEGAL"
Comment: Ah, I had forgotten to upvote your solution! Did it now. ;)


iphone maps GPS icon

Question: I would like to make a button that centers the map on the current GPS location. Google Maps app has that icon on bottom left. Where can I get that icon. Is it embedded in the SDK?
Answer: That button image is not publicly available for use in the SDK.  This question was asked recently on SO but I am unable to find the original question, perhaps someone else will be able to dig it up.  This free icon set (http://glyphish.com/) has one that is pretty close.
Comment: Thanks, that set has the icon I was looking for and more.

iphone maps GPS icon


Can I always create new instance of IHttpClientFactory even I can use instance twice or more?

Question: I wrote a WebAPI in .NET Core and used IHttpClientFactory for creating httpClients. I customized it on Startup.cs in ConfigurationServices.
services.AddHttpClient("ITSMServiceClient", m =>
            {
                m.DefaultRequestHeaders.Accept.Clear();
                m.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            }).SetHandlerLifetime(TimeSpan.FromMinutes(10))
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                var handler = new HttpClientHandler()
                {
                    AllowAutoRedirect = false,
                    UseCookies = false
                };

                // Отключаем проверку валидности http-сертификата (если необходимо)
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.ServerCertificateCustomValidationCallback =
                               (httpRequestMessage, cert, cetChain, policyErrors) => true;

                return handler;
            });

Then I use it in one dataProvider via DI.
private readonly IHttpClientFactory _clientFactory;

        public ExecuteDataProvider(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }

I use methods of this provider for all sending requests
public async Task<HttpResponseMessage> PostAsync(HttpRequestMessage request)
        {
            using (var client = _clientFactory.CreateClient("ITSMServiceClient"))
            {
                return await client.SendAsync(request);
            }
        }

And I have a question. Is it normal behavior always get new instance from _clientFactory even if I can reuse instance twice or more in code?
All my dataProvider and another entyties describe like SingleInstance in DI.
builder.RegisterType<ExecuteDataProvider>().As<IExecuteDataProvider>().SingleInstance();

Now I use it something like this:
var request = CreatePostRequest(url, parameters, jParameters, checkingToken);

HttpResponseMessage httpResponseMessage = await _executeCoreDataProvider.PostAsync(request);
if (await CheckingForUnauthorizedToken(httpResponseMessage, checkingToken))
{
        request = CreatePostRequest(url, parameters, jParameters, checkingToken);
        httpResponseMessage = await _executeCoreDataProvider.PostAsync(request);
}
response = await httpResponseMessage.Content.ReadAsStringAsync();
httpResponseMessage.Dispose();

And I worry about twice getting HttpClient. Is it normal or use one instance of client will be more correctly?
I've already read about ClientFactory on Microsoft Docs; this, and also some other sites.
Answer: In the scope of a single request, it's normal to use just one HttpClient. However, if it's easier, you can get multiple instances from the IHttpClientFactory. The HttpClient itself is just a thin wrapper, so multiple instances don't have a big impact. The important part is that these instances are coming from the IHttpClientFactory, which shares the HttpMessageHandler between multiple HttpClient instances.
The only unusual part to your code is the using statement; generally, HttpClient instances are not disposed (this is still true in the IHttpClientFactory world). But this disposal isn't bad; just a bit unusual.
Docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.1#httpclient-and-lifetime-management
Comment: Thank you Stephen! I've thought the same, but I really had to heard an opinion.
Comment: [Updated link](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-7.0#httpclient-and-lifetime-management)
"HttpClient instances can generally be treated as .NET objects **not** requiring disposal. Disposal cancels outgoing requests and guarantees the given HttpClient instance can't be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances"


Is that possible to change color of EditText `dots`?

Question: If you have an EditText with android:password equaled to true you see "dots" instead of text. I'm wondering if it possible to change color of these dots?
Answer: if you change the color of the text, the color of the dots will change
android:textColor="#FF0000" OR setTextColor(int)


Filter for one attribute (array) for one of its value (json)

Question: Having the following record
   {
      "name": "
 Festões Plástico, 12mt x 17cm - Festas Populares",
      "categories": [
        "Festas",
        "Casamentos",
        "Decorações"
      ],
      "hierarchicalCategories": {
        "lvl0": "Festas",
        "lvl1": "Festas > Casamentos",
        "lvl2": "Festas > Casamentos > Decorações"
      },
      "description": "",
      "brand": "Misterius",
      "price": 14.94,
      "stock": "Disponível",
      "prices": [
        {
          "value": 12,
          "type": "specificValue",
          "family": "fatos",
          "subfamily": "example"
        },
        {
          "value": 13,
          "type": "specificValue13",
          "family": "fatos13",
          "subfamily": "example13"
        },
        {
          "value": 14,
          "type": "specificValue14",
          "family": "fatos14",
          "subfamily": "example14"
        },
        {
          "value": 15,
          "type": "specificValue15",
          "family": "fatos15",
          "subfamily": "example15"
        },
        {
          "value": 16,
          "type": "specificValue16",
          "family": "fatos16",
          "subfamily": "example16"
        }
      ],
      "color": [
        {
          "name": "Amarelo",
          "label": "Amarelo,#FFFF00",
          "hexa": "#FFFF00"
        },
        {
          "name": "Azul",
          "label": "Azul,#0000FF",
          "hexa": "#0000FF"
        },
        {
          "name": "Branco",
          "label": "Branco,#FFFFFF",
          "hexa": "#FFFFFF"
        },
        {
          "name": "Laranja",
          "label": "Laranja,#FFA500",
          "hexa": "#FFA500"
        },
        {
          "name": "Verde Escuro",
          "label": "Verde Escuro,#006400",
          "hexa": "#006400"
        },
        {
          "name": "Vermelho",
          "label": "Vermelho,#FF0000",
          "hexa": "#FF0000"
        }
      ],
      "specialcategorie": "",
      "reference": "3546",
      "rating": 0,
      "free_shipping": false,
      "popularity": 0,
      "objectID": "30"
    }

Now by searching for "Festas Populares" will return the record and its attributes, is it possible to also filter for one attribute array as "prices" to only return one json. for example "prices.type"="specificValue14" and "family"="fatos14" and "family"="fatos" and "subfamily"="example"
{
"value": 14,
"type": "specificValue14",
"family": "fatos14",
"subfamily": "example14"
}

the record return would be:
 {
          "name": "
 Festões Plástico, 12mt x 17cm - Festas Populares",
          "categories": [
            "Festas",
            "Casamentos",
            "Decorações"
          ],
          "hierarchicalCategories": {
            "lvl0": "Festas",
            "lvl1": "Festas > Casamentos",
            "lvl2": "Festas > Casamentos > Decorações"
          },
          "description": "",
          "brand": "Misterius",
          "price": 14.94,
          "stock": "Disponível",
          "prices": [
            {
              "value": 14,
              "type": "specificValue14",
              "family": "fatos14",
              "subfamily": "example14"
            }
          ],
          "color": [
            {
              "name": "Amarelo",
              "label": "Amarelo,#FFFF00",
              "hexa": "#FFFF00"
            },
            {
              "name": "Azul",
              "label": "Azul,#0000FF",
              "hexa": "#0000FF"
            },
            {
              "name": "Branco",
              "label": "Branco,#FFFFFF",
              "hexa": "#FFFFFF"
            },
            {
              "name": "Laranja",
              "label": "Laranja,#FFA500",
              "hexa": "#FFA500"
            },
            {
              "name": "Verde Escuro",
              "label": "Verde Escuro,#006400",
              "hexa": "#006400"
            },
            {
              "name": "Vermelho",
              "label": "Vermelho,#FF0000",
              "hexa": "#FF0000"
            }
          ],
          "specialcategorie": "",
          "reference": "3546",
          "rating": 0,
          "free_shipping": false,
          "popularity": 0,
          "objectID": "30"
        }

for some context a product can have multiple prices associated, for a specific user, or one day there is campaign giving discount, etc so for that cases want to filter price associated to the product/record.
Answer: No, this is not possible with Algolia. Records are always returned with the attributes specified inside attributesToRetrieve. These attributes are returned in full.


How to select master page from database asp.net c#

Question: I saved in my database some master pages as a part of my school work.
I want to render selected master page from my database on page load event, because I am using get method in my form.
How can I render master page on page load event?
Thanks a lot.
Comment: Is it web forms, right?
Comment: yes @ricardofranca
Answer: The OnLoad Event is to late to change your MasterPage at runtime. You can change it on the Pre_Init event:
<code>    protected void Page_PreInit(object sender, EventArgs e)
{
     Page.MasterPageFile = "~/myMaster.master";
}
</code>
Edit:
Based on your comment, here a sample from Microsoft:
specifying the masterpage programaticly
Comment: I know, but I can't know which master page to render because this information is on database.
Comment: you mean how to get information from database?
Comment: no, i mean how to set master page from the database @jackjop