text:
Q: How to determine the Content-Length of a gzipped file in Python? I've a big compressed file and I want to know the size of the content without uncompress it. I've tried this:
import gzip
import os

with gzip.open(data_file) as f:
          f.seek(0, os.SEEK_END)
          size = f.tell()

but I get this error
ValueError: Seek from end not supported

How can I do that?
Thx.

A: Unfortunately, the Python 2.x gzip module doesn't appear to support any way of determining uncompressed file size.
However, gzip does store the uncompressed file size as a little-endian 32-bit unsigned integer at the very end of the file: http://www.abeel.be/content/determine-uncompressed-size-gzip-file
Unfortunately, this only works for files <4gb in size due to using only a 32-bit integer the gzip format; see the manual.
import os
import struct

with open(data_file,"rb") as f:
    f.seek(-4, os.SEEK_END)
    size, = struct.unpack("<I", f.read(4))
    print size

A: It is not possible in principle to definitively determine the size of the uncompressed data in a gzip file without decompressing it.  You do not need to have the space to store the uncompressed data -- you can discard it as you go along.  But you have to decompress it all.
If you control the source of the gzip file and can assure that a) there are no concatenated members in the gzip file, b) the uncompressed data is less than 4 GB in length, and c) there is no extraneous junk at the end of the gzip file, then and only then you can read the last four bytes of the gzip file to get a little-endian integer that has the length of the uncompressed data.
See this answer for more details.
Here is Python code to read a gzip file and print the uncompressed length, without having to store or save the uncompressed data.  It limits the memory usage to small buffers.  This requires Python 3.3 or greater:
#!/usr/local/bin/python3.4
import sys
import zlib
import warnings
f = open(sys.argv[1], "rb")
total = 0
buf = f.read(1024)
while True:             # loop through concatenated gzip streams
    z = zlib.decompressobj(15+16)
    while True:         # loop through one gzip stream
        while True:     # go through all output from one input buffer
            total += len(z.decompress(buf, 4096))
            buf = z.unconsumed_tail
            if buf == b"":
                break
        if z.eof:
            break       # end of a gzip stream found
        buf = f.read(1024)
        if buf == b"":
            warnings.warn("incomplete gzip stream")
            break
    buf = z.unused_data
    z = None
    if buf == b"":
        buf == f.read(1024)
        if buf == b"":
            break
print(total)

A: To summerize, I need to open huges compressed files (> 4GB) so the technique of Dan won't work and I want the length (number of  line) of the file so the technique of Mark Adler is not appropriate.
Eventually, I found for uncompressed files a solution( not the most optimized but it works!) which can be transposed easily to compressed files:
size = 0

with gzip.open(data_file) as f:
  for line in f:
    size+= 1
    pass

return size

Thank you all, people in this forum are very effective!


text:
Q: f:setPropertyActionListener not setting variable I have tried various different was but cannot seem to set the "selected" variable.
JavaBean:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.enterprise.context.Dependent;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;

@Named(value = "lab3")
@Dependent
@ManagedBean
@SessionScoped
public class Lab3 {

public Lab3() {
}

@Resource (name="jdbc/sample") // This is the JNDI name
private DataSource ds;

private ArrayList<Cars> c = new ArrayList<>();

public ArrayList<Cars> getC() {

    // Declare the JDBC objects.
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {

        // Establish the connection
        connection = ds.getConnection("app", "app");

        // Create and execute an SQL statement that returns some data.
        String SQL = "SELECT * FROM cars";
        statement = connection.createStatement();
        resultSet = statement.executeQuery(SQL);

        // Iterate through the data in the result set and each column
        while (resultSet.next()) {
            c.add(new Cars(resultSet.getInt("CARID"),
                    resultSet.getString("CARMAKE"),
                    resultSet.getString("CARMODEL"),
                    resultSet.getInt("CARYEAR")));
        }
    } // Handle any errors that may have occurred.
    catch (SQLException e) {
        System.out.println(Arrays.toString(e.getStackTrace()));
    }
    finally
    {
        try
        {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        }
        catch (Exception ex) {
                System.out.println ("Exception cleaning up Database objects " +
                                    ex.getMessage());
        }
    }
    return c;
}

public void setC(ArrayList<Cars> c) {
    this.c = c;
}

    private int selected;

/**
 * Get the value of selected
 *
 * @return the value of selected
 */
public int getSelected() {
    return selected;
}

/**
 * Set the value of selected
 *
 * @param selected new value of selected
 */
public void setSelected(int selected) {
    this.selected = selected;
}

private ArrayList<Mileage> m = new ArrayList<>();

public ArrayList<Mileage> getM() {

    // Declare the JDBC objects.
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {

        // Establish the connection
        connection = ds.getConnection("app", "app");

        // Create and execute an SQL statement that returns some data.
        String SQL = "SELECT * FROM mileage where mileagecarid = " + selected;
        statement = connection.createStatement();
        resultSet = statement.executeQuery(SQL);

        // Iterate through the data in the result set and each column
        while (resultSet.next()) {
            m.add(new Mileage(resultSet.getInt("MILEAGEID"),
                    resultSet.getInt("MILEAGESTART"),
                    resultSet.getInt("MILEAGEEND"),
                    resultSet.getDouble("MILEAGEGASUSED")));
        }
    } // Handle any errors that may have occurred.
    catch (SQLException e) {
        System.out.println(Arrays.toString(e.getStackTrace()));
    }
    finally
    {
        try
        {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        }
        catch (Exception ex) {
                System.out.println ("Exception cleaning up Database objects " +
                                    ex.getMessage());
        }
    }
    return m;
}

public void setM(ArrayList<Mileage> m) {
    this.m = m;
}

public String results() {
    return "carresults";
}
}

index.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Lab3</title>
    </h:head>
    <h:body>
        <h:outputStylesheet library="css" name="style.css" />
        <h:form>
            <h:dataTable id="dbresults" value="#{lab3.c}" var="row" >
                <h:column>
                    <f:facet name="header" >Make</f:facet>
                    <h:outputText value="#{row.carmake}">
                    </h:outputText>
                </h:column>
                <h:column>
                    <f:facet name="header" >Model</f:facet>
                    <h:outputText value="#{row.carmodel}">
                    </h:outputText>
                </h:column>
                <h:column>
                    <f:facet name="header" >Year</f:facet>
                    <h:outputText value="#{row.caryear}">
                    </h:outputText>
                </h:column>
                <h:column>
                    <f:facet name="header" >Details</f:facet>
                    <h:commandButton id="submit" value="Details" action="#{lab3.results}" >
                        <f:setPropertyActionListener target="#{lab3.selected}" value="#{row.carid}" />
                    </h:commandButton>
                </h:column>
            </h:dataTable>
        </h:form>
    </h:body>

carresults.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Lab3</title>
    </h:head>
    <h:body>
        <h:outputStylesheet library="css" name="style.css" />
        <h:outputText value="#{lab3.selected}" ></h:outputText>
        <h:form>
            <h:dataTable id="dbresults" value="#{lab3.m}" var="row" >
                <h:column>
                    <f:facet name="header" >Start
(km)</f:facet>
                    <h:outputText value="#{row.mileagestart}">
                    </h:outputText>
                </h:column>
                <h:column>
                    <f:facet name="header" >End
(km)</f:facet>
                    <h:outputText value="#{row.mileageend}">
                    </h:outputText>
                </h:column>
                <h:column>
                    <f:facet name="header" >Trip
(km)</f:facet>
                    <h:outputText value="#{row.trip}">
                    </h:outputText>
                </h:column>
                <h:column>
                    <f:facet name="header" >Gas Used
(L)</f:facet>
                    <h:outputText value="#{row.mileagegasused}">
                    </h:outputText>
                </h:column>
                <h:column>
                    <f:facet name="header" >Fuel Economy
(L/100km)</f:facet>
                    <h:outputText value="#{row.litre}">
                    </h:outputText>
                </h:column>
            </h:dataTable>
        </h:form>
    </h:body>

I have outputted the "selected" variable on the carresults.xhtml page and it always returns zero.

A: first you need to correct this imports and this annotations:
import javax.inject.Named;
import javax.enterprise.context.Dependent;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@Named(value = "lab3")
@Dependent
@ManagedBean
@SessionScoped

You don't need Named and ManagedBean, yous should have one or the other. ManagedBean are bean managed by JSF, Named are beans managed by CDI.
Then you need to see what is the scope you want, maybe @Dependent is wrong for what you want. You shouldn't have @SessionScoped and @Dependent at the same time, both are scopes with different lifecycles.
Try deleting @Dependent, it has a smaller scope than @SessionScoped. If you delete @ManagedBean you need to change the import of @SessionScoped, it needs to be:
import javax.enterprise.context.SessionScoped;

This import is for CDI beans, if you choose to only have:
@Named
@SessionScoped

A: Try as below
<h:commandButton id="submit" value="Details" action="#{lab3.results(row.carid)}"/>

public String results(int selected) {
    this.selected = selected;
    return "carresults";
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between loop and while true? The Rust tutorial, and now book claim there is a difference between while true and loop, but that it isn't super important to understand at this stage.

If you need an infinite loop, you may be tempted to write this:
while true {

However, Rust has a dedicated keyword, loop, to handle this case:
loop {

Rust's control-flow analysis treats this construct differently than a while true, since we know that it will always loop. The details of what that means aren't super important to understand at this stage, but in general, the more information we can give to the compiler, the better it can do with safety and code generation, so you should always prefer loop when you plan to loop infinitely.

Having done a little bit of compiler-type work, I have to wonder what possible semantic difference there is, since it would be trivial for the compiler to figure out both are an infinite loop.
So, how does the compiler treat them differently?

A: The first thing to say is, in terms of performance, these are likely to be identical. While Rust itself doesn't do anything special with while true, LLVM likely does make that optimisation. The Rust compiler tries to keep things simple by delegating optimisations to LLVM where it can.

in general, the more information we can give to the compiler, the better it can do with safety and code generation

While certain constant expressions might get optimised away by LLVM, the semantics of the language are not altered by whether an expression is constant or not. This is good, because it helps humans reason about code better too.
Just because true is a simple expression, we know it's constant. And so is true != false and [0; 1].len() == 1. But what about num_cpus::get() == 1? I actually don't know if there are some compilation targets where that could be constant, and I shouldn't have to think about it either!
The error in telotortium's example would be more significant when combined with generated code or macros. Imagine a macro which sometimes results in a simple static expression like true == true, but sometimes references a variable or calls a function. Sometimes the compiler is able to ascertain that the loop runs once, but other times it just can't. In Rust right now, the error in that example will always be an error, no matter what code was generated for that condition. No surprises.

A: This was answered on Reddit. As you said, the compiler could special-case while true, but it doesn't. Since it doesn't, the compiler doesn't semantically infer that an undeclared variable that's set inside a while true loop must always be initialized if you break out of the loop, while it does for a loop loop:

It also helps the compiler reason about the loops, for example
let x;
loop { x = 1; break; }
println!("{}", x)

is perfectly valid, while
let x;
while true { x = 1; break; }
println!("{}", x);

fails to compile with "use of possibly uninitialised variable" pointing to the x in the println. In the second case, the compiler is not detecting that the body of the loop will always run at least once.
(Of course, we could special case the construct while true to act like loop does now. I believe this is what Java does.)

A: One major difference is that loop can return a value by passing a value to break. while and for will not:
fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    assert_eq!(result, 20);
}

A:
What is the difference between loop and while true?

You could ask what is the difference between for and while? The answer will be close to: What is a programming idiom?
When you write while condition {}, you say "while condition is true, do that", but we can see that say "while true is true, do that", is redundant. This is where loop comes from, it can express infinite loops very well  because we say "loop on that". We don't have any condition, this is better.

So, how does the compiler treat them differently?

I can't answer the "how" question, but I suppose you want to know "why". It allows the compiler to know that this loop will run at least one time, like the do {} while (condition); from C. The compiler can use this information to produce better code or warnings. Plus, you will be certain that the loop will be executed where a while loop could be gone because the compiler optimize it away. The fun part is that internally Rust uses LLVM, and it looks like LLVM doesn't have a way to express infinite loop, so it produces bugs in some cases.


text:
Q: Is there an #IF DEBUG for Asp.net markup? Can I do something like this in the markup of an asp.net page, based off the "Define DEBUG constant" setting?
#IF (DEBUG) THEN
  <asp:TextBox ID="TextBox1" runat="server">You're in debug mode</asp:TextBox>
#END IF

A: <form runat="server">
 <% #if DEBUG %>
 <asp:TextBox ID="TextBox1" runat="server">You're in debug mode</asp:TextBox>
 <% #else %>
 <asp:TextBox ID="TextBox2" runat="server">Mmm... No, I think you're not in debug mode</asp:TextBox>
 <% #endif %>
</form>

Note that you cannot assign the same ID for those text boxes.
Also note that DEBUG is true when it is set so in web.config:
<compilation debug="true">

A: The close as I can get is:
<asp:Literal id="isDebug" runat="server" />
<script runat="server">
    void Page_Load()
    {
#if DEBUG
        isDebug.Text = "You're in debug mode";
#endif
    }
</script>

This would give you problems if you wanted to have anything else in your Page_Load() event; the literal code above only works if the page/control has no code behind.
If I needed to do this, I would encapuslate the above code into a user control and include that control in the pages of interest.
My test user control looks like this:
<%@ Control Language="C#" AutoEventWireup="true"  %>
<asp:Literal id="isDebug" runat="server" />
<script runat="server">
    void Page_Load()
    {
#if DEBUG
        isDebug.Text = "You're in debug mode";
#endif
    }
</script>

A: If you are trying to step through javascript or prefer to minify javascript when not debugging, I prefer this approach:
<% if (Debugger.IsAttached) { %>

  <script src="jquery.js"></script>

<% } else { %>

  <script src="jquery.min.js"></script>

<% } %>

I can easily step through code when I am debugging, otherwise I want the scripts to be minified. Be sure to include the following import:
<%@ Import Namespace="System.Diagnostics" %>

Moreover, it is nice to use the Web Essentials visual studio extension to bundle/minify your javascript files so that there is only one request made to the server for your scripts.

A: How about using a Literal and then using #if DEBUG in your code-behind to inject html for your textbox into the literal? Also there are direct code blocks in ASP.NET but I don't know if they deal with #if statements; those seem to be reserved for the C# compiler.

A: It would be easy enough to roll your own.  You might miss some of the cooler non-compiling features of Compilation Constants but you'd definitely have the ability to add markup based on a global parameter of some sort.


text:
Q: Failed to start appium: TypeError When i try to start an appium session i always get the following Error:
error: Unhandled error: TypeError: Path must be a string. Received null
    at assertPath (path.js:9:11)
    at Object.posix.resolve (path.js:427:5)
    at [object Object].<anonymous> (/usr/local/lib/node_modules/appium/lib/devices/android/android-common.js:686:29)
    at /usr/local/lib/node_modules/appium/node_modules/appium-adb/lib/adb.js:277:7
    at ChildProcess.exithandler (child_process.js:205:7)
    at emitTwo (events.js:88:13)
    at ChildProcess.emit (events.js:173:7)
    at maybeClose (internal/child_process.js:819:16)
    at Socket.<anonymous> (internal/child_process.js:320:11)
    at emitOne (events.js:78:13)
    at Socket.emit (events.js:170:7)
    at Pipe._onclose (net.js:470:12) context: [POST /wd/hub/session {"desiredCapabilities":{"app":"/Users/user/Documents/app.apk","appPackage":"package","appium-version":"1.0","platformVersion":"5.1","automationName":"Appium"]

Here is my Java code:
DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("appium-version", "1.0");
        capabilities.setCapability("automationName", "Appium");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("platformVersion", "5.1");
        capabilities.setCapability("deviceName", "device");
        capabilities.setCapability("app", "/Users/user/Documents/app.apk");
        capabilities.setCapability("appPackage", "package");
        WebDriver wd = new AndroidDriver(new URL("http://127.0.0.1:4444/wd/hub"), capabilities);
        wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        wd.close();

I am starting the appium server only with the port 4444.
I cant find a solution to this error.

A: i found the solution, ANDROID_HOME was not set.


text:
Q: How Storage API can be used to get Azure Classic VM metrics? Can we collect metrics for Azure Classic VM using Storage API or is there any other way to get the metrics for Azure Classic VM please suggest.

A: To get the Azure VM metrics from a Azure Storage Service, you need to enable Diagnostics and configure the Storage Account on Azure portal.

After that, you will find that multi tables will be created to store the metrics.

The tables are with the following naming conventions:

*

*WADMetrics : Standard prefix for all WADMetrics tables

*PT1H or PT1M : Signifies that the table contains aggregate data over 1 hour or 1 minute

*P10D : Signifies the table will contain data for 10 days from when the table started collecting data

*V2S : String constant

*yyyymmdd : The date at which the table started collecting data

Each WADMetrics table will contain the following columns:

*

*PartitionKey: The partitionkey is constructed based on the resourceID value to uniquely identify the VM resource. for e.g. : - 002Fsubscriptions::002FresourceGroups:002F:002Fproviders:002FMicrosoft:002ECompute:002FvirtualMachines:002F

*RowKey : Follows the format :. The descending time tick calculation is max time ticks minus the time of the beginning of the aggregation period. E.g. if the sample period started on 10-Nov-2015 and 00:00Hrs UTC then the calculation would be: DateTime.MaxValue.Ticks - (new DateTime(2015,11,10,0,0,0,DateTimeKind.Utc).Ticks). For the memory available bytes performance counter the row key will look like: 2519551871999999999__:005CMemory:005CAvailable:0020Bytes

*CounterName : Is the name of the performance counter. This matches the counterSpecifier defined in the xml config.

*Maximum : The maximum value of the performance counter over the aggregation period.

*Minimum : The minimum value of the performance counter over the aggregation period.

*Total : The sum of all values of the performance counter reported over the aggregation period.

*Count : The total number of values reported for the performance counter.

*Average : The average (total/count) value of the performance counter over the aggregation period.

To read the data from Azure Table, you could use Azure Table client library or Azure Table REST API.
Get started with Azure Table storage using .NET
Table Service REST API
Update 2017/07/18

my doubt is 20170709 is start date and 20170719 is end date am i right?

Yes, you are right.

Doubt 2.To access this table i need to create a POJO so how can i get the schema of the table meaning if maximum/minimum/Average is int/long/double/float

You can open a entity of the table from Azure Storage Explorer. You will see the type of the columns. For example,

Doubt 3. how to query WADMetricsPT1HP10DV2S20170709 to get metrics for one particular hour?

You could query the data by Timestamp.

A:
Can we collect metrics for Azure Classic VM using Storage API

By collect metrics, if you mean the process of capturing the metrics data then the answer is no. You can't use Storage API to do that. You would need  to use the Metrics API for that purpose. Data collected by this API will store the data in Azure Storage.
Once the data is in Azure Storage, then you can use Storage API to get that data. Depending on where the data is stored (Blobs and/or Tables), you would use appropriate parts of Storage API to fetch and manage that data.


text:
Q: How to count the numbers of rows based on an id column that have shifted from one category to another (in order)? I have a pandas dataframe like this:
         id    year_group  category
0        8300           1     low
1        8300           2     medium
2       11725           1     low
3       11725           2     low
4       18068           1     medium
...       ...         ...       ...
59354   18962           1     low
59355   11669           1     low
59356   13110           3     low
59357    2378           1     low
59358   19363           1     low

[59359 rows x 3 columns]

I'm trying to determine how many ids shifted from one category to another based on a year (year_group column). For example, for id 8300, a shift from year 1 to year 2 shows a category change from low to medium (in that order). I want to count the number of times this happens between year_groups 1 to 3, for each category.
I'm not sure how to complete this. At the moment I have considered dropping each year_group and making separate data frames before trying to group everything, like this:
# year 1 and 2
years_1_2  = df.drop(df[df.year_group == 3].index)

However, I don't know how to make sure the grouping is based on positions of the year_groups, i.e. year 1 going to year 2 and not year 2 going to year 1.
Maybe there is something more streamlined that I can do. Perhaps making use of np.where... Any suggestions on how best to tackle this problem?

A: Maybe this can get you started. It's a bit verbose, but clear, I believe.
Comments in line
# added and modified data for just 2 years
data='''         id    year_group  category
0        8300           1     low
1        8300           2     medium
2       11725           1     low
3       11725           2     low
4       18068           1     medium
5       18068           2     low
6   18962           1     low
7   18962           2     low
8        21           1     low
9        21           2     medium'''
df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python')

# sort to keep ids and year_groups ascending
df.sort_values(['id', 'year_group'], ascending=[True, True], inplace=True)

      id  year_group category
8     21           1      low
9     21           2   medium
0   8300           1      low
1   8300           2   medium
2  11725           1      low
3  11725           2      low
4  18068           1   medium
5  18068           2      low
6  18962           1      low
7  18962           2      low

# if you have year 3, this will only take years 1 and 2
# if a grouping has a count of 2, that means there is no change from one year to the next, so drop everything that didn't change
dft = df[df[df['year_group'] != 3].groupby(['id', 'category'])['year_group'].transform('count') < 2]

      id  year_group category
8     21           1      low
9     21           2   medium
0   8300           1      low
1   8300           2   medium
4  18068           1   medium
5  18068           2      low

# making lists that show movement from low - medium, medium - low, etc...
yearlychanges = dft.groupby('id')['category'].apply(list).reset_index()

      id       category
0     21  [low, medium]
1   8300  [low, medium]
2  18068  [medium, low]

# convert lists to strings for counting
yearlychanges['changes'] = yearlychanges.apply(lambda x: '-'.join(x['category']), axis=1)

      id       category     changes
0     21  [low, medium]  low-medium
1   8300  [low, medium]  low-medium
2  18068  [medium, low]  medium-low

# count number of changes
yearlychanges[['changes', 'id']].groupby('changes').count()

            id
changes
low-medium   2
medium-low   1

A: If I understood you correctly:
Setup
df = pd.DataFrame(data={{'id': [8300, 8300, 8300, 8301, 8301, 8301], 'year_group': [1, 2, 3, 1, 2, 3], 'category': ['low', 'medium', 'low', 'low', 'medium', 'low']}})

Code
df['shift'] = df.groupby('id')['category'].apply(lambda x: x + ' ' + x.shift(-1))
shifts = df.dropna(subset=['shift']).groupby(['shift']).size()

Input
         id  year_group category
0      8300           1      low
1      8300           2   medium
2      8300           3      low
59355  8301           1      low
59356  8301           2   medium
59357  8301           3      low

Output:
shift
low medium    2
medium low    2


text:
Q: Cannot start MySQL on windows box with named pipes I've installed MySQL server on Windows although in the configuration have selected to not run MySQL as a server and have disabled TCP/IP access so only named pipes can be used, I'm now having problems getting the server running. Below is the output, after trying to start in standalone mode. Can anybody who knows a thing or two about MySQL make any suggestions on how I can get this running?
Thanks.
C:\Program Files\MySQL\MySQL Server 5.5\bin>mysqld --standalone --console
110723  9:09:54 [Note] Plugin 'FEDERATED' is disabled.
110723  9:09:54 InnoDB: The InnoDB memory heap is disabled
110723  9:09:54 InnoDB: Mutexes and rw_locks use Windows interlocked functions
110723  9:09:54 InnoDB: Compressed tables use zlib 1.2.3
110723  9:09:54 InnoDB: Initializing buffer pool, size = 107.0M
110723  9:09:54 InnoDB: Completed initialization of buffer pool
InnoDB: The first specified data file D:\Work\MySQLDB\ibdata1 did not exist:
InnoDB: a new database to be created!
110723  9:09:54  InnoDB: Setting file D:\Work\MySQLDB\ibdata1 size to 10 MB
InnoDB: Database physically writes the file full: wait...
InnoDB: Error: log file .\ib_logfile0 is of different size 0 359661568 bytes
InnoDB: than specified in the .cnf file 0 56623104 bytes!
110723  9:09:54 [ERROR] Plugin 'InnoDB' init function returned error.
110723  9:09:54 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
110723  9:09:54 [ERROR] Unknown/unsupported storage engine: INNODB
110723  9:09:54 [ERROR] Aborting

110723  9:09:54 [Note] mysqld: Shutdown complete

A: InnoDB: The first specified data file D:\Work\MySQLDB\ibdata1 did not exist:
InnoDB: a new database to be created!
110723  9:09:54  InnoDB: Setting file D:\Work\MySQLDB\ibdata1 size to 10 MB
InnoDB: Database physically writes the file full: wait...
InnoDB: Error: log file .\ib_logfile0 is of different size 0 359661568 bytes
InnoDB: than specified in the .cnf file 0 56623104 bytes!

What looks out of place here is the complaint about ib_logfile0 being a different size. That will definitely take out InnoDB.
At the DOS Command Line, run this:
del D:\Work\MySQLDB\ib_logfile*

Restart mysqld and ib_logfile0 and ib_logfile1 should be rebuilt with the proper size.
Give it a Try !!!


text:
Q: unicode string formatting I just saw this in a piece of uncommented code.  Is there ever a reason to do this?
 new_var = u'%s' % (child.tag)

where child is an instance and tag is an attribute of that instance?  It seems like this does it more simply:
 new_var = unicode(child.tag)

A: They are identical, and it's just a matter of preference.  In terms of the Zen of Python and such, there's really not a "better" way as both are explicit in that they are getting a unicode representation of child.tag.  Mechanically they do the same thing:
>>> class foo(object):
    def __init__(self, val):
        self.val = val

    def __str__(self):
        return "str: %s" % self.val
    def __unicode__(self):
        return "unicode: %s" % self.val

>>> f = foo("bar")
>>> u'%s' % f
u'unicode: bar'
>>> unicode(f)
u'unicode: bar'
>>> '%s' % f
'str: bar'

A: One reason for this could be either that the code used to contain a literal string which had to be translated (then %s is a useful placeholder), or is expected to contain a literal at some later point.

A: They should produce the same results.  I think the 'u' prefix character wasn't added until Python 2.5 and the unicode() function was there prior to that, and now.  Also, if you need to specify the encoding type, unicode() will let you do that.


text:
Q: bootstrap 3 modal footer align buttons on both edges How can I align buttons in modal's footer so they are on both sides of modal ? Default behaviour sets all buttons near right edge, but I need close button on right and another buttons on left.

A: You can add class pull-left to the buttons which you want to align to left.
In the below sample, close button will be aligned to right and other buttons aligned to left.
Sample footer code:

    <button type="button" class="btn btn-primary pull-left" style="">Save changes</button>
    <button type="button" class="btn btn-primary pull-left" style="">Save changes1</button>
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Example:

$(function () {
 $(".btn").click(function () {
  $("#myModal").modal('show');
 });
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />

Launch Demo Modal

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Confirmation

Do you want to save changes you made to document before closing?

     If you don't save, your changes will be lost.

    <button type="button" class="btn btn-primary pull-left">Save changes</button>
    <button type="button" class="btn btn-primary pull-left">Save changes</button>
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: Similar to Phani's answer but now visualized and using non-inline CSS classes.

 $('#myModal').modal('show');
.modal .modal-footer button {
  float:left;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: Convert recursion to tail recursion I have a question about how to convert 'recursion' to 'tail recursion'.
This is not a homework, just a question that popped up when I tried to polish the recursion theorem from a book on algorithms.
I am familiar with the 2 typical examples of using recursion (factorial and Fibonacci sequence), and also know how to implement them in a recursive way and tail-recursive way.
My code is as below (I use Perl just to make it simple, but can be easily converted to C/Java/C++).
# This is the recursive function
sub recP {
    my ($n) = @_;
    if ($n == 0 or $n == 1 or $n == 2) {
        return 1;
    } else {
        return (recP($n-3) * recP($n-1)) + 1;
    }
}

for my $k (1 .. 10) {
    print "recP($k) = ", recP($k), "\n";
}

When running the code, the output as below:
recP(1) = 1
recP(2) = 1
recP(3) = 2
recP(4) = 3
recP(5) = 4
recP(6) = 9
recP(7) = 28
recP(8) = 113
recP(9) = 1018

The recursive function invokes itself twice with different parameters before return.
I've tried several ways to convert this to a tail recursive function but all turned out to be wrong.
Can anybody take a look at the code and show me the correct way to make it tail-recursive? Especially I believe there is a routine for the conversion for this tree recursion (invoke recursive function multiple times before return), can anyone shed some light on this? So I can use the same logic to handle different questions later.

A: Using google, I found this page that describes Tail Recursion. Basically, you need to split the function into at least two other functions: one that does the work, keeping an "accumulation" of the current value, and another that is a driver for your workhouse function. The factorial example in C is below:
/* not tail recursive */
unsigned int
factorial1(unsigned int n)
{
    if(n == 0)
        return 1;
    return n * factorial1(n-1);
}

/* tail recursive version */
unsigned int
factorial_driver(unsigned int n, unsigned int acc)
{
    if(n == 0)
        return acc;

    /* notice that the multiplication happens in the function call */
    return factorial_driver(n - 1, n * acc);
}

/* driver function for tail recursive factorial */
unsigned int
factorial2(unsigned int n)
{
    return factorial_driver(n, 1);
}

A: @Alexey Frunze's answer is okay but not precisely right.  It is indeed possible to convert any program into one where all recursion is tail recursion by transforming it into Continuation Passing Style.
I don't have time right now but will try to re-implement your program in CPS if I get some minutes.

A: Although you often see the following as an example of converting factorial to tail-call:
int factorial(int n, int acc=1) {
  if (n <= 1) return acc;
  else        return factorial(n-1, n*acc);
}

it's not quite correct, since it requires multiplication to be both associative and commutative. (Multiplication is associative and commutative, but the above doesn't serve as a model for other operations which don't satisfy those constraints.) A better solution might be:
int factorial(int n, int k=1, int acc=1) {
  if (n == 0) return acc;
  else        return factorial(n-1, k+1, acc*k);
}

This also serves as a model for the fibonacci transform:
int fibonacci(int n, int a=1, int b=0) {
  if (n == 0) return a;
  else        return fibonacci(n-1, a+b, a);
}

Note that these compute the sequence starting at the beginning, as opposed to queueing pending continuations in a call stack. So they are structurally more like the iterative solution than the recursive solution. Unlike the iterative program, though, they never modify any variable; all bindings are constant. This is an interesting and useful property; in these simple cases it doesn't make much difference, but writing code without reassignments makes some compiler optimizations easier.
Anyway, the last one does provide a model for your recursive function; like the fibonacci sequence, we need to keep the relevant past values, but we need three of them instead of two:
int mouse(int n, int a=1, int b=1, int c=1) {
  if (n <=2 ) return a;
  else        return mouse(n-1, a*c+1, a, b);
}

Addenda
In comments, two questions were raised. I'll try to answer them (and one more) here.
First, it should be clear (from a consideration of the underlying machine architecture which has no concept of function calling) that any function call can be rephrased as a goto (possibly with non-bounded intermediate storage); furthermore, any goto can be expressed as a tail-call. So it is possible (but not necessarily pretty) to rewrite any recursion as tail-recursion.
The usual mechanism is "continuation-passing style" which is a fancy way of saying that every time you want to call a function, you instead package the rest of the current function as a new function (the "continuation"), and pass that continuation to the called function. Since every function then receives a continuation as an argument, it has to finish any continuation it creates with a call to the continuation it received.
That's probably enough to make your head spin, so I'll put it another way: instead of pushing arguments and a return location onto the stack and calling a function (which will later return), you push arguments and a continuation location onto the stack and goto a function, which will later goto the continuation location. In short, you simply make the stack an explicit parameter, and then you never need to return. This style of programming is common in event-driven code (see Python Twisted), and it's a real pain to write (and read). So I strongly recommend letting compilers do this transformation for you, if you can find one which will do that.
@xxmouse suggested that I pulled the recursion equation out of a hat, and asked how it was derived. It's simply the original recursion, but reformulated as a transformation of a single tuple:

       fn = fn-1*fn-3 + 1
    =>
       Fn = <Fn-11*Fn-13+1, Fn-11, Fn-12>
I don't know if that's any clearer, but it's the best I can do. Look at the fibonacci example for a slightly simpler case.
@j_random_hacker asks what the limits on this transformation are. It works for a recursive sequence where each element can be expressed by some formula of the previous k elements, where k is a constant. There are other ways to produce a tail-call recursion. For example:
// For didactic purposes only
bool is_odd(int n) { return n%2 == 1; }

int power(int x, int n, int acc=1) {
  if (n == 0)         return acc;
  else if (is_odd(n)) return power(x, n-1, acc*x);
  else                return power(x*x, n/2, acc);
}

The above is not the same as the usual non-tail-call recursion, which does a different (but equivalent and equally long) sequence of multiplications.
int squared(n) { return n * n; }

int power(int x, int n) {
  if (n == 0)         return 1;
  else if (is_odd(n)) return x * power(x, n-1));
  else                return squared(power(x, n/2));
}

Thanks to Alexey Frunze for the following test:
Output (ideone):
mouse(0) = 1
mouse(1) = 1
mouse(2) = 1
mouse(3) = 2
mouse(4) = 3
mouse(5) = 4
mouse(6) = 9
mouse(7) = 28
mouse(8) = 113
mouse(9) = 1018

A: You could do something like this:
#include <stdio.h>

void fr(int n, int a[])
{
  int tmp;

  if (n == 0)
    return;

  tmp = a[0] * a[2] + 1;
  a[2] = a[1];
  a[1] = a[0];
  a[0] = tmp;

  fr(n - 1, a);
}

int f(int n)
{
  int a[3] = { 1, 1, 1 };

  if (n <= 2)
    return 1;

  fr(n - 2, a);

  return a[0];
}

int main(void)
{
  int k;
  for (k = 0; k < 10; k++)
    printf("f(%d) = %d\n", k, f(k));
  return 0;
}

Output (ideone):
f(0) = 1
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 3
f(5) = 4
f(6) = 9
f(7) = 28
f(8) = 113
f(9) = 1018

The compiler may transform fr() into something like this:
void fr(int n, int a[])
{
  int tmp;

label:

  if (n == 0)
    return;

  tmp = a[0] * a[2] + 1;
  a[2] = a[1];
  a[1] = a[0];
  a[0] = tmp;

  n--;

  goto label;
}

And that would be tail-call optimization.

A: The problem is that the last operation is not one of the recursive calls, but the addition of 1 to the multiplication. Your function in C:
unsigned faa (int n)  // Ordinary recursion
{
    return n<3 ? 1 :
                 faa(n-3)*faa(n-1) + 1;  // Call, call, multiply, add
}

If you change the order in which the values are requested, you can turn one of the calls into a loop:
unsigned foo (int n)  // Similar to tail recursion
{                     // (reverse order)
    int i;
    unsigned f;

    for (i=3, f=1; i<=n; i++)
        f = f*foo(i-3) + 1;

    return f;
}

The key is thinking about the order in which values are actually computed in the original function, instead of the order in which they are requested.
Note that I am assuming that you want to remove one recursive call. If you want to write the recursive call at the end of the function expecting the compiler to optimize it away for you, see the other answers.
Though, "The Right Thing(TM)" to do here is to use dynamic programming to avoid computing the same values many times:
unsigned fuu (int n)  // Dynamic programming
{
    int i;
    unsigned A[4]={1,1,1,1};

    for (i=3; i<=n; i++)
    {
        memmove (A+1, A, 3*sizeof(int));
        A[0] = A[1]*A[3] + 1;
    }

    return A[0];
}

The array A contains a sliding window of the sequence: A[0]==f(i), A[1]==f(i-1), A[2]==f(i-2) and so on.
The memmove might have been written as:
        A[3] = A[2];
        A[2] = A[1];
        A[1] = A[0];


text:
Q: Grouping QuerySet in Django Having scheme like this:
class Model1(models.Model):
    pass

class Model2(models.Model):
    model1 = models.ForeignKey(Model1)
    date = models.DateField()

class Model3(models.Model):
    model2 = models.ForeignKey(Model2)

I need to query Model3 having unique model2__model1__id and the least model2__date.
I've managed to make required query using QuerySet.extra() method, like this:
Model3.objects.order_by('model2__date').extra(select={'m1_id': 'DISTINCT `app_model2`.`model1_id`'})

But I'm afraid it won't work with additional sortings etc.
I also don't want to use raw queries as those don't support sorting as well, and also database-level slicing (there could be huge amounts of records).
Is there more correct way to do what I'm trying to achieve?
UP:
I am using MySQL DB backend, so distinct() with field names is not available

A: I know you can do the following
Model3.objects.order_by('model2__model1_id', 'model2__date').distinct('model2__model1_id')

Unfortunately it's not sorted by model2.date, but for each model1.id the model2.date is the least, and it's sorted by model1 id

A: I've found the solution: module django-group-by allows to apply grouping to querysets, like this:
Model3.objects.group_by('model2__model1')

(You need to mix GroupByMixin into the model manager)


text:
Q: Big FFT amplitude difference between the existing (synthesized) signal and the filtered signal I think, what amplitude in the noised regions on the FFT-plot of the filtered signal should be lower, then now. Probably, small numeric deviations/errors presented in the scipy.fftpack.lfilter().
I tried to add noise to the existing signal, but no result.
Why FFT-amplitude of the filtered signal (green) in the noise regions are so high?

Update:
300 dB of an FFT-amplitude are non-physical - it's clear, it's due to 64bit float in the Python-environment.
FFT of the filtered signal (green) has so low dB (as ~67 dB) due to ~4000 samples at all signal (not 'per second' as on the picture, little mistake, not critical), sample rate = 200 samples/sec. 1 frequency bin=200/4000/2=0.025Hz, 2000 bins shown.
If we take a longer signal, we get a more frequency resolution per bin (i.e. 40 000samples, 1 freq bin = 200/40 000/2 = 0.0025 Hz). And also we get FFT of a filtered signal ~87 dB.
(Numbers 67 dB and 87 dB seems to be non-physical, because of an initial signal SNR 300dB, but I try to add some noise to the existing signal and get the same numbers)
If you want to get a picture of a non-depend FFT to the number of samples in a signal, you should use a windowed FFT and slide window to compute a whole-signal-FFT.
'''
Created on 13.02.2013, python 2.7.3

@author:
'''
from numpy.random import normal
from numpy import sin, pi, absolute, arange, round
#from numpy.fft import fft
from scipy.fftpack import fft, ifft
from scipy.signal import kaiserord, firwin, lfilter, freqz
from pylab import figure, clf, plot, xlabel, ylabel, xlim, ylim, title, grid, axis, show, log10,\
                  subplots_adjust, subplot

def filter_apply(filename):
    pass

def sin_generator(freq_hz = 1000, sample_rate = 8000, amplitude = 1.0, time_s = 1):
    nsamples = round(sample_rate * time_s)
    t = arange(nsamples) / float(sample_rate.__float__())
    signal = amplitude * sin(2*pi*freq_hz.__float__()*t)
    return signal, nsamples

def do_fir(signal, sample_rate):
    return signal

#-----------------make a signal---------------
freq_hz = 10.0
sample_rate = 400
amplitude = 1.0
time_s = 10
a1, nsamples = sin_generator(freq_hz, sample_rate, amplitude, time_s)
a2, nsamples = sin_generator(50.0, sample_rate, 0.5*amplitude, time_s)
a3, nsamples = sin_generator(150.0, sample_rate, 0.5*amplitude, time_s)
mu, sigma = 0, 0.1 # mean and standard deviation
noise = normal(mu, sigma, nsamples)
signal = a1 + a2 + a3 # + noise

#----------------create low-pass FIR----
# The Nyquist rate of the signal.
nyq_rate = sample_rate / 2.0
# The desired width of the transition from pass to stop,
# relative to the Nyquist rate.  We'll design the filter
# with a 5 Hz transition width.
width = 5.0/nyq_rate

# The desired attenuation in the stop band, in dB.
ripple_db = 60.0

# Compute the order and Kaiser parameter for the FIR filter.
N, beta = kaiserord(ripple_db, width)
print 'N = ',N, 'beta = kaiser param = ', beta

# The cutoff frequency of the filter.
cutoff_hz = 30.0

# Use firwin with a Kaiser window to create a lowpass FIR filter.
# Length of the filter (number of coefficients, i.e. the filter order + 1)
taps = firwin(N, cutoff_hz/nyq_rate, window=('kaiser', beta))

# Use lfilter to filter x with the FIR filter.
filtered_signal = lfilter(taps, 1.0, signal)

#----------------plot signal----------------------
hh,ww=2,2
figure(figsize=(12,9))
subplots_adjust(hspace=.5)
#figure(1)
subplot(hh,ww,1)

# existing signal
x = arange(nsamples) / float(sample_rate)

# The phase delay of the filtered signal.
delay = 0.5 * (N-1) / sample_rate

# original signal
plot(x, signal, '-bo' , linewidth=2)

# filtered signal shifted to compensate for
# the phase delay.
plot(x-delay, filtered_signal, 'r-' , linewidth=1)

# Plot just the "good" part of the filtered signal.
# The first N-1 samples are "corrupted" by the
# initial conditions.
plot(x[N-1:]-delay, filtered_signal[N-1:], 'g', linewidth=2)

xlabel('time (s)')
ylabel('amplitude')
axis([0, 1.0/freq_hz*2, -(amplitude*1.5),amplitude*1.5]) # two periods of freq_hz
title('Signal (%d samples)' % nsamples)
grid(True)

#-------------- FFT of the signal
subplot(hh,ww,2)

signal_fft=fft(signal)
filtered_fft =fft(filtered_signal[N-1:])

# existing signal
y = 20*log10( ( abs( signal_fft/nsamples )*2.0)/max( abs( signal_fft/nsamples )*2.0) )# dB Amplitude
x = arange(nsamples)/float(nsamples)*float(sample_rate)

# filtered signal
y_filtered = 20*log10( (abs(filtered_fft/ (nsamples - N + 1) )*2.0)/max(abs(signal_fft/ (nsamples - N + 1) )*2.0) )# dB Amplitude
x_filtered = arange(nsamples - N + 1)/float(nsamples - N + 1)*float(sample_rate)
yy = fft(ifft(filtered_fft))

plot(x,y, linewidth=1)
plot(x_filtered, y_filtered, 'g', linewidth=2)
xlim(0, sample_rate/2) # compensation of mirror (FFT imaginary part)
xlabel('freq (Hz)')
ylabel('amplitude, (dB)')
title('Signal (%d samples)' % nsamples)
grid(True)

#--------------FIR ampitude response
subplot(hh,ww,3)

w, h = freqz(taps, worN=8000)
#plot((w/pi)*nyq_rate, absolute(h), linewidth=2)
plot((w/pi)*nyq_rate, 20*log10(absolute(h)/1.0),'r', linewidth=1)
xlabel('Frequency (Hz)')
#ylabel('Gain -blue')
ylabel('Gain (dB)')
title('Frequency Response')
#ylim(-0.05, 1.05)
grid(True)

#--------------FIR coeffs
subplot(hh,ww,4)
plot(taps, 'bo-', linewidth=2)
title('Filter Coefficients (%d taps)' % N)
grid(True)

show()

A: I think you -300dB of noise is pretty low. Keep in mind the this is a log scale, so we are talking about a couple of digits at 64bit resolution.
Using double precision float (64bit) you won't get any lower.


text:
Q: Do we need to add indicate the amount for thunder when he was going to tell you the thunder just struck? It was raining heavily.
Suddenly a thunder struck.
My son went to me and said he was scared.
"What's happened?" I said.

"It's thunder."
"It's a thunder."

Do we need to add indicate the amount for thunder when he was going to tell you the thunder just struck?

A: No, "a thunder" is never used because "thunder" is only used to mean a plural. You could say "a clap of thunder" or " the noise of thunder" but not just "a thunder".
By the way "what's happened" is grammatical but unnatural sounding. Normally people just say "what happened".


text:
Q: Detecting Seasonality in R Problem: Detecting cyclical patterns in daily data using periodogram and FFT in R.
The issue is how to code in R the periodogram to detect monthly, quarterly, semi-annual, annual..etc cyclical patterns in the data. In other words I need to detect the existence of cyclical patterns for low frequencies ( ie: 1 year=> 2*pi/365, 6 months = > 4*pi/365, etc)
Reproducible Example:
 library(weatherData)
 w2009=getWeatherForYear("sfo",2009)
 w2010=getWeatherForYear("sfo",2010)
 w2011=getWeatherForYear("sfo",2011)
 w2012=getWeatherForYear("sfo",2012)
 w2013=getWeatherForYear("sfo",2013)
 w2014=getWeatherForYear("sfo",2014)
 w=rbind(w2009,w2010); w=rbind(w,w2011); w=rbind(w,w2012)
 w=rbind(w,w2013); w=rbind(w,w2014)

 # Next we analyze the periodograms
 # This is IMAGE 1
 TSA::periodogram(w$Max_TemperatureF)
 # Next: I dont really know to use this information
 GeneCycle::periodogram(w$Max_TemperatureF)
 # Next THIS IS IMAGE 2
 stats::spectrum(w$Max_TemperatureF)
 # I also tried . This is IMAGE 3
 f.data <- GeneCycle::periodogram(tmax)
 harmonics <- 1:365
 plot(f.data$freq[harmonics]*length(tmax),]
      f.data$spec[harmonics]/sum(f.data$spec),
      xlab="Harmonics (Hz)", ylab="Amplitute Density", type="h")

After reading the answers, I did:
 per <- TSA::periodogram(w$Max_TemperatureF,lwd = 1)
 x <- which(per$freq < 0.01)
 plot(x = per$freq[x], y = per$spec[x], type="s")

My question is what does it all mean? Do we have a seasonality cycle?

A: If you are looking for a long periods (365 days) you will find it under very low frequency
> 1/365
[1] 0.002739726

You can actually see a peak on the left of your first image at this value. Filter to lower frequencies if you want to zoom-in:
per <- TSA::periodogram(w$Max_TemperatureF,lwd = 1)
x <- which(per$freq < 0.01)
plot(x = per$freq[x], y = per$spec[x], type="s")

Another way to search for periodicity is auto-correlation estimation (acf):
acf(w$Max_TemperatureF, lag.max = 365*3)

See also seasonal decomposition:
ts1 <- ts(data = w$Max_TemperatureF, frequency = 365)
plot( stl(ts1, s.window = "periodic"))


text:
Q: What kind of coordinate notation is this? I've tried searching the web and a lot of questions here to find out which coordinate system this is:
[ 4.402223, 51.228429 ]
It should be near Antwerpen.
Does anyone recognise what coordinate system it is?


text:
Q: Calling a method with parameters within another method located in a superclass I was wondering how I could call getJD() within getToD and keep the parameters intact,(or temporarily set the parameters as variables in main and call the variables to the method).
The parameters are going to be input using the scanner class later in the main method.
    import static java.lang.Math.*;
public class jdMethods
{
    public static double getJD(double y, double m, double d){
        if (m<=2.0){
            y--;
            m += 12.0;
        }
        double a=floor(y/100.0);
        return (365.25*(y+4716.0))+(30.6001*(m+1))+d+(2.0-a+floor(a/4.0))-1524.5;
    }

    public static double getToD(int h, int m, int s)
    {
        double a = getJD(a, a, a) + ((h-12)/24) + (m/1440) + (s/86400);
        return a;
    }
}

Edited for clarity.

A: All those parameters will be intact since you are using double and int, those are not Object s so it's value is copied when passed to a function, unlike Object s that a reference to it is passed to the function.
About your code, undefined variable a won't let it compile:
double a = getJD( a, a, a ) + ((h-12)/24) + (m/1440) + (s/86400);
I don't get what you are trying to do there, remember that a from getJD method is not the same a into getToD.

A: It's not perfectly clear on what you are trying to do, but I assumed that you just want to save the result of your first getJD() and to use the result within your getToD(), so I made a private _jd and created a setter and getter for it.
import static java.lang.Math.*;

public class jdMethods
{

    private double _jd;
    public double getJD(){
        return _jd;
    }

    public void setJD(double y, double m, double d){
        if (m<=2.0){
            y--;
            m += 12.0;
        }
        double a=floor(y/100.0);
        _jd = (365.25*(y+4716.0))+(30.6001*(m+1))+d+(2.0-a+floor(a/4.0))-1524.5;
    }

    public double getToD(int h, int m, int s)
    {
        double a = getJD() + ((h-12)/24) + (m/1440) + (s/86400);
        return a;
    }
}

So here is how you call it:
jdMethods testRun = new jdMethods();
testRun.setJD(1,2,3);
System.out.println(testRun.getToD(3, 2, 1));


text:
Q: How to make an element no larger than the enclosing element?

blah

#outer has a fixed, predefined size. I want #inner to always be within #outer (and if #inner's content is too large then to make it scrollable).
"Solution":
#inner {
    width: 100%;
    height: 100%;
    overflow: scroll;
}

THis solution is wrong since it makes #inner's vertical size exactly the same as #outer's, and since #inner is below h2, then it makes #inner ALWAYS go beyond #outer, which looks really ugly.
Now I don't know h2's vertical size (since it depends on the font), and as far as I know CSS doesn't allow us to dynamically retrieve size of elements, so I can't do something like that:
#inner {
    height: calc(100% - getHeightOf(#outer>h3));
}

What is the solution to my problem? How can I make #inner never go outside #outer, no matter how large #inner's content may be?

A: Scenario-1: You don't want h2 content to be in fixed position. It will also scroll if inner content is overflow .

#outer{
  width: 100%;
  height: 200px;
  background-color: #eee;
  border: 2px solid grey;
  overflow: auto;
}
#inner{
  background-color: #ccc;
}

blah

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Scenario-2: You want h2 to be fixed in a sense that it should not scroll. The scroll bar should only be in inner div. In that case, use div instead of h2 and use definite height as shown below:

#outer{
  width: 100%;
  height: 200px;
  background-color: #eee;
  border: 2px solid grey;
  overflow: hidden;
}
.my-h2{
  font-size: 20px;
  font-weight: bold;
  height: 10%;
}
#inner{
  height: 90%;
  overflow: auto;
  background-color: #ccc;
}

blah

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: Give the Overflow:scroll property to the outer


text:
Q: How to put JComboBox into an Applet I have this code below. How do I make this JComboBOx run in an Applet? I'm trying to create an applet that allows the user to select a font and type in that font in a JTextArea. I have been searching for answers and made little progress. The error java.lang.reflect.InvocationTargetException keeps popping up. If you need more specifics please just comment.
import java.applet.Applet;
import java.awt.BorderLayout;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Font_Chooser extends JApplet {

    JLabel jlbPicture;
public Font_Chooser(){

    // Create the combo box, and set first item as Default
     GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] names = ge.getAvailableFontFamilyNames();
    final JComboBox comboTypesList = new JComboBox(names);
    comboTypesList.setSelectedIndex(0);
    comboTypesList.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JComboBox jcmbType = (JComboBox) e.getSource();
            String cmbType = (String) jcmbType.getSelectedItem();
            jlbPicture.setIcon(new ImageIcon(""
                    + cmbType.trim().toLowerCase() + ".jpg"));
            System.out.println(comboTypesList.getSelectedItem());
            //Font myFont = new Font((String)comboTypesList.getSelectedItem(), Font.BOLD, 12);

        }
    });
    // Set up the picture
    jlbPicture = new JLabel(new ImageIcon(""
            + names[comboTypesList.getSelectedIndex()] + ".jpg"));
    jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
    jlbPicture.setPreferredSize(new Dimension(177, 122 + 10));
    // Layout the demo
    setLayout(new BorderLayout());
    add(comboTypesList, BorderLayout.NORTH);
    add(jlbPicture, BorderLayout.SOUTH);

    }

public static void main(String s[])  {
    JFrame frame = new JFrame("JComboBox Usage Demo");
    frame.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {
            System.exit(0);

        }
    });
    frame.setContentPane(new Font_Chooser());
    frame.pack();
    frame.setVisible(true);

    }
}


text:
Q: Unable to use AWS Athena with JSON + Snappy In looking at AWS Athena's supported compression documentation I can see that Snappy is supported. However, when attempting to use Snappy compression with JSON data format, I am met with a multitude of errors.
I have tried creating tables in Athena with both available SerDes:
'org.apache.hive.hcatalog.data.JsonSerDe'
'org.openx.data.jsonserde.JsonSerDe'

I have tried uncompressed JSON and compressing with GZIP. Both work fine.
I have tried creating the table with a multitude of TBLPROPERTIES and SERDEPROPERTIES, but none have helped.
'Zero Records Returned' from my query is the end result of any attempt to query SNAPPY compressed JSON.
Has anyone seen this issue and overcome it?

A: For data in CSV, TSV, and JSON, Athena determines the compression type from the file extension. If no file extension is present, Athena treats the data as uncompressed plain text. If your data is compressed, make sure the file name includes the compression extension .json.snappy


text:
Q: Value does not reset when browser go back clicked I have added code to reset when browser go back button clicked. Below is my code.
if (performance.navigation.type == 2) { // This is to check navigation back button
    $('#radiobtn_one').prop('checked',false);
    $('#radiobtn_two').prop('checked',false);
    $('#radiobtn_three').prop('checked',false);
    $('#radiobtn_four').prop('checked',false);
    $('#radiobtn_six').prop('checked',false);

}

<input type="radio" name="status" id="radiobtn_one" value="active"
v-bind:checked="status=='active'" v-model="status">

My form has 5 steps. All those radio button are in next steps, those are all hidden initially with vue js condition.
Can anyone explain how could i reset hidden (display:none via vue js) input radio buttons?


text:
Q: Mechanize + Python: how to follow a link in a simple javascript? short: How to execute/simulate javascript redirection with python Mechanize?
location.href="http://www.site2.com/";

I've made a python script with mechanize module that looks for a link in a page and follows it.
The problem is on a particular site that when I do
br.follow_link("http://www.address1.com")

he redirects me to this simple page:
<script language="JavaScript">{
    location.href="http://www.site2.com/";
    self.focus();
    }</script>

Now, if I do:
br = mechanize.Browser(factory=mechanize.RobustFactory())

... #other code

br.follow_link("http://www.address1.com")
for link in br.links():
br.follow_link(link)
print link

it doesn't prints anything, that means that there is no link in that page.
But if I manually parse the page and I execute:
br.open("http://www.site2.com")

Site2 doesn't recognizes that I'm coming from "www.address1.com" and the script does      not work as I would like!
Sorry if it's just a newbie question and thank you in advance!
p.s. I have br.set_handle_referer(True)
EDIT: more info:
Inspecting that link with Fiddler2 it looks like:

GET http://www.site2.com/ HTTP/1.1 Host: www.site2.com Connection:
  keep-alive User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)
  AppleWebKit/537.4 (KHTML, like Gecko)        Chrome/22.0.1229.94
  Safari/537.4 Accept:
  text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
  Referer: http://www.address1.com Accept-Encoding: gzip,deflate,sdch
  Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie:
  PHPSESSID=6e161axxxxxxxxxxx; user=myusername;
  pass=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; ip=79.xx.xx.xx;
  agent=a220243a8b8f83de64c6204a5ef7b6eb;
  __utma=154746788.943755841.1348303404.1350232016.1350241320.43; __utmb=154746788.12.10.1350241320; __utmc=154999999; __utmz=154746788.134999998.99.6.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=%something%something%

so it seems to be a cookie problem?

A: Mechanize can't deal with JavaScript, since it can't interpret it, try parsing your site manually and passing this link to, br.follow_link.

A: I solved it! in this way:
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    ...

    br.follow_link("www.address1.com")
    refe= br.geturl()
    req = urllib2.Request(url='www.site2.com')
    req.add_header('Referer', refe)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj) )
    f = opener.open(req)
    htm = f.read()
    print "\n\n", htm

A: You could set the HTTP referrer header explicitly before making your request
br.addheaders = [('Referer', 'http://alpha.com')]
br.open("http://beta.com")

More details in the surprisingly difficult to find official docs  http://wwwsearch.sourceforge.net/mechanize/doc.html

A: How about
br.open("http://alpha.com")

br.follow_link("http://beta.com")

If you use br_follow_link hopefully that sets the HTTP referrer with the previous page. Whereas if you dobr.open that's like opening a new window, it doesn't set the HTTP referrer header.

Edit. Ok it looks like .follow_link doesn't take strings but takes a special mechanize.Link object with a property .absolute_url. You can fake that.
>>> class Fake:
...     pass
...
>>> x = Fake()
>>> x.absolute_url="http://stackoverflow.com"
>>> br.follow_link(x)
<response_seek_wrapper at 0x2937af8 whose wrapped object = <closeable_response at 0x2937f08 whose fp = <socket._fileobject object at 0x02934970>>>
>>> br.title()
'Stack Overflow'

or make a real mechanize.Link which is less hacky but more tedious.


text:
Q: How to do using React JS Progress bar data wants to come api enter image description here
depending on data progress bar needs to show, that data comes from api call

Your balance

                    <div class="bg-blue-600 text-xs font-medium text-blue-100 text-center p-0.5 leading-none rounded-full h-3" style={{ width: `${CreditDatas}%`}}>

                    {CreditDatas?.balancecredits} /
                    {CreditDatas?.availablecredits}

I want to fill in the color balance of the credits.
Thanks, in advance.


text:
Q: Locking user account on RHEL using PAM LDAP I have a bit of an edge case here. My institution has a RHEL server where students can log in and do their work. Accounts are held in LDAP and the server uses PAM and LDAP to authenticate. At the end of the academic year I need to lock the student accounts on this server - i.e. preserve them intact, but prevent that user from logging in. I've tried passwd -l and usermod -L, but in both cases the user can still log in.
Is there a way of locking an account that will work with PAM LDAP?

A: This can be accomplished by using group ACLs. Adding the following line to your common-auth file:
auth required    pam_access.so

Will get it set up. You can then use a group (it can be LDAP) to set an explicit deny. Invert the meaning to get an explicit allow, which may be a better choice if you're not allowed to ever delete students.
-:ALL EXCEPT root grp-retired-students:ALL EXCEPT LOCAL


text:
Q: Return one-level result list from a join statement in EF I have the following simple join statement:
Dim result = (From PropertyDefinition In econtext.PropertyDefinitions
              Join ProductDef In econtext.ProductPropertyValues
                On PropertyDefinition.PropertyDefID Equals ProductDef.ProductPropDefID
              Where ProductDef.ProductID = 1
              Select ProductDef,
                     PropertyDefinition.PropertyDefName,
                     PropertyDefinition.PropertyDefName2,
                     PropertyDefinition.PropertyDefIIsDeleted).list()

If i explicitly included all columns under ProductDef it works, and the result comes in one list, currently the result of ProductDef is coming in a separated list:

I need everything from ProductDef and some from PropertyDefinition but not in nested lists,
How to get the result in one-shot list without the need to explicitly include all columns of ProductDef?

A: I don't think you can.
You're getting the ProductDef as a nested object because that's exactly what you're asking for when you specify ProductDef as one of the values to return: the ProductDef object itself, rather than any of its properties.
What you want seems to be the equivalent of SQL Server's table1.* syntax for requesting that all columns of a given table be returned, with the potential for returning additional values as well.  But I don't think that exists in LINQ.
It's possible you could work something up with dynamic data types that could do this, but honestly it'd be simpler just to list out all the properties you want.
ETA:  Or, you could create another type that had all the properties that you wanted, and create a constructor that took a ProductDef and a PropertyDefinition and populated all the fields from the constructor parameters.  That would deliver you an object that had all the properties you wanted.  But it would certainly be more work.


text:
Q: Access two tables at a time in .net SELECT TOP 1000
    [ID]
    ,[Name]
    ,[Phone]
    ,[Email]
    ,[AID]
    ,[Password]
    ,[Date/time]
    ,[IsVerify]
    ,[ProfilePicture]
FROM
    [ChefODine].[dbo].[User]

This is my User table AID is the foreign Key of address table having following fields.
SELECT TOP 1000
    [ID]
    ,[Location]
    ,[LAT]
    ,[Lng]
FROM
    [ChefODine].[dbo].[Address]

I want to add user address and other info in database through web service. i want that whenever user add his info the address will save in address table and AID will save in user table. This is my code Please guide me i am new in this.
[HttpPost]
public User Register([FromBody]User user)
{
    if (db.Users.Any(x => x.Email == user.Email))
        throw new Exception("Username \"" + user.Email + "\" is already taken");

    db.Users.Add(user);
    db.SaveChanges();

    return user;
}

A: You have to Specify the value before hitting into SaveChanges something like:
[HttpPost]
public User Register([FromBody]User user)
{
    if (db.Users.Any(x => x.Email == user.Email))
        throw new Exception("Username \"" + user.Email + "\" is already taken");
    user.Email  = "this is the Email from anywhere";
    user.AID = "This is your Aid Value";
    db.Users.Add(user);
    db.SaveChanges();

     //If you want to save Address
   AddressEntity adr = new AddressEntity()
    adr.address = "This is your new address";
    db.Address.Add(adr);
    db.SaveChanges();

    return user;
}


text:
Q: Discrepancy between Minimize and NSolve I was trying to minimize a quartic polyonomial equation with a constraint using Mathematica but I got some conflicting results and I wanted to ask to you. Am I making a conceptual mistake or a coding mistake?
First I wanted to minimize using the Minimize function:
Minimize[pol1[1.9, 0.1],
  c0r^2 + c0i^2 + c1r^2 + c1i^2 == 1, {c0r, c0i, c1r, c1i}];

As you can see the function called pol1 and the constraint is a unit sphere. Function is a quartic polynomial with funny coefficients:
 Chop[N[pol1[1.9, 0.1]]]
2.23232 c0i^2 - 0.0995481 c0i^4 + 2.23232 c0r^2 -
 0.199096 c0i^2 c0r^2 - 0.0995481 c0r^4 - 0.433493 c0i c1i +
 0.126205 c0i^3 c1i + 2.07557 c0r c1i - 1.69557 c0i^2 c0r c1i +
 0.126205 c0i c0r^2 c1i - 1.69557 c0r^3 c1i + 7.66189 c1i^2 -
 0.763494 c0i^2 c1i^2 + 1.0748 c0i c0r c1i^2 - 7.94349 c0r^2 c1i^2 +
 0.458615 c0i c1i^3 - 6.16151 c0r c1i^3 - 1.31455 c1i^4 -
 2.07557 c0i c1r + 1.69557 c0i^3 c1r - 0.433493 c0r c1r +
 0.126205 c0i^2 c0r c1r + 1.69557 c0i c0r^2 c1r +
 0.126205 c0r^3 c1r - 1.0748 c0i^2 c1i c1r + 14.36 c0i c0r c1i c1r +
 1.0748 c0r^2 c1i c1r + 6.16151 c0i c1i^2 c1r +
 0.458615 c0r c1i^2 c1r + 7.66189 c1r^2 - 7.94349 c0i^2 c1r^2 -
 1.0748 c0i c0r c1r^2 - 0.763494 c0r^2 c1r^2 +
 0.458615 c0i c1i c1r^2 - 6.16151 c0r c1i c1r^2 -
 2.6291 c1i^2 c1r^2 + 6.16151 c0i c1r^3 + 0.458615 c0r c1r^3 -
 1.31455 c1r^4

It gave me a real solution.
But then I thought maybe I should do it in the proper way: use Lagrange multiplier method, take derivatives with respect to each parameters, solve the equations and then find the solution that has the global minimum:
    eqs = pol1[1.9, 0.1] + \[Mu]*(c0r^2 + c0i^2 + c1r^2 + c1i^2 - 1)
eq1 = N[D[eqs, c0r]];
eq2 = N[D[eqs, c0i]];
eq3 = N[D[eqs, c1r]];
eq4 = N[D[eqs, c1i]];
eq5 = N[D[eqs, \[Mu]]];

NSolve[eq1 == 0 && eq2 == 0 && eq3 == 0 && eq4 == 0 && eq5 == 0, {c0r,
   c0i, c1r, c1i, \[Mu]}]

Now this second method doesn't even return a real solution set. Where is the mistake?
I will be grateful if you help.
Mathematica version 11.01.0

A: You only need NMinimize to solve your problem!
J=2.23232 c0i^2 - 0.0995481 c0i^4 + 2.23232 c0r^2 -
0.199096 c0i^2 c0r^2 - 0.0995481 c0r^4 - 0.433493 c0i c1i +
0.126205 c0i^3 c1i + 2.07557 c0r c1i - 1.69557 c0i^2 c0r c1i +
0.126205 c0i c0r^2 c1i - 1.69557 c0r^3 c1i + 7.66189 c1i^2 -
0.763494 c0i^2 c1i^2 + 1.0748 c0i c0r c1i^2 - 7.94349 c0r^2 c1i^2 +
0.458615 c0i c1i^3 - 6.16151 c0r c1i^3 - 1.31455 c1i^4 -
2.07557 c0i c1r + 1.69557 c0i^3 c1r - 0.433493 c0r c1r +
0.126205 c0i^2 c0r c1r + 1.69557 c0i c0r^2 c1r +
0.126205 c0r^3 c1r - 1.0748 c0i^2 c1i c1r + 14.36 c0i c0r c1i c1r +
1.0748 c0r^2 c1i c1r + 6.16151 c0i c1i^2 c1r +
0.458615 c0r c1i^2 c1r + 7.66189 c1r^2 - 7.94349 c0i^2 c1r^2 -
1.0748 c0i c0r c1r^2 - 0.763494 c0r^2 c1r^2 +
0.458615 c0i c1i c1r^2 - 6.16151 c0r c1i c1r^2 -
2.6291 c1i^2 c1r^2 + 6.16151 c0i c1r^3 + 0.458615 c0r c1r^3 -1.31455 c1r^4

sol=NMinimize[J, c0r^2 + c0i^2 + c1r^2 + c1i^2 == 1, {c0r, c0i, c1r, c1i}]
(*{1.97153, {c0r -> 0.948685, c0i -> -0.118812, c1r -> 0.00523234,c1i -> -0.293008}}*)

NSolve doesn't find a solution!
eqn = Map[# == 0 &, D[J, {{c0i, c0r, c1i, c1r}}]];
NSolve[ Join[eqn , {c0r^2 + c0i^2 + c1r^2 + c1i^2 == 1}], {c0i, c0r,c1i, c1r}, Reals]
(*{}*)

A: Not really an answer, just showing we can solve the system in question.
poly = 2.23232 c0i^2 - 0.0995481 c0i^4 + 2.23232 c0r^2 -
   0.199096 c0i^2 c0r^2 - 0.0995481 c0r^4 - 0.433493 c0i c1i +
   0.126205 c0i^3 c1i + 2.07557 c0r c1i - 1.69557 c0i^2 c0r c1i +
   0.126205 c0i c0r^2 c1i - 1.69557 c0r^3 c1i + 7.66189 c1i^2 -
   0.763494 c0i^2 c1i^2 + 1.0748 c0i c0r c1i^2 -
   7.94349 c0r^2 c1i^2 + 0.458615 c0i c1i^3 - 6.16151 c0r c1i^3 -
   1.31455 c1i^4 - 2.07557 c0i c1r + 1.69557 c0i^3 c1r -
   0.433493 c0r c1r + 0.126205 c0i^2 c0r c1r +
   1.69557 c0i c0r^2 c1r + 0.126205 c0r^3 c1r -
   1.0748 c0i^2 c1i c1r + 14.36 c0i c0r c1i c1r +
   1.0748 c0r^2 c1i c1r + 6.16151 c0i c1i^2 c1r +
   0.458615 c0r c1i^2 c1r + 7.66189 c1r^2 - 7.94349 c0i^2 c1r^2 -
   1.0748 c0i c0r c1r^2 - 0.763494 c0r^2 c1r^2 +
   0.458615 c0i c1i c1r^2 - 6.16151 c0r c1i c1r^2 -
   2.6291 c1i^2 c1r^2 + 6.16151 c0i c1r^3 + 0.458615 c0r c1r^3 -
   1.31455 c1r^4;

vars = Variables[poly];
lagrangian = poly + mu*(vars.vars - 1);
derivs = Grad[lagrangian, Variables[lagrangian]];

solns = NSolve[derivs];
realsolns = Select[solns, FreeQ[#, Complex] &];

Check we made the sum of squares vanish.
In[303]:= (vars.vars - 1) /. realsolns

(* Out[303]= {-1.11022302463*10^-16, 7.77156117238*10^-16,
 6.66133814775*10^-16, -1.11022302463*10^-16, 0., \
-6.10622663544*10^-16, -2.38524477947*10^-16, -1.82145964978*10^-16, \
-6.39245600897*10^-16,
 2.08166817117*10^-15, -1.2490009027*10^-16, -2.00811589579*10^-14, \
-1.89015469942*10^-14, -3.88578058619*10^-16, 0., 1.38777878078*10^-16} *)

Check resulting polynomial values.
In[304]:= poly /. realsolns

(* Out[304]= {6.70664718833, 6.70664718833, 6.70664718833, \
6.70664718833, 1.55255414283, 1.55255414283, 2.14374447723, \
2.14374447723, 2.14374443673, 1.9715274388, 1.9715274388, \
1.9715274388, 1.9715274388, 1.97152732129, 1.97152732129, \
1.97152732129} *)

We can get that smallest value using optimization directly.
{min, vals} =
 Minimize[pol1,
  c0r^2 + c0i^2 + c1r^2 + c1i^2 == 1, {c0r, c0i, c1r, c1i},
  Method -> "DifferentialEvolution"]

(* Out[305]= {1.55255311155, {c0r -> 0.13967123044,
  c0i -> 0.781692557246, c1r -> -0.602194200876,
  c1i -> 0.0825305977305}} *)

So what is different? Just the version. For NSolve some of the version 10 releases had trouble getting explicitly real values. Use of Chop at some modest level might suffice to recover reasonable results.


text:
Q: Doubt about the existence of the gradient. Consider $$ f(x,y) = \begin{cases} \frac{xy}{x^2+y^2} & , \text{if } \ (x,y)\neq(0,0) \\
\hspace{0.5cm}0 &, \text{if } \ (x,y)=(0,0) \end{cases} $$
Computing the limit at zero
$$
\left\{
\begin{array}{c}
x=rcos\theta \\
y=rsin\theta \\
\end{array}
\right.
$$
$$ (x,y) \to (0,0) \Longleftrightarrow r \to 0 $$
$$ \lim_{ r \to \ 0 }  \frac{ r^2cos\theta sin\theta }{ r^2( cos^2 \theta + sin^2 \theta) } = cos \theta sin \theta   $$
Then the limit does not exist. Hence this function is not continuos at zero.
$$ \nabla f(x,y) = \begin{cases} \left(  \frac{y(y^2-x^2)}{(x^2+y^2)^2} , \frac{x(x^2-y^2)}{(x^2+y^2)^2} \right) & , \text{if } \ (x,y)\neq(0,0) \\
\hspace{0.5cm} (0,0) &, \text{if } \ (x,y)=(0,0) \end{cases} $$
So it doesn't matter that the function is not continuous at zero? or this function does not differentiable at zero?

A: If a function $f$ is differentiable at a point $p$, then $\nabla f(p)$ exists. However, the existence of $\nabla f(p)$ only requires the existence of partial derivatives of $f$ at $p$, which is not enough to assure that $f$ is differentiable at $p$.


text:
Q: Recursive method to build a vector I have a simple recursive function:
def subTree(z,sublevels):

    if(z < sublevels):
        print "from z = ", z, " to z = ", z+1
        subTree(z+1,sublevels)
    else:
        print "z = ", z, " !"

this simply goes from z to sublevels, ex:
subTree(2, 6)
from z =  2  to z =  3
from z =  3  to z =  4
from z =  4  to z =  5
from z =  5  to z =  6
z =  6  !

Now, how can i make it so that the call to the function returns an ordered vector of z ?
(in the example it would be: z[2,3,4,5,6])
From keiv code :
def subTree(z,sublevels,a):
    a.append(z)
    if(z < sublevels):
        subTree(z+1,sublevels,a)

a=[]
subTree(2,6,a)

A: I share keiv.fly's bias for a recursive function that returns a result:
def subTree(z, sublevels):
    result = [z]

    if z < sublevels:
        result += subTree(z + 1, sublevels)

    return result

a = subTree(2, 6)

It can be reduced to the slightly less efficient one-liner:
def subTree(z, sublevels):
    return [z] + (subTree(z + 1, sublevels) if z < sublevels else [])

and both can be modified to return a tuple instead of a list:
def subTree(z, sublevels):
    return (z,) + (subTree(z + 1, sublevels) if z < sublevels else ())

And we can easily reverse the order of the result, if desired:
def subTree(z, sublevels):
    return (subTree(z + 1, sublevels) if z < sublevels else ()) + (z,)

Returning:
(6, 5, 4, 3, 2)

If you want to pass the array into the function, then I suggest you still return it as a value as follows:
def subTree(z, sublevels, array):
    array += type(array)([z])

    if z < sublevels:
        array = subTree(z + 1, sublevels, array)

    return array

By doing type(array)([z]), and the explicit returns, we can make this function work for multiple data types:
a = []
a = subTree(2, 6, a)
print(a)

a = ()
a = subTree(2, 6, a)
print(a)

a = b""
a = subTree(ord('2'), ord('6'), a)
print(a)

OUTPUT:
[2, 3, 4, 5, 6]
(2, 3, 4, 5, 6)
b'23456'

A: This code changes "a" list to [2,3,4,5,6]
def subTree(z,sublevels,a):
    a.append(z)
    if(z < sublevels):
        subTree(z+1,sublevels,a)

a=[]
subTree(2,6,a)


text:
Q: PHP function returns ZERO I'm having trouble with this PHP function.  It keeps returning zero, but I know the SQL statement works because I've queried it myself.  Any ideas what I'm doing wrong?  The last line makes no sense to me...I'm editing this code that someone else wrote.  This function should return a number in the hundreds, assuming the date is in March.  Thanks!
    function getCountBetweenDays($day1,$day2,$service)

{

    global $conn;

    if ($service==1){

$query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";}

    elseif($service==2){

$query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";}

        elseif($service==3){

$query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";}

$result = mysql_query($query,$conn);

  $num = mysql_fetch_array ($result);

  return $num['NUM'];

}

A: Try some debug output in your function, e.g.
function getCountBetweenDays($day1,$day2,$service)
{
  global $conn;

  switch($service) {
    case 1:
      $query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'";
      break;
    case 2:
      $query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'";
      break;
    case 3:
      $query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'";
      break;
    default:
      die('unknown value for $service');
  }

  echo '
Debug: $query=', htmlspecialchars($query), '
';
  $result = mysql_query($query,$conn) or die('mysql_query failed: '.htmlspecialchars(mysql_error($conn)));
  echo '
Debug: numrows=', mysql_num_rows($result), '
';
  $num = mysql_fetch_array($result);

  return $num['NUM'];
}

A: For starters, add
if (!$result) echo mysql_error();

after each mysql_query() call to see whether there are any errors. I'm pretty sure there are.

A: Your queries are not formatter properly they are :
"SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";

They should be :
"SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'";

You have an extra semi-colon in each query. and use or die mysql_error() to print out the error.
Also this part :
$num = mysql_fetch_array ($result);

  return $num['NUM'];

I'd replaced with :
$num = mysql_fetch_array ($result);

extract($num);

  return $NUM;//if this is your field name

A: Fixed it...dumb mistake.  I'm so new to PHP and MySQL, sorry.
getCountBetweenDays(2010-3-1,2010-3-28,CONT_ALL_SERVICE);

should have been:
getTweetCountBetweenDays('2010-3-1','2010-3-28',CONT_ALL_SERVICE);

Thanks all for the help and I now know how to debug properly!

A: You're trying to reference a numeric index [n] with an associative index ['s']. Either specify  this to your query
mysql_fetch_array($result, MYSQL_BOTH)

Or just do
mysql_fetch_assoc($result);

Which will let you reference indices by association

A:
return $num['NUM'];

means return the 'num' part of the array; Change 'NUM' to 1 or 2 and then try


text:
Q: When using fastify-session and fastify-webockets, how do I get access to the session? When I use both fastify-websocket and fastify-session in my Fastify app, I run into an issue.
  fastify.get( myWebsocketPath, websocket: true },
               async (connection, rawRequest) => {

    console.log(`request for websocket connection`)
    if( request.session.authenticated ) {
      myApi( connection.socket )
    }
  })

Except this fails because I only have the rawRequest, not the regular request decorated with the session.

A: It seems that to get an external handle for it you need to set the session store yourself. It's better to use a custom store, but for simplicity in this example I will use the built-in one provided by fastify-session.
let fastifySession = require(`fastify-session`)
let mySessionStore = new fastifySession.MemoryStore /// TODO: customize
let options = { store: mySessionStore, secret: `itsasecrettoeverybody`,  cookieName: `sessionId`, expires: 3600000, cookie:  { secure: false } }
fastify.register(fastifySession, options)

// ...

const routes = async (fastify, options) => {
  fastify.get( myWebsocketPath, websocket: true },
               async (connection, rawRequest) => {

    /// Retrieve the session
    let cookies = rawRequest.headers.cookie.split(`;`)
    for( c of cookies ) {
      if( c.startsWith(`sessionId=`) ) {

        /// Get SessionID from the cookie
        let sessionID = c.substring(10).trim()
        sessionID = sessionID.substring( 0, sessionID.indexOf(`.`) )

        /// Collect session and check the authentication state.
        mySessionStore.get( sessionID, ( o, session ) => {
          if( session != null && session.authenticated == true ) {
            myApi( connection.socket )
          }
        })
        break
      }
    }
  })
}

Credit to Zekth for pointing me in the right direction.


text:
Q: Crop out background in an image - NumPy / Python I have the following image extracted. Background value is 170, I need to extract the polygon with a minimum of 170 values.
for the image is like below

I would like to have a processed image as below

I can implement a nested for loop and iterate through until i find the minimum index of the column and find the maximum index of the column number for each row and then extract the region.. but Im interested in a numpy query more efficient solution

A: Approach #1
One strategy would be to label the image, get the label for one of the corners, as one sample for the background color and create a mask of that color. So, the inverted mask area is the one we are trying to crop into. For the cropping, we will take inspiration from Crop black border of image using NumPy : Answer post.
Here's the implementation -
import cv2
from scipy.ndimage import label

im = cv2.imread('xYTKn.png') # read in input image
L,_ = label(im)
mask = (L!=L[0,0]).any(-1)
out = im[np.ix_(mask.any(1), mask.any(0))]
cv2.imwrite('output.png',out)

Input -

Output -

Approach #2
Another similar strategy would be to convert to grayscale upfront, then label and get the required mask, like so -
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
L,_ = label(gray)
mask = (L!=L[0,0])
out = im[np.ix_(mask.any(1), mask.any(0))]

Benchmarking
We will time the proposed solutions on the given sample image. The mask creation is different between the two approaches. So, we will time those sections only -
In [70]: %%timeit
    ...: L,_ = label(im)
    ...: mask = (L!=L[0,0]).any(-1)
47.4 ms ± 2.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [71]: %%timeit
    ...: gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    ...: L,_ = label(gray)
    ...: mask = (L!=L[0,0])
2.59 ms ± 20.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


text:
Q: where is the default cursor location of the edittext in Oreo? Prior to Android 8.0, the default cursor location of edittext is 0: the cursor is before the text.
But in android 8.0, the cursor is after the text.
How to resolve that ?
I tried to use edittext.setSelection, but it does not work.


text:
Q: File remaining locked in Windows after Java File.canWrite() returning true and all close() methods called I'm using a WatchService to check for the addition of a file to a directory. A listener then  gets an input stream from the file in the form of a ByteBuffer wrapped in a custom class (See below).
The issue is that despite calling close() on every relevant object (and a few more too), and checking that the file is not locked with File.canWrite() (which returns true), Windows still complains that the file is locked by the JVM when I try to move it.
I have scoured the code for anything which might be locking the file, but since canWrite() is returning true I'm not sure what else I can do. Does anyone have any ideas?
The skeleton of the custom class is as follows. I realise this may not be the best implementation but I don't know whether it's causing the issue either.
private static class ByteBufferBackedInputStream extends InputStream {

    private final ByteBuffer  buf;
    private final FileChannel channel;

    public ByteBufferBackedInputStream(FileInputStream fs) throws IOException {

        this.channel = fs.getChannel();
        this.buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

        fs.close();
    }

    //... all required methods implemented, including close() method

}

Any help would be much appreciated.
Edit Following on from the first comments, I am using buf.close() and this isn't helping. I've also stepped through the whole process and no exceptions are being thrown - just to be sure I am using finally blocks.
I have a feeling this may somehow be to do my implementation of the WatchService but it doesn't explicitly use any IO methods, just a producer and consumer LinkedBlockingQueue.
Edit 2 As Andreas suggested in the comments below, using a standard read()/write() operation worked and the file was not locked. Ultimately, the use of a buffer was legacy code (possibly for optimisation when dealing with potentially large files) so can be safely changed for now.
None the less, the question still remains technically unanswered so I'll leave it open for now. Thanks for the help :)


text:
Q: angular ui-router on back press TypeError: a.indexOf is not a function I'm working on an Angular 1.6.1 web-application with Angular Material and ui-router modules installed.
Navigating from state to state is working fine but when the browser back button is pressed the URL is changing but the state is not (the view stays the same)! I get the following error in the console log:
TypeError: a.indexOf is not a function
at f (angular.js:438)
at m (angular.js:438)
at Object.z.transitionTo (angular.js:438)
at Array.<anonymous> (angular.js:438)
at Object.invoke (angular.js:39)
at g (angular.js:438)
at angular.js:438
at b (angular.js:438)
at n (angular.js:438)
at m.$broadcast (angular.js:146)

The $stateChangeStart is not even reached.
So it seems like there is something happening to the browser history stack.
A couple of days ago everything worked fine, did not change anything since then (well, not according to my git log).
My $stateProvider config is divided over different files, the first file looks likes this:
  $stateProvider
        //Main states
        .state('main', {
            abstract: true,
            controller: 'MainController',
            template: '

'
        })
        .state('null', {
            parent: 'main',
            url: '/',
            controller: function($state){
                $state.go('login', {}, {location: "replace", reload: true});
            }
        })
        //main loggedin state loading main loggedin view
        .state('logged-in', {
            parent: 'main',
            abstract: true,
            templateUrl: COMP_DIR + 'core/logged-in/logged-in.view.html',
            controller: 'LoggedInController',
            controllerAs: 'vm'
        })

        .state('no-enterprise', {
            parent: 'logged-in',
            abstract: true,
            template: '

',
            controller: 'NoEnterpriseController'
        })

After this configuration I include a couple of routing files for each module of the application. After that I add the last routing file like this:
 $stateProvider
    //main enterprise state
        .state('enterprise', {
            parent: 'logged-in',
            url: '/{slug}',
            controller: 'EnterpriseController',
            controllerAs: 'vm',
            template: '

'
        })

        //states inside enterprise state
        .state('dashboard', {
            url: '/',
            parent: 'enterprise',
            title: 'Dashboard',
            templateUrl: COMP_DIR + 'dashboard/dashboard.index.view.html',
            controller: 'Dashboard.DashboardController',
            controllerAs: 'vm'
        })

The state changes are being triggered by adding a simple ui-sref to an element and that is working fine, but i'm not able to go back with the back button of the browser.
Does anybody have an idea why this error is popping up and the back button is therefore not working properly?
Thanks in advance!
Edit: Additionally, when I refresh the application (pressing F5) back button is working until I navigate forward one step, then I get the same error trying to navigate forward in the history stack.

A: I solved the problem. There was an error in the $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams) {} function.
I tried to compare the toState.name to something undefined.
Which was weird because the error occurs before the state change. So if you have a error while changing states be sure to check your $stateChangeSuccess event handler ;)