text:
Q: How to set local variable inside callback function in Java / Android? How can I set the local variable publicIpAddress inside the onResponse() callback below? The line "publicIpAddress = response" has the error "final local variable publicIpAddress cannot be assigned, since it is defined in an enclosing type"
public static String getPublicIpAddress(Context context)
    {
        String publicIpAddress = "";

        StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET,
                                                                    "http://icanhazip.com/",
                                                                    new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                publicIpAddress = response;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error in getPublicIpAddress()");
            }
        });

        VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

        return publicIpAddress;
    }

A: A final variable can only be initialized once. See How final keyword works
In your case, you are initializing it 2 times, in the declaration (final String publicIpAddress = ""; and in OnResponse).
Try to:
1) Remove the keyword final
2) Remove the initialization in the declaration of the publicIpAddress

A: Ok Do like this
public class xxxx  extends Activity {

  static String publicIpAddress;
................................

public static String getPublicIpAddress(Context context)
    {

        StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET,
                                                                    "http://icanhazip.com/",
                                                                    new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                publicIpAddress = response;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error in getPublicIpAddress()");
            }
        });

        VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

        return publicIpAddress;
    }

A: This is definitely not recommended. The request you are making is asynchronous and will always return null or "" - whatever value you initialized publicIpAddress with.
Your method is returning immediately after placing StringRequest in the queue before it has a chance to execute the onResponse method. The return happens before this code is ever called: publicIpAddress = response;
Read this: Asynchronous HTTP Requests in Android Using Volley


text:
Q: Multiple Complex types in parameters of Web API call I am doing a POC and seeing if I can't convert one of our old .asmx webservices into a WebAPI 2 webservice.  I have already done some of the simple methods that we have that just take simpel input parameters...
public int HelloWorld(int parm){
   if(parm == 3){ return "you are stupid";}
   else if (parm == 2) { return "No you are stupid"; }
   else { return "In any event, Hello World!"}
}

But I have several cases where I need to pass in large complex types into the methods.
public IEnumerable<ComplexObjects> processComplexObjs(ComplexObjects firstParm, ComplexObjects secondParm){
   ...
   return List<ComplexObjects>;
}

Apparently you can't have more than one complex object if you use [FromBody] as an attribute peppered around the parameter.  Apparently there is a way you can JSONObject to do this.  Are there any good examples of how to do this?

A: this gives one way around it
http://blog.travisgosselin.com/web-api-signatures-with-multiple-complex-parameters/
Basically, use the JObject to store the complex classes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React Context Provider that knows whether any components are mounted that use this context I have a context provider which maintains a websocket connection to the server and exposes some state that the server can update, and is trivial for components to consume. This much works fine.
However, the websocket code connects whenever the provider is mounted - which in my case is basically always. But about half the time there aren't actually any components rendered that consume this context.
Is it possible for my provider to know when there are no components mounted that consume its context, so that it could connect/disconnect only as required?

A: Just a thought, how about making the components call the context on mount and unmount:
useEffect(() => {
  // This will run when the component is mounted
  registerIncontext("componentId");
  return () => {
    // This will run when the component is unmounted
    unregisterIncontext("componentId");
  };
}, []);

You will have to expose a way to register and unregister in the context.


text:
Q: combining a vector and int in c++11? Say if I had a vector<string> already defined and filled called test and an int called a. If I wanted to combine these 2 into a single object called combined where i could do combined[0] = test; to initialize/retrieve the object with the vector and combined[1] = a; to initialize/retrieve the object with the int, what would be the best function to do so and how would I do so? I had attempted to do vector<vector<string>, int> but this gave me an error.
Note: I am compiling with -std=c++11 if this matters.

A: Use a std::tuple<std::vector<std::string>,int>.
#include <tuple>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> test;
    int a{};
    std::tuple<std::vector<std::string>,int> combined;

    //To access elements, use `std::get`:
    std::get<0>(combined) = test;
    std::get<1>(combined) = a;
}

to answer cellsheet's comment: that function already exists, it's called std::make_tuple() (see also comment by fjardon on how to store this).
Btw, why do you need to extend std::vector<std::string> by an int?

A: If I understand correctly what you're asking, I think you can do this with a std::pair:
std::pair<std::vector<std::string>, int> combined;
combined.first = test; // assign vector
combined.second = a; // assign int

or simply
auto combined = std::make_pair(test,a);

A: It requires (ugly) type elision:
#include <iostream>
#include <stdexcept>
#include <type_traits>
#include <vector>

class X {
    public:
    typedef std::vector<std::string> vector_type;
    typedef int integer_type;

    private:
    enum Type {
        TypeVector,
        TypeInteger
    };

    template <bool Constant>
    class Proxy
    {
        private:
        typedef typename std::conditional<
                Constant, const void, void>::type void_t;

        public:
        typedef typename std::conditional<
            Constant, const vector_type, vector_type>::type vector_t;
        typedef typename std::conditional<
            Constant, const integer_type, integer_type>::type integer_t;

        Proxy(vector_t& v)
        :   m_type(TypeVector), m_data(&v)
        {}

        Proxy(integer_t& i)
        :   m_type(TypeInteger), m_data(&i)
        {}

        operator vector_t& () const {
            if(m_type != TypeVector) throw std::runtime_error("Invalid Type");
            return *static_cast<vector_t*>(m_data);
        }

        operator integer_t& () const {
            if(m_type != TypeInteger) throw std::runtime_error("Invalid Type");
            return *static_cast<integer_t*>(m_data);
        }

        private:
        template <typename T, typename U, bool> struct Assignment
        {
            static void apply(void_t*, const U&) {}
        };

        template <typename T, typename U>
        struct Assignment<T, U, true>
        {
            static void apply(void_t* p, const U& value) {
                *static_cast<T*>(p) = value;
            }
        };

        template <typename T, typename U>
        // Attention: Use a reference - std::is_assignable<int, int>::value> is false;
        struct Assign : Assignment<T, U, std::is_assignable<T&, U>::value>
        {};

        public:
        template <typename U>
        Proxy&
        operator = (const U& value) {
            static_assert( ! Constant, "Assignment to Constant");
            switch(m_type) {
                case TypeVector:
                Assign<vector_t, U>::apply(m_data, value);
                break;
                case TypeInteger:
                Assign<integer_t, U>::apply(m_data, value);
                break;
                default: throw std::out_of_range("Invalid Type");
            }
            return *this;
        }

        private:
        Type m_type;
        void_t* m_data;
    };

    public:
    X() : m_v{"Hello"}, m_i(1) {}
    Proxy<true> operator [] (std::size_t i) const {
        switch(i) {
            case 0: return Proxy<true>(m_v);
            case 1: return Proxy<true>(m_i);
            default: throw std::out_of_range("Invalid Index");
        }
    }

    Proxy<false> operator [] (std::size_t i) {
        switch(i) {
            case 0: return Proxy<false>(m_v);
            case 1: return Proxy<false>(m_i);
            default: throw std::out_of_range("Invalid Index");
        }
    }

    private:
    vector_type m_v;
    integer_type m_i;
};

int main() {

    // Note: The Proxy has no operator []

    // const
    {
        const X x;
        const X::vector_type& v = x[0];
        std::cout << v[0] << " " << x[1] << std::endl;
    }
    // non const
    {
        X x;
        X::vector_type& v = x[0];
        v[0] = "World";
        x[1] = 2;
        std::cout << v[0] << " " << x[1] << std::endl;
    }
}

You might consider boost::any, instead.


text:
Q: Multiple regression in R: Variable not found in data.frame Here's my data.frame :: beef
> head(beef)
   YEAR....PBE  CBE  PPO  CPO  PFO DINC  CFO RDINC RFP
1 1925    59.7 58.6 60.5 65.8 65.8 51.4 90.9  68.5 877
2 1926    59.7 59.4 63.3 63.3 68.0 52.6 92.1  69.6 899
3   1927    63 53.7 59.9 66.8 65.5 52.1 90.9  70.2 883
4   1928    71 48.1 56.3 69.9 64.8 52.7 90.9  71.9 884
5   1929    71 49.0 55.0 68.7 65.6 55.1 91.1  75.2 895
6 1930    74.2 48.2 59.6 66.1 62.4 48.8 90.7  68.3 874

And
dput(head(beef))
structure(list(YEAR....PBE = structure(1:6, .Label = c("1925    59.7",
"1926    59.7", "1927    63", "1928    71", "1929    71", "1930    74.2",
"1931    72.1", "1932    79", "1933    73.1", "1934    70.2",
"1935    82.2", "1936    68.4", "1937    73", "1938    70.2",
"1939    67.8", "1940    63.4", "1941    56"), class = "factor"),
    CBE = c(58.6, 59.4, 53.7, 48.1, 49, 48.2), PPO = c(60.5,
    63.3, 59.9, 56.3, 55, 59.6), CPO = c(65.8, 63.3, 66.8, 69.9,
    68.7, 66.1), PFO = c(65.8, 68, 65.5, 64.8, 65.6, 62.4), DINC = c(51.4,
    52.6, 52.1, 52.7, 55.1, 48.8), CFO = c(90.9, 92.1, 90.9,
    90.9, 91.1, 90.7), RDINC = c(68.5, 69.6, 70.2, 71.9, 75.2,
    68.3), RFP = c(877L, 899L, 883L, 884L, 895L, 874L)), .Names = c("YEAR....PBE",
"CBE", "PPO", "CPO", "PFO", "DINC", "CFO", "RDINC", "RFP"), row.names = c(NA,
6L), class = "data.frame")

I want to create a multiple linear regression model for PBE depending on the other variables. Following the tutorial in this link I think I should do something the following code:
> lm(formula = PBE ~ CBE + PBO + CPO + PFO +
+        DINC + CFO+RDINC+RFP+YEAR, data = beef)

Error in eval(expr, envir, enclos) : object 'PBE' not found
so I decided to try the followings but all have some errors:
> lm(formula=PBE~YEAR,data=beef)
Error in eval(expr, envir, enclos) : object 'PBE' not found
> lm(formula=beef$PBE~beef$YEAR)
Error in model.frame.default(formula = beef$PBE ~ beef$YEAR, drop.unused.levels = TRUE) :
  invalid type (NULL) for variable 'beef$PBE

Can you please give me some insight where the typo/error is lying?
P.S.: I read the file using beef=read.table("beef.txt", header = TRUE, sep = "\t", comment.char="%") and the file looks like the following:
% http://lib.stat.cmu.edu/DASL/Datafiles/agecondat.html
%
% Datafile Name: Agricultural Economics Studies
% Datafile Subjects: Agriculture , Economics , Consumer
% Story Names: Agricultural Economics Studies
% Reference: F.B. Waugh, Graphic Analysis in Agricultural Economics,
%   Agricultural Handbook No. 128, U.S. Department of Agriculture, 1957.
% Authorization: free use
% Description: Price and consumption per capita of beef and pork
%   annually from 1925 to 1941 together with other variables relevant to
%   an economic analysis of price and/or consumption of beef and pork
%   over the period.
% Number of cases: 17
% Variable Names:
%
%   PBE = Price of beef (cents/lb)
%   CBE = Consumption of beef per capita (lbs)
%   PPO = Price of pork (cents/lb)
%   CPO = Consumption of pork per capita (lbs)
%   PFO = Retail food price index (1947-1949 = 100)
%   DINC = Disposable income per capita index (1947-1949 = 100)
%   CFO = Food consumption per capita index (1947-1949 = 100)
%   RDINC = Index of real disposable income per capita (1947-1949 = 100)
%   RFP = Retail food price index adjusted by the CPI (1947-1949 = 100)
%
% The Data:
YEAR    PBE CBE PPO CPO PFO DINC    CFO RDINC   RFP
1925    59.7    58.6    60.5    65.8    65.8    51.4    90.9    68.5    877
1926    59.7    59.4    63.3    63.3    68  52.6    92.1    69.6    899
1927    63  53.7    59.9    66.8    65.5    52.1    90.9    70.2    883
1928    71  48.1    56.3    69.9    64.8    52.7    90.9    71.9    884
1929    71  49  55  68.7    65.6    55.1    91.1    75.2    895
1930    74.2    48.2    59.6    66.1    62.4    48.8    90.7    68.3    874
1931    72.1    47.9    57  67.4    51.4    41.5    90  64  791

Here's the result of View(beef) as suggested by Patrick:

A: You need to go back and look at the file that you loaded these data into R from. The output from head() suggests that the first variable is YEAR....PBE and that the PBE data has gotten merged with the YEAR variable, probably because of some issue with the delimiters in use in the file you read in. Go back and check the file carefully.
One way to do this from within R is to use count.fields(), which you pass the filename to check. Do read ?count.fields as you will potentially need to set the sep and quote arguments in order to match the file you read the data from. The function will tell you how many fields (variables) it finds; compare this with the known number of variables.
From your edit, it is clear that something like what I describe above has happened:
> names(beef)
[1] "YEAR....PBE" "CBE"         "PPO"         "CPO"         "PFO"
[6] "DINC"        "CFO"         "RDINC"       "RFP"

It seems the file is not all/fully/truly Tab-delimited. I was able to read the bit of data you included with:
beef <- read.table("file.name", header = TRUE, sep = "", comment.char = "%")

> head(beef)
  YEAR  PBE  CBE  PPO  CPO  PFO DINC  CFO RDINC RFP
1 1925 59.7 58.6 60.5 65.8 65.8 51.4 90.9  68.5 877
2 1926 59.7 59.4 63.3 63.3 68.0 52.6 92.1  69.6 899
3 1927 63.0 53.7 59.9 66.8 65.5 52.1 90.9  70.2 883
4 1928 71.0 48.1 56.3 69.9 64.8 52.7 90.9  71.9 884
5 1929 71.0 49.0 55.0 68.7 65.6 55.1 91.1  75.2 895
6 1930 74.2 48.2 59.6 66.1 62.4 48.8 90.7  68.3 874
> str(beef)
'data.frame':   7 obs. of  10 variables:
 $ YEAR : int  1925 1926 1927 1928 1929 1930 1931
     $ PBE  : num  59.7 59.7 63 71 71 74.2 72.1
 $ CBE  : num  58.6 59.4 53.7 48.1 49 48.2 47.9
     $ PPO  : num  60.5 63.3 59.9 56.3 55 59.6 57
 $ CPO  : num  65.8 63.3 66.8 69.9 68.7 66.1 67.4
     $ PFO  : num  65.8 68 65.5 64.8 65.6 62.4 51.4
 $ DINC : num  51.4 52.6 52.1 52.7 55.1 48.8 41.5
     $ CFO  : num  90.9 92.1 90.9 90.9 91.1 90.7 90
 $ RDINC: num  68.5 69.6 70.2 71.9 75.2 68.3 64
     $ RFP  : int  877 899 883 884 895 874 791


text:
Q: Update middleware in Rails Is there any way to MODIFY (NOT replace) a middleware in rails?
So instead of:
config.middleware.delete ::Rack::Cache
config.middleware.use ::Rack::Cache, :metastore => "rails:/", :entitystore => "rails:/", :verbose => false

I want to simply write something like config.middleware.find!(::Rack::Cache).verbose = false.
UPDATE: The reason to do it is because the capybara-webkit prints tons of messages when running from cucumber.

A: I think for this particular middleware, you can set the Rack environment option to be merged with its default configuration as per: http://rtomayko.github.com/rack-cache/configuration

A: I ended up with:
  # Disable annoying Cache messages:
  config.action_controller.perform_caching = true
  config.action_dispatch.rack_cache = {:metastore => "rails:/", :entitystore => "rails:/", :verbose => false}

This worked for my particular case (Rails cache was used by Dragonfly and wasn't inserted anymore).
I don't think there is a way of doing what I originally asked though.


text:
Q: STM32 (SWD) printf not working I'm new using STM32 microcontrollers. I have been trying to use the printf tracing in my code without success, nothing is printed on the console. I can start a debug session, I can place breakpoints on my code, inspect variables and all works as expected but not the printf.
My setup:

I have reimplemented the _write method:
int _write(int32_t file, uint8_t *ptr, int32_t len)
{
/* Implement your write code here, this is used by puts and printf for example */
int i=0;
for(i=0 ; i<len ; i++)
ITM_SendChar((*ptr++));
return len;

}

And placed a breakpoint on:
__STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch)
{
  if (((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL) &&      /* ITM enabled */
      ((ITM->TER & 1UL               ) != 0UL)   )     /* ITM Port #0 enabled */
  {
    while (ITM->PORT[0U].u32 == 0UL)
    {
      __NOP();
    }
    ITM->PORT[0U].u8 = (uint8_t)ch;
  }
  return (ch);
}

ITM->PORT[0U].u8 = (uint8_t)ch; is being executed, but there is no printf ouput on the console.

A: One thing that's not been mentioned is that assuming that all the connections are correct and that the IDE has been properly configured, printf may not show up in the console or may show up but be corrupted if \n isn't added to the printf function. eg.
printf("Hello World!");

Will either not work or show garbage, whereas:
printf("Hello World!\n");

Does work. This is true for STM32s CubeIDE

A: I had the same problem, I solved it by changing some settings.
First take a look at your configuration in the ST_CUBE_MX in the clock configuration in the value of SYSCLK.

And then this same value you must write in the debugger settings, like this:

I run this under Debian 10.

A: There are three extra magic steps to get this working:

*

*Serial Wire View (SWV) tracing must be enabled. You haven't specified, but the IDE you're using looks similar to Atollic TrueSTUDIO. In that IDE, you enable SWV in the Debug configuration by enabling the checkbox shown in this image:

*You must "Start Trace" during every new debug session. In your screenshot it looks like you've already done it by clicking the red round button in the SWV ITM Data Console pane, but to make sure have another look around for a "SWV Console" window and click the red round button.

*And you must connect the SWV pin. SWD only requires GND, SWCLK and SWDIO for debugging. If you also want Trace functionality you need to connect the SWV pin. Confusingly, the SWV pin is often called the SWO pin. It's usually shared with the JTDO JTAG pin. Should be pin 39 (PB3) on the STM32F103 Blue Pill.

A: You will able to print debug info via SWO method or UART-TX (simplier and common):

SWO method:
In the Bluepill MCU (STM32F103), SWO pin is PB3: connect this pin with your stlinkv2 programmer:

Moreover, you will have to use a specific printf using SWO interface (see SWO_PrintString() in this tutorial).

UART-TX method:
Initialize one of the 3 UARTs to send chars through the TX pin and receive the messages in your PC with a well-known USB-UART adapter. Probably, you will use the implemented method in your favorite RTOS or framework to send strings to the UART.

A: This problem can be resolved by matching the clock configuration, system core clock and tge ST link debugger core clock.  The default in the ST-link debugger doesn't match the core clock so we have to manually type and match it.  I resolved my issue with this.


text:
Q: Linux: ip alias versus iproute When setting up a web server with multiple IP-based virtual hosts, I've always used the  eth0:x alias notation in /etc/network/interfaces. The wiki on my hosting provider states however that this is deprecated and one should now use the iproute tools.
Is this correct, and what's the difference between using aliases and using iproute?

A: Yes, device aliases are deprecated, and have been for a long time.  My guess is that they'll probably never go away, because far too many people will go to their graves using aliases because that's what they've always done.
There's not a huge amount of difference between the two approaches, in practice; I've switched to using iproute mainly because it saves me having to think about interfaces -- rather than having to go "which alias has the IP address I want to remove?" or "what's the next alias interface name that's available?" I can just say "oh, I'd like another IP address or four on this interface" and "let's just delete that IP address from that interface".  It's just plain neater, IMO.


text:
Q: Replacing elements in numpy array based on another array I have the following numpy array:
[['CLU20']
 ['CLZ20']
 ['CLH21']]

I also have another array:
['CLU20' 'CLZ20' 'CLH21' 'CLM21' 'CLU21' 'CLZ21' 'CLH22' 'CLM22' 'CLU22']

I need to replace each "x" element of the first array with the element following the same "x" element in the second array.
This is the expected output
[['CLZ20']
 ['CLH21']
 ['CLM21']]

I could do this with a loop using np.where to get the index of every "x" element in the second array, but I guess there's a better way to do this.

A: following_numpy_array = np.array([
    ['CLU20'], ['CLZ20'], ['CLH21']
]) #why not to flat this array? do you need both shapes?

another_array = np.array(['CLU20','CLZ20','CLH21','CLM21','CLU21','CLZ21','CLH22','CLM22','CLU22'])

#find the indices in `another_array` and add 1 (cose we need the follow position)
ids = np.argwhere(following_numpy_array.repeat(len(another_array), axis=1)==another_array)
ids[:,1]+=1

#update
following_numpy_array[ids[:,0], 0] = another_array[ids[:,1]]

Now following_numpy_array is:
array([['CLZ20'],
       ['CLH21'],
       ['CLM21']], dtype='<U5')

Note that if you want to update 'CLU22' it will raise an error because there are no elements after it in another_array


text:
Q: Sails-js is lifting but localhost:1337 not working Sails project is not working. After sails lift command from terminal. I did run the project through the localhost: 1337 port from browser. But its not loading, browser screen is blank. And there is no error message in terminal.
Note: The same project had run very well before few hours in same machine
Please help why this error came suddenly
enter image description here
enter image description here


text:
Q: Python couldn't insert row to MySQL I'm trying to accomplish following query:
sql = "INSERT INTO adr_citydistricts (CityDistrict, CityDistrictRU) VALUES (% (ua) s,% (ru) s);"
data = {'ua': 'ukrainian', 'ru': 'russian'}
cursor.execute (sql, data)

After executing this query, there is no such record in table.
If do the same query in SQLyog, record will exists.
I've also tried:
sql = "INSERT INTO adr_citydistricts (CityDistrict, CityDistrictRU) VALUES ('123 ', '333');"
cursor.execute (sql)
print sql

and there is no row in the table.
The console displays : INSERT INTO adr_citydistricts (CityDistrict, CityDistrictRU) VALUES ('123 ', '333');
Executing this query in SQLyog, normally inserts a row in the table.
I've created another table with the same structure.
Can someone help me, please?

A: You need to cursor.commit() to reflect changes.

9.2.3. Method MySQLConnection.commit()
This method sends a COMMIT statement to the MySQL server, committing
the current transaction. Since by default Connector/Python does not
autocommit, it is important to call this method after every
transaction that modifies data for tables that use transactional
storage engines.


text:
Q: How can I change the font of the row numbers? (listings package) Is there a way to make the row numbers on the left of the code the same font as the code? I believe if you change the default font of the code, the row numbers are still in the default font. I'm using the listings package and changed to the Deja Vu Sans Mono font.
\documentclass[11pt,a4paper]{article} \usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage[onehalfspacing]{setspace}
\usepackage[left=1in, right=1in, top=1in, bottom=1in]{geometry}

\usepackage{DejaVuSansMono}

\usepackage{listings}

\lstset{frame=tb,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\footnotesize\ttfamily},
numbers=left,
numbersep=0pt,
numberstyle=\tiny\color{gray},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}

\begin{document}

\begin{lstlisting}
    Hello
    Hello
    Hello
\end{lstlisting}

\end{document}

A: Just add \ttfamily to your settings for \numberstyle:

\documentclass{article}

\usepackage{xcolor}
\usepackage{DejaVuSansMono}

\usepackage{listings}

\lstset{frame=tb,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\footnotesize\ttfamily},
  numbers=left,
  numbersep=1ex,
  numberstyle={\tiny\color{gray}\ttfamily},
  breaklines=true,
  breakatwhitespace=true,
  tabsize=3
}

\begin{document}

\begin{lstlisting}
Hello
Hello
Hello
\end{lstlisting}

\end{document}


text:
Q: Integer value comparison I'm a newbie Java coder and I just read a variable of an integer class can be described three different ways in the API.  I have the following code:
if (count.compareTo(0)) {
            System.out.println(out_table);
            count++;
    }

This is inside a loop and just outputs out_table.
My goal is to figure out how to see if the value in integer count > 0.
I realize the count.compare(0) is the correct way? or is it count.equals(0)?
I know the count == 0 is incorrect. Is this right? Is there a value comparison operator  where its just count=0?

A: To figure out if an Integer is greater than 0, you can:

*

*check if compareTo(O) returns a positive number:
if (count.compareTo(0) > 0)
     ...

But that looks pretty silly, doesn't it? Better just...

*use autoboxing1:
if (count > 0)
    ....

This is equivalent to:
if (count.intValue() > 0)
    ...

It is important to note that "==" is evaluated like this, with the Integer operand unboxed rather than the int operand boxed. Otherwise, count == 0 would return false when count was initialized as new Integer(0) (because "==" tests for reference equality).
1Technically, the first example uses autoboxing (before Java 1.5 you couldn't pass an int to compareTo) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.

A: Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.
Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:
if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.
If you're having trouble understanding this, check out the link above, or imagine it's doing this:
if (count.intValue() > 0) { }

A: Integers are autounboxed, so you can just do
if (count > 0) {
    ....
}

A: It's better to avoid unnecessary autoboxing for 2 reasons.
For one thing, it's a bit slower than int < int, as you're (sometimes) creating an extra object;
void doSomethingWith(Integer integerObject){ ...
  int i = 1000;
  doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));

The bigger issue is that hidden autoboxing can hide exceptions:
void doSomethingWith (Integer count){
  if (count>0)  // gets compiled into count.intValue()>0

Calling this method with null will throw a NullPointerException.
The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare() or intValue(), and if you've got the primitive just check the value directly.

A: You can also use equals:
 Integer a = 0;

 if (a.equals(0)) {
     // a == 0
 }

which is equivalent to:
 if (a.intValue() == 0) {
     // a == 0
 }

and also:
 if (a == 0) {

 }

(the Java compiler automatically adds intValue())
Note that autoboxing/autounboxing can introduce a significant overhead (especially inside loops).

A: One more thing to watch out for is if the second value was another Integer object instead of a literal '0', the '==' operator compares the object pointers and will not auto-unbox.
ie:
Integer a = new Integer(0);
Integer b = new Integer(0);
int c = 0;

boolean isSame_EqOperator = (a==b); //false!
boolean isSame_EqMethod = (a.equals(b)); //true
boolean isSame_EqAutoUnbox = ((a==c) && (a.equals(c)); //also true, because of auto-unbox

//Note: for initializing a and b, the Integer constructor
// is called explicitly to avoid integer object caching
// for the purpose of the example.
// Calling it explicitly ensures each integer is created
// as a separate object as intended.
// Edited in response to comment by @nolith

A: well i might be late on this but i would like to share something:
Given the input:
    System.out.println(isGreaterThanZero(-1));
public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

Returns false
public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

Returns true
So i think in yourcase 'compareTo' will be more accurate.


text:
Q: How to get only the date part? I'm trying to get only the date part in the file name. For eg:
abc-xyz20140417.tar
abc-20120420.tar
abc-efghi19800815.tar

Output needed:
20140417
20120420
19800815

A: If the number characters in the filenames are only the date which is required for you, then here is an example:
root@localhost:~[0]$ ls -1 abc-*
abc-20120420.tar
abc-efghi19800815.tar
abc-xyz20140417.tar
root@localhost:~[0]$ ls -1 abc-*  | sed 's/[^0-9]//g'
20120420
19800815
20140417

Hope it helps.

A: Assuming the date is always the last 8 characters before ".tar", this will work with any sed on any OS:
$ sed 's/.*\(........\).tar$/\1/' file
20140417
20120420
19800815


text:
Q: Laravel http (curl) throws RequestException while creating the response I have a simple curl API request in a project that is based on Laravel 9 by using XAMPP. I use the Http::withHeaders(array("key" => "value))->post("api-url") to call the API (see Laravel documentation).

Http::withOptions(['debug' => fopen('php://stderr', 'w')])->withHeaders($header)->get($url)

The handling is to get a JSON from an external API. The API is valid (https://api.clearstream.com/) and I am authenticated via a registered API key. (Other API-Endpoints are working fine)
The problem I have is that I get the following deatiled Laravel error:
Laravel - DetailedCodeOfFail
When I use the http option "debug" I get the following error:

[object] (InvalidArgumentException(code: 0): "default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval'; script-src-elem
'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self'
'unsafe-inline'; style-src-elem 'self' 'unsafe-inline'; media-src
'self'; frame-src 'self'; worker-src 'self'; connect-src 'self';
manifest-src 'self'; img-src 'self' data:; font-src 'self';
form-action 'self' ; object-src 'none'; block-all-mixed-content;" is
not valid header value at
\vendor\guzzlehttp\psr7\src\MessageTrait.php:263)
\vendor\guzzlehttp\psr7\src\MessageTrait.php(209):
GuzzleHttp\Psr7\Response->assertValue('default-src 'se...')
[internal function]:
GuzzleHttp\Psr7\Response->GuzzleHttp\Psr7\{closure}('default-src
'se...')

Any idea why the response fails?

*

*all versions are nearly up to date

A: You can get this error when the third-party api you are consuming sends header values that don't meet guzzlehttp/psr7's regex check.  This check was added to the psr7 library back in 2022-03-20 but will cause more headaches for developers now that guzzlehttp/guzzle includes the latest psr7 (2022-06-20).
There is a bug report for this issue.


text:
Q: Chrome Extension: executeScript on tab I've recently started developing my first Google Chrome Extension, and am experiencing an issue that I'm not entirely sure how to fix.
In my script, I'm checking if a tab is open to a specific website, and, if so, I'm performing the following code:
chrome.tabs.update(tab.id, {active: true});

// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
    "code": "messageOpen(15, false);"
});

The above code should update the tab setting it as active and should then attempt to execute a function called messageOpen(). The problem I'm experiencing is that the function messageOpen() exists as a function that was included in the <HEAD> of my website, but not my extension.
Hence, when attempting to execute the messageOpen() function, I'm receiving this error:
Uncaught ReferenceError: messageOpen is not defined

I'm 100% positive that the messageOpen() function works if I browse the website regularly, but when using executeScript, it's as if the extension is incapable of running functions that have already been loaded in my active tab.
Does anybody have some suggestions or alternatives?

A: This happens because content scripts cannot interact with the window object of the page they are injected to. If you want to execute a script that uses your messageOpen() function then you'll have to inject that code into the page context using a <script>, like this:
var myScript = document.createElement('script');
myScript.textContent = 'messageOpen(15, false);';
document.head.appendChild(myScript);

So, if you want to inject this code using the executeScript() method and the "code" property you can do it like this:
chrome.tabs.update(tab.id, {active: true});

// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
    "code": "var myScript = document.createElement('script');"
        + "myScript.textContent = 'messageOpen(15, false);';"
        + "document.head.appendChild(myScript);"
});

NOTE: since January 2021, use Manifest V3 with chrome.scripting.executeScript() instead of chrome.tabs.executeScript().

A: Here's the working sample to execute js on a tab for Manifest v3:

chrome.scripting.executeScript({
  target: { tabId: tab.id },
  func: () => {
    // write your code here
    document.body.style.backgroundColor = "red";
  },
});

You also need to add scripting permission to Manifest.json
 permissions: [
    'scripting', // to execute js into a tab
  ],


text:
Q: slideDown drop down menu so I'm trying to make a nice little effect on my drop down menu, but i don't know the right way to use the hover and slideDown function
$('nav > div > ul > li').hover(function() {
    $('nav > div > ul > li > ul').stop(true, true).slideDown(200);
}, function() {
    $('nav > div > ul > li > ul').stop(true, true).slideUp(200);

});

that is what i have now, this don't work it shows my submenu regardless of what li I'm hovering, i want it to work so it is on the element and only the element that has the submenu.
EDIT: FIDDLE

A: Try this fiddle
http://jsfiddle.net/MzJNT/2/
I would suggest adding some ID for selectors like below
JS
     $( document ).ready(function() {
$('#parent').hover(function() {
    $('#submenu').stop(true, true).slideDown(200);
}, function() {
    $('#submenu').stop(true, true).slideUp(200);

});

 });

I am sure there is a more efficent way to do this but this is a good start.
EDIT
I think i found the actual issue with why it isn't sliding like you want it too, you have a style that is making it show instead of using the JS to make it show up
Remove this...
     nav > div > ul > li:hover > ul {
     display: block;
     }

or try this fiddle http://jsfiddle.net/MzJNT/9/


text:
Q: Button ClickEvent not triggered when textArea onFocus I need to trigger button ClickEvent when focusing on textArea input.
PS : My textArea with some styles when it's focused it becomes maximized
The example is below :
https://stackblitz.com/edit/angular-ivy-zy9sqj?file=src/app/app.component.html

A: As soon as you click on the button your textarea loses focus and returns back to it's initial height, which is why the click gets missed. You must somehow not let the textarea go back to it's initial height as soon it loses focus, or maybe delay it, so that the button gets clicked first.
One approach would be to set the textarea height to its maximized height when the button is hovered, using the JavaScript mouseover event.
And, once the button is clicked, change it back to its initial height.
See if the below workaround works for you!
HTML:
<textarea id="text">test</textarea> <br/>
<button id="button">Change</button>

CSS:
textarea{
  height: 100px; /* initial height */
}
textarea:focus {
  height: 200px; /* maximized height */
}

JavaScript:
document.querySelector('#button')
        .addEventListener('click', function () {
            document.querySelector('#text').value += 'changed';
            document.querySelector('#text').style.height = '100px';
});

document.querySelector('#button')
        .addEventListener('mouseover', function () {
            document.querySelector('#text').style.height = '200px';
});

jsFiddle: https://jsfiddle.net/ew86fb5p/
hope that helps!


text:
Q: Where clause failed on three level nested include I has four modelDBList: AlarmsDB, MonitorSpotDB, MonitorGroupDB, UserDB
these modelDB has reference as list:
AlarmDB.belongsTo(MonitorSpotDB);
MonitorSpotDB.belongsTo(MonitorGroupDB);
MonitorGroupDB.hasMany(MonitorSpotDB);
UserDB.belongsToMany(MonitorGroupDB, { through: MonitorGroupUserDB});
MonitorGroupDB.belongsToMany(UserDB, { through: MonitorGroupUserDB,});

Now I want to get alarm relative user, so I use sequelize write code like:
  public async getAlarms(limit: number, offset: number, whereQuery: any, whereUser: any): Promise<{ count: number, rows: Alarm[] }> {
    let alarms = await AlarmDB.findAndCount({
        limit: limit,
        offset: offset,
        order: [
            ["createdAt", "desc"],
        ],
        where: whereQuery,
        include: [
            {
                model: MonitorSpotDB, as: "monitorSpot", attributes: ["id", "name", "monitorGroupId"], required: true,
                include: [{
                    model: MonitorGroupDB, as: "monitorGroup", attributes: ["id", "name"], required: true,
                    include: [{ model: UserDB, as: "users", attributes: ["id", "name"], where: whereUser }],
                }],
            },
        ],
    });
    return alarms;
}

but I get null array, If I delete
include: [{ model: UserDB, as: "users", attributes: ["id", "name"], where: whereUser }],

I can get data, I don't what to cause this problem, this is run error


text:
Q: How do I change the "root" directories name in JTree? I have a simple implementation of JTree:
tree1 = new JTree(LibObj.collectionToStringArray(LibObj.books));
tree1.setRootVisible(true);
scrollPane2 = new JScrollPane(tree1);
scrollPane2.setPreferredSize(new Dimension(350, 300));
panel.add(scrollPane2);

LibObj.collectionToStringArray(LibObj.books) is a method in another class that takes a collection and turns it into an array of strings
Everything is displaying as expected but the root directory is named "Root". How do I change the name? (I want it to be called Books)

A: Using the constructor JTree(TreeNode node) would give you the chance to create your own root node.
Just like this:
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node name");
for( String book : booksArray ) {
    DefaultMutableTreeNode bookNode = new DefaultMutableTreeNode(book);
    rootNode.add(bookNode);
}

tree1 = new JTree(rootNode);
tree1.setRootVisible(true);
[...]


text:
Q: Modifying a list with user input, selecting the item by index How can I select an item from this list by it's index and modify it back to the list with an update?
mylist = ['CHECK EMAIL', 'OPEN PROJECT', 'PRIORITIZE PROJECT']
i = 1
for list in mylist:
    print i, list
    i = i + 1

while True:

    elif ToDo == 'R':
        index = raw_input('What would you like to remove from the list?').upper()

        if index in mylist:
            mylist.remove(index)
            print "It has been removed. What would you like to do now?\n"
            print "Your New ToDoList :"
            print"-----------"
            i = 1
            for index in mylist:
                print i, list
                i = i + 1
        else:
            print "THAT doesn't exist in this list!! Try again!"

A: Two parts in that question:
"How can I select an item from this list by it's index"
Assuming index is the index, and mylist is the list, this is achieved with mylist[index]. Obviously, index has to be (at least) an integer. In your current code, it comes from raw_input that returns a string. So convert that string to an integer using, e.g., index = int(index).
"and modify it back to the list with an update?"
Assuming x contains the new value: mylist[index] = x.
If you want to first remove the item, keep going on with mylist.remove(index), and if you want to insert something new at that same position, use mylist.insert(index, x).
More on lists: https://docs.python.org/2/tutorial/datastructures.html (Python 2, as you used print i, list and not print(i, list). I suggest you to move to Python 3 as well).

A: Please try below code .. i hope it meets your requirement.
mylist = ['CHECK EMAIL', 'OPEN PROJECT', 'PRIORITIZE PROJECT']
i = 1
for list in mylist:
    print(i,list)
    i = i + 1
while mylist:
index = int(input('What would you like to remove from the list? \n'))
print(index)

if index <= len(mylist):
    del mylist[index - 1]
    print("It has been removed. What would you like to do now?\n")
    print ("Your New ToDoList :")
    print("-----------")
    i = 1
    for index in mylist:
        print(i,index)
        i = i + 1
else:
    print("THAT doesn't exist in this list!! Try again!")


text:
Q: Split the list into lines I have a full_list as follows:
full_list = [[[-180, 90], [-180, 80], [-175, 80], [-175, 90]], [[-180, 80], [-180, 70], [-175, 70], [-175, 80]], [[-180, 70], [-180, 60], [-175, 60], [-175, 70]], [[-180, 60], [-180, 50], [-175, 50], [-175, 60]]]

How can I produce the list called ans as follows?
ans = [[[-180, 90], [-180, 80], [-175, 80], [-175, 90]],
       [[-180, 80], [-180, 70], [-175, 70], [-175, 80]],
       [[-180, 70], [-180, 60], [-175, 60], [-175, 70]],
       [[-180, 60], [-180, 50], [-175, 50], [-175, 60]]]

Both list are same, only difference is the later one is splitted into lines.

A: Are you talking about pretty printing? Your list is already like that.
>>> full_list = [[[-180, 90], [-180, 80], [-175, 80], [-175, 90]], [[-180, 80], [-180, 70], [-175, 70], [-175, 80]], [[-180, 70], [-180, 60], [-175, 60], [-175, 70]], [[-180, 60], [-180, 50], [-175, 50], [-175, 60]]]

>>> from pprint import pprint
>>> pprint(full_list)
[[[-180, 90], [-180, 80], [-175, 80], [-175, 90]],
 [[-180, 80], [-180, 70], [-175, 70], [-175, 80]],
 [[-180, 70], [-180, 60], [-175, 60], [-175, 70]],
 [[-180, 60], [-180, 50], [-175, 50], [-175, 60]]]

A: As mentioned in another answer, pprint is the natural way to go.
But depending on your precise needs, you might do this as well:
print(*full_list, sep='\n')

# Output:
[[-180, 90], [-180, 80], [-175, 80], [-175, 90]]
[[-180, 80], [-180, 70], [-175, 70], [-175, 80]]
[[-180, 70], [-180, 60], [-175, 60], [-175, 70]]
[[-180, 60], [-180, 50], [-175, 50], [-175, 60]]

To customise a bit, you can use range:
def my_custom_printer(full_list):
    for i in range(0, len(full_list), 2):
        try:
            print("{}, {}".format(full_list[i], full_list[i+1]))
        except IndexError:
            # len(full_list) is odd, so just print the last index
            print(full_list[i])

my_custom_printer(full_list)

# Output:
[[-180, 90], [-180, 80], [-175, 80], [-175, 90]], [[-180, 80], [-180, 70], [-175, 70], [-175, 80]]
[[-180, 70], [-180, 60], [-175, 60], [-175, 70]], [[-180, 60], [-180, 50], [-175, 50], [-175, 60]]

But then it gets a bit dirty... Mainly because the actual data and its representation are not strictly consistent anymore


text:
Q: Elasticsearch - script_fields error I am using elastic 1.5.0. When I run this block in the query:
"script_fields" : {
        "test1" : {
            "script" : "doc['actual_air_time'].value * 2",
             "lang":"groovy"
        }
    }

I get an error:
nested: ScriptException[dynamic scripting for [groovy] disabled]

How can I enable groovy script for elastic? Is there any other way to evaluate "test1" without using script_fields?

A: You can enable it in elasticsearch.yml, by setting:
script.groovy.sandbox.enabled: true

For more details see: http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html


text:
Q: MacroPDF417 barcode reading FileID from codewords I'm reading the ISO spec for MacroPDF417, FileID field. It says:

Each codeword in the file ID can have a value between 0 and 899, effectively making the file ID a series of base 900 numbers. Each codeword of the series is transmitted as the 3-digit ASCII representation of its decimal value.

The spec has an example as follows:

File ID = 17base900 53base900

Which value in codewords is [017] [053].
Can someone explain me, is the fileID value 1753? Or not?
If it's 1753, how to can you read it from codewords? How should the zero before 53 be interpreted? Should it be removed?

A: No, FileId is not 1753.
As per spec FileId is a series of base 900 numbers, so the above is a series of 017, 053 and not a single number 1753.
We might wright this as 17base900 53base900, this is not equal to 1753 in base 10.
I did not find any tool to read the fileId from a barcode however you can check this value in the codewords using this tool http://online-barcode-reader.inliteresearch.com/default.aspx.
This will be written in codewords as 928nnnnn\017\053 where nnnnn is segment id.
If you are setting the fileId by converting the base 10 number to base 900 numbers then you might convert the codewords back to base 10 numbers to get the originally set value. If you want help in converting to base 10, check this link http://mathbits.com/MathBits/CompSci/Introduction/tobase10.htm.


text:
Q: hardware acceleration FFMPEG on Windows I've installed the latest gyan.dev full build on Windows 10,
I want to convert a sequence of png to an h265 .mp4 movie
and I'm successfully using this command
ffmpeg -r 60 -f image2 -s 3840x2160 -i TEST_%04d.png -vcodec libx265 -crf 1  -pix_fmt yuv440p -hwaccel cuvid Y:\TEST.mp4
I would like to take advantage of the hardware acceleration of my RTX2080 during the process,
but I can't find any resource or command to add since -hwaccel which I supposed to be enough,
doesn't works.
Any hint is highly appreciated!
Best and stay safe.

A: libx265 is a software encoder. It does not support hardware encoding.
What you want is to use one of the hardware encoders. For hardware h.264 you will want to use the h264_nvenc video codec or for h.265 the hevc_nvenc
ffmpeg -r 60 -f image2 -s 3840x2160 -i TEST_%04d.png -vcodec hevc_nvenc -crf 1  -pix_fmt yuv440p -hwaccel cuvid Y:\TEST.mp4
You can list the encoders available using ffmpeg.exe -encoders and look for ones that mention NVIDIA in the list. For my ffmpeg I get the following Nvidia encoders in that list
 V..... h264_nvenc           NVIDIA NVENC H.264 encoder (codec h264)
 V..... nvenc                NVIDIA NVENC H.264 encoder (codec h264)
 V..... nvenc_h264           NVIDIA NVENC H.264 encoder (codec h264)
 V..... nvenc_hevc           NVIDIA NVENC hevc encoder (codec hevc)
 V..... hevc_nvenc           NVIDIA NVENC hevc encoder (codec hevc)

And you can list the encoder parameters using, for example, ffmpeg -h encoder=hevc_nvenc

A: Thanks to @Mokubai, @Gyan and @llogan for their answers.
In case someone wants to use ffmepg hwaccel for h265 to h264 conversion, use this:
ffmpeg -encoders | findstr /ic:"NVIDIA"

You should see:
 V....D h264_nvenc           NVIDIA NVENC H.264 encoder (codec h264)
 V....D hevc_nvenc           NVIDIA NVENC hevc encoder (codec hevc)

ffmpeg command:
ffmpeg.exe -vsync 0 -hwaccel cuda -i <input_file> -map 0  -c:a copy -c:v h264_nvenc -pix_fmt yuv420p -preset hq <output_file>

It reduced the runtime by 4X for me, for a 30-minute video, on a GTX1060 card.
Cheers


text:
Q: Acessing folder paths in google collab I'm trying to use google collab for its tensorflow environment, but the path system looks a bit complex. What i am trying is to dynamically access the path to my train and validation folders that has cats and dogs in each folder, for classification. I am using Keras/Tensorflow, thus i am trying to access these folders from my google drive.
my cd path is currently like this: cd "/content/drive/My Drive/data"

Where my folder data contains train and validation folders
What i am doing is trying to simply use some data augmentation for train and validation:
from google.colab import files
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
from keras.preprocessing import image

img_width, img_height = 150, 150

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 1000
nb_validation_Samples = 100
epochs = 50
batch_size = 20

if K.image_data_format() == 'channels_first':
   input_shape = (3, img_width, img_height)
else:
   input_shape = (img_width, img_height, 3)

train_datagen = ImageDataGenerator(
    rescale= 1. / 255,
    shear_range = 0.2,
    zoom_range=0.2,
    horizontal_flip=True
)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
   train_data_dir,
   target_size=(img_width, img_height),
   batch_size=batch_size,
   class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode="binary")

I get the following error: FileNotFoundError: [Errno 2] No such file or directory: 'data/train'
I have already mounted my drive, but i have no idea how to access my google drive folder as i would do regurarly using jupyter notebook for instance, when the folder would be in the same path as the notebook.

A: First mount drive:
from google.colab import drive
drive.mount('/content/drive')

And then use:
train_data_dir = '/content/drive/My Drive/data/train'
validation_data_dir = '/content/drive/My Drive/data/validation'


text:
Q: RangeError: radix must be an integer at least 2 and no greater than 36 When I try and convert milliseconds to a string I get an error saying

RangeError: radix must be an integer at least 2 and no greater than 36

I am using the Datejs script and using the toString function.
var date2 = (returnDay + time);
alert("Return Date is:"+ date2.toString("MMM-dd-yy"));

The return day is todays date
var returnDate = new Date().getTime();

and the time is the answer. It is all in milliseconds.
time=14*24*60*60*1000

When I go to convert the milliseconds to a String I get the error
Can anyone help?


text:
Q: Data in Array of earlier pocket is being deleted Dim n As Integers
Public AAA() As Integer
Public QQQ() As String

Sub Initialise()
n = 0
End Sub

Sub WrongAnswer(oShape As Shape)
A = oShape.TextEffect.Text
SendWrongAnswer
End Sub

Sub SendWrongAnswer()
ReDim QQQ(500)
QQQ(n) = Q

ReDim AAA(500)
AAA(n) = A

n = (n) + 1
End Sub

When I make the array AAA() and QQQ() and store data in the pockets, the data in earlier pockets becomes "0" or "".
If AAA(1) = 50 and then when the macro stores AAA(2) = 34, then AAA(1) becomes 0.

A: Move ReDim statement to Sub Initialise method then it will work.
Sub Initialise()
n = 0
ReDim AAA(500)
ReDim QQQ(500)
End Sub

EDIT: If you want to preserve the existing data when you redimension it then use preserve keyword.
ReDim Preserve AAA(500)


text:
Q: Pyspark 3.2.0 - Mlib Pipeline - after using load() function Transform() returning empty dataframe
*

*Using Windows10 and Hadoop 2.7.

*Able to get predictions using transform() with Python 3.6 & 3.7 using Apache Spark 2.4.4 and 2.4.7.

*After upgrading to Python 3.8.5 and Apache spark 3.2.0:
Tried saved pipeline model,
Model load and
Used transform function to get prediction. ** retuning empty dataframe.

Able to load saved pipeline model, checked stages in pipeline object.
model.write().overwrite().save(saveDir)
tm = PipelineModel.load(saveDir_model)
spark_tdf = spark.createDataFrame(testData)
predDF = tm.transform(spark_tdf)


text:
Q: Latest maven dependency version for pentao kettle I want to mavenize pentaho kettle plugin development, and using below xml code in pom.xml to upgrade the current version 4.4.0 stable to the latest one.
I Used 6.0.0.1-364 , but 6.1 is stable latest according to pentaho site. Then what is the corresponding maven dependency for the same?
Here http://repo.pentaho.org/content/grou...e/kettle-core/ I can see the list of kettle maven dependencies . But which one is latest and stable version ? Please help me understand
<dependencies>
<dependency>
<groupId>pentaho-kettle</groupId>
<artifactId>kettle-core</artifactId>
<version>6.0.0.1-364</version>
</dependency>

<dependency>
<groupId>pentaho-kettle</groupId>
<artifactId>kettle-engine</artifactId>
<version>6.0.0.1-364</version>
</dependency>

<dependency>
<groupId>pentaho-kettle</groupId>
<artifactId>kettle-ui-swt</artifactId>
<version>6.0.0.1-364</version>
</dependency>
</dependencies>

A: AFAK you should use the maven dependency corresponding to the PDI version installed in your system. So if you are using Kettle version of 6.0.0.1-364 then use the same maven dependency. Now from the above link, it seems that the latest version is 6.1.0.2-208. If you are looking for the latest version, it is 6.1.0.2
POM link: http://repo.pentaho.org/content/groups/omni/pentaho-kettle/kettle-core/6.1.0.2-208/kettle-core-6.1.0.2-208.pom
Hope it helps :)


text:
Q: Better approach: conditionally add/remove views or change visibility I want to use a BottomSheetLayout for different cases like as a SearchBar with search results when user is actively searching and also to show a RecyclerView with different items, buttons, etc. when user is not searching.
In general, this requires different views which
has to be conditionally shown in the BottomSheetLayout.
One approach I know is to create the corresponding views and change the visibility. Second approach is to add/remove views to the parent view. Let's say that the container is a ConstraintLayout.
I want to know what is the best approach in respect to performance, usability and complexity. Maybe there are other possibilities that I don't know yet.


text:
Q: Weird PF_Handle declaration in Adobe After Effects SDK I 'm trying to host After Effects plugins in my video editor.
On implementing some of the Adobe Callbacks, there 's a suite (a set of function pointers) that allocate memory, of type PF_Handle. This type has a weird declaration of
       typedef void        **PF_Handle;
A double pointer. The function pointers I am requested to implement are described here.
PF_Handle (*host_new_handle)(A_HandleSize size);
void (*host_lock_handle)(PF_Handle pf_handle);
void (*host_unlock_handle)(PF_Handle pf_handle);
void (*host_dispose_handle)(PF_Handle pf_handle);

Nothing would be weird if the PF_Handle was a plain void*, I would simply call new/delete and cast the pointer. Indeed, the same plugin's code I am debugging takes that pointer, locks it, and uses it directly. But in the very same plugin later,I see code like this:
`return *(PF_Pixel**)m_bufH;`

m_bufH is PF_Handle which was allocated by a call to host_new_handle. This means that the plugin expects a double pointer. No locking function is called and the plugin attemps to access the double pointer data, failing of course.
What could be the issue?
What could happen here? What's the meaning of locking and unlocking a double pointer?

A: A handle points to movable memory.  The memory may be moved by the memory manager, invalidating the pointer you have.  In order to create a handle, use the API provided by the memory manager — otherwise the manager will not know how to move the allocated memory.  Locking the handle protects the memory from being used and gives you a pointer you can use while the handle is locked.  You should not keep handles locked longer than strictly necessary to access the memory, otherwise you defy the purpose of the memory manager, causing resource depletion and other problems.  Accessing an unlocked handle through a double dereference is possible under condition that the compiler does not optimise it out.  And it is slower than locking, unless you do just one simple thing.


text:
Q: Mongodb: How to Migrate Mongodb database from older version? I was upgraded my mongodb version from 2.6 to 4.1 and also I take backup my all the database json data to my system and restore it when the updation
is completed.
But the problem in Robomongo tool it show all the database but inside of that all the collections and schemas are empty.
what can I do?

A: You can follow the upgrade path:

To upgrade an existing MongoDB deployment to 4.0, you must be running a 3.6-series release.
To upgrade from a version earlier than the 3.6-series, you must successively upgrade major releases until you have upgraded to 3.6-series. For example, if you are running a 3.4-series, you must upgrade first to upgrade first to 3.6 before you can upgrade to 4.0.


text:
Q: Grabbing specific indices of a list Is there a way to grab specific indices of a list, much like what I can do in NumPy?
sample = ['a','b','c','d','e','f']
print sample[0,3,5]
>>>['a','d','f']

I've tried Googling this, but I couldn't find a good way to word my issue that resulted in relevant results...

A: You can use a list comprehension:
>>> sample = ['a','b','c','d','e','f']
>>> [sample[i] for i in (0, 3, 5)]
['a', 'd', 'f']

Or, something I quickly made:
>>> class MyList(list):
...     def __getitem__(self, *args):
...             return [list.__getitem__(self, i) for i in args[0]]
...
>>> mine = MyList(['a','b','c','d','e','f'])
>>> print mine[0, 3, 5]
['a', 'd', 'f']


text:
Q: Detect & Limiting Direction of Scrolling A website I recently stumbled across -
http://www.nuabikes.com/
Nuabike.com can detected & limit the direction the amount their users can scroll along the y-axis which then locks the page/panel into a position before moving onto another section of the website. (See link above)
Would anyone have an idea on how this has been created or know of any plugin's that achieves this?
I came across the plugin called jQuery Panel Snap however it doesn't limit the amount of the scrolling along the y-axis and results in the user being able to pass/miss different sections of my website.
Any help would be greatly appreciated.


text:
Q: Electrode shape in a triggered spark gap? I was reading about spark gaps which are triggered with a third electrode, and I think that the concept is pretty straightforward, but the resource described the usage of a third electrode which would be shaped like a ring or washer:

The article didn't really describe why the trigger electrode would be shaped like a disk instead of, say, a wire or some other pointed shape.  Is a ring shaped electrode a more useful shape for causing a discharge, or are trigger electrodes just generally made this way?

A: The electric field of a cone or point looks like this:

The electric field of a ring or disk simmilar to the one shown above looks like this:

Source: https://demonstrations.wolfram.com/ElectricFieldAroundAChargedRing/
The field through the ring is symmetric, when activated would most likely draw down the field uniformly through the axis of the spark gap and lead to a break down of voltage in the middle. And odds are that it would be best for the spark to not touch the ring.
A point or cone off to one side would lower the electric field outside of the axis of the spark gap, and is not symmetric (if there is only one off to the side).


text:
Q: Why am I not able to access an attribute from an inherited class? Given the following classes:
class DataAccessLayer():

    def __init__(self):
        self.engine = create_engine(CONN_STRING, pool_size=95, max_overflow=0)
        self.connection = self.engine.connect()

class DataAccessLayerParallel(DataAccessLayer):

    def __init__(self):
        session_factory = sessionmaker(bind=self.connection)

I try to create an instance of DataAccessLayerParallel as follows:
dal = DataAccessLayerParallel()

However, I get the error:
Exception has occurred: AttributeError
'DataAccessLayerNonParallel' object has no attribute 'connection'

I assume this is because the __init__ method from DataAccessLayer does not run when it is inherited? How would I ensure I can get access to the connection attribute?

A: You need to call the parent constructor with super.
Like so:
class DataAccessLayer():

    def __init__(self):
        self.engine = create_engine(CONN_STRING, pool_size=95, max_overflow=0)
        self.connection = self.engine.connect()

class DataAccessLayerParallel(DataAccessLayer):

    def __init__(self):
        super(DataAccessLayerParallel, self).__init__()
        self.session_factory = sessionmaker(bind=self.connection)


text:
Q: Finding the p-values for one sample t-test in different cases Calculate and interpret the $p-$ value in the following situations:
(a) one-sample $t$ - test for testing
(i) $H_{0}: \mu=\mu_{0}$ vs $H_{1}: \mu \neq \mu_{0}$
(ii) $H_{0}: \mu \leq \mu_{0}$ vs $H_{1}: \mu>\mu_{0}$
(iii) $H_{0}: \mu \geq \mu_{0}$ vs $H_{1}: \mu<\mu_{0}$
when $n=10$ and the observed value
$$
t_{\mathrm{obs}}=\frac{\sqrt{n}\left(\bar{x}_{n}-\mu_{0}\right)}{\sqrt{\frac{1}{n-1} \sum_{i=1}^{n}\left(x_{i}-\bar{x}_{n}\right)^{2}}}=2.2
$$
(b) the same setting but with a test based on the CLT-approximation of the distribution of $t_{\text {obs }}$
(c) likelihood ratio test when the observed value of the test statistic is 10 and there are
(i) 1 ,
(ii) 5 ,
(iii) 10
degrees of freedom.

I have just started to study P-vlaue (from Cassella and Berger), I am having difficulty in solving this problem.
For the part (a) using following steps I think I can find the required p value:

*

*Calculate the sample mean.
$\overline{x}\ =\ \frac{x_1\ +\ x_2\ +\ \cdots\ +\ x_n}{n}$

*Calculate the sample standard deviation.
$\hat{\sigma}\ =\ \sqrt{\frac{(x_1\ -\ \overline{x})^2\ +\ (x_2\ -\ \overline{x})^2\ +\ \cdots\ +\ (x_n\ -\ \overline{x})^2}{n\ -\ 1}}$

*Calculate the test statistic.
$t\ =\ \frac{\overline{x}\ -\ m_0}{\hat{\sigma}/\sqrt{n}}$

*Calculate the probability of observing the test statistic under the null hypothesis. This value is obtained by comparing t to a t-distribution with $(n\ -\ 1)$ degrees of freedom. This can be done by looking up the value in a table, such as those found in many statistical textbooks, or with statistical software for more accurate results.
$p\ =\ 2\ \cdot\ Pr(T\ >\ |t|)$    (two-tailed)
$p\ =\ Pr(T\ >\ t)$    (upper-tailed)
$p\ =\ Pr(T\ <\ t)$    (lower-tailed)

But I have no idea how to calculate p-values in case for part (b) and part (c).
Any hint or suggestion will be very helpful.


text:
Q: Best practice for implementing long-running searches with REST As part of a REST Service, I need to implement a search call. The basic idea is that the user can POST a new search, and GET the results:
POST http://localhost/api/search
GET http://localhost/api/search?id=123

However, my search may run a few minutes, and return partial results until it is done. That is, the GET-Request would return something like:
status: running
results: a, b, c.

while the next GET-Request might return
status: completed
results: a, b, c, d, e.

This contradicts the semantics of a RESTful GET request. The request should always return the same result when called several times. For example, when the user uses a caching proxy, the full results might never be delivered to the user.
Question: Is there any way to provide a truly RESTful implementation for long running searches with partial results?

A: While the search is executing, you could set the appropriate response headers (e.g. Expires or max-age) to indicate that the response should not be cached (HTTP/1.1 14.9.3, 13.4).
Once the search result is complete, you could then send a more appropriate Expires / max-age  header to allow or extend the cacheability of the result.
The burden would be on the client to re-query the resource until its search status is complete. The client could maybe use the value of the Expires header to determine when it should re-query for updated results.
Alongside of this, you could also use a custom 2XX status code to indicate that the result is not yet complete. Maybe a HTTP/1.1 299 In Progress, or whatever makes sense. The spec indicates that HTTP status codes are extensible.

For the record, your statement:

This contradicts the semantics of a RESTful GET request. The request should always return the same result when called several times.

is not true for GET requests - resources can change. That GET requests are idempotent only means that "...the side-effects of N > 0 identical requests is the same as for a single request". [spec]

A: It's not a problem if the first GET request returns partial results, and the second GET request returns the full results. That's because the first GET request doesn't cause the result of the second request to change: That request would have returned the full results, even if the first GET hadn't been issued. "idempotent" doesn't mean identical results. It means that the first GET doesn't affect the second GET.
It would be a problem if the first GET request returned partial results, and the second GET would return the remaining results (first GET returns A, B, C; second GET returns D, E, F). Here the first GET changes the second result, so it's not RESTful.

A: A few days ago I happend to stumble upon a blog post over at reddit that deals with your problem. You might want to check it out: Bill Higgin's RESTy long-ops.
Happy reading.

A: Maybe not the most elegant answer, but will get around caching proxies:  Just don't send the same query twice.  Add a timestamp to the query (&time=1318355458).  This way, each request is unique (you could also add milliseconds to the time if you're requesting > 1hz).
As for following the doctrine of "The request should always return the same result when called several times", it seems logically contradictory to the goal of returning partial results at different times for the same query.

A: Could you do a wait instead of a poll if you just want the full results?
Why can't you provide a resource as part of your POST that will get the results PUT to it?  You're providing a 'call back' REST interface so, rather than polling, the client process waits for a PUT to the provided resource.  You can then either GET the results or the results could be included in the PUT.


text:
Q: Feature request: Provide search room option in chat mobile version The mobile version of chat does not have a search option:

And all contains 1406 pages.
Please provide a search option in the top bar (like the filter rooms search bar on full site).


text:
Q: XMLHttpRequest.status is "0" for AJAX Request I am trying to create an app in Javascript that fetches data from a barcode database API (http://upcdatabase.org/api). When I make the AJAX requests, the GET requests are getting through to the API. I can see from the API's website how many requests I've made.
However, I am getting an XMLHttpRequest.status of "0" every time, on Firefox, Chrome, and Edge. I have a feeling I'm missing something since this is my first time doing this.
Here is the code I'm using:
var upc = prompt("Enter UPC Code:");

var requestUrl = "https://api.upcdatabase.org/product/" + upc +
    "/73114EC2F9C47240583DBF3AA190CB4C";

function httpGetAsync(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            alert(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send();
    alert(xmlHttp.status);
}

httpGetAsync(requestUrl);

Thanks to anyone who can help!

A: From the documentation:

Before the request is complete, the value of status will be 0.

The request isn't complete until readyState == 4, so it's normal to see 0 if you log status before that test is successful. Try this:
function httpGetAsync(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            alert(xmlHttp.status);
            if (xmlHttp.status == 200) {
                alert(xmlHttp.responseText);
            }
        }
    };
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send();
}


text:
Q: Difference between notifyDataSetChanged() and Adapter.this.notifyDataSetChanged() I am new to programming. Can you please explain what the difference between notifyDataSetChanged() and Adapter.this.notifyDataSetChanged() is? I think it has something to do with that context stuff?
I´m wondering which one I should use for my RecyclerView changes.

A: They are likely one and the same. this is a Java keyword to specify the current object, and the only reason you would have to specify Adapter.this before the method is if you were in an inner class where this would refer to something else.


text:
Q: How to have interaction behavior work on a UserControl I have the following UserControl that has an attached behavior on it. At the moment I have to select one of the DataGrid items in order for it to run the behavior.
Only guessing here but it's kind of understandable because these containers are not focusable or are not supposed to register keyboard events, so it goes to the next child available???
I could place this functionality on the window however this UserControl can get swapped out with another UserControl and I prefer for it not be be lying around.
This is just a unique case in my app where the only thing on the window is the DataGrid and I don't necessarily want to select a DataGrid item to begin the behavior.
My question is: Is it possible to get the following behavior to work? Either on the UserControl, Grid or maybe some other control that would permit this.
<UserControl x:Class="UserManagement.LaunchPad"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:helpers="clr-namespace:UserManagement.Helpers"
             xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
             xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <i:Interaction.Behaviors>
        <helpers:OpenPopupBehaviors FindPopupObject="{Binding ElementName=PopupFind}"
                                    GotoPopupObject="{Binding ElementName=PopupGoto}" />
    </i:Interaction.Behaviors>

    <Grid>
        <DockPanel>
            <DataGrid />
        </DockPanel>
        <Popup Name="PopupGoto" />
        <Popup Name="PopupFilter "/>
    </Grid>
</UserControl>

Here is the behavior:
class OpenPopupBehaviors : Behavior<UserControl>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.KeyDown += _KeyBoardBehaviorKeyDown;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        this.AssociatedObject.KeyDown -= _KeyBoardBehaviorKeyDown;
    }

    void _KeyBoardBehaviorKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.F && (Keyboard.Modifiers & (ModifierKeys.Control)) == (ModifierKeys.Control))
        {

            var popup = FindPopupObject as UserManagement.Controls.NonTopmostPopup;
            if (popup == null)
                return;

            popup.IsOpen = true;
        }

        if (e.Key == Key.G && (Keyboard.Modifiers & (ModifierKeys.Control)) == (ModifierKeys.Control))
        {
            var popup = GotoPopupObject as Popup;
            if (popup == null)
                return;

            popup.IsOpen = true;
        }
    }

    public static readonly DependencyProperty FindPopupObjectProperty =
        DependencyProperty.RegisterAttached("FindPopupObject", typeof(object), typeof(OpenPopupBehaviors), new UIPropertyMetadata(null));

    public object FindPopupObject
    {
        get { return (object)GetValue(FindPopupObjectProperty); }
        set { SetValue(FindPopupObjectProperty, value); }
    }

    public static readonly DependencyProperty GotoPopupObjectProperty =
        DependencyProperty.RegisterAttached("GotoPopupObject", typeof(object), typeof(OpenPopupBehaviors), new UIPropertyMetadata(null));

    public object GotoPopupObject
    {
        get { return (object)GetValue(GotoPopupObjectProperty); }
        set { SetValue(GotoPopupObjectProperty, value); }
    }
}

A: So far I can see is that the focus if your issue
you can make use of Preview events to receive the events even if the focus is on control's child or their descendants
protected override void OnAttached()
{
    base.OnAttached();
    this.AssociatedObject.PreviewKeyDown += _KeyBoardBehaviorKeyDown;
}

protected override void OnDetaching()
{
    base.OnDetaching();
    this.AssociatedObject.PreviewKeyDown-= _KeyBoardBehaviorKeyDown;
}

I have changed KeyDown to PreviewKeyDown
above solution will work as long as the AssociatedObject have focus on it or any child within it. if you look forward to control it globally then perhaps you may need to attach the events to top level elements eg. Window
so in order to do that you need to find the appropriate parent of AssociatedObject and attach the event to the same.
also make sure that the following cast is valid
FindPopupObject as UserManagement.Controls.NonTopmostPopup;

it could be
FindPopupObject as Popup;


text:
Q: No network after Windows Server upgrade Last night I started upgrading a server from Windows Server 2008 R2 to Windows Server 2012 R2.
This morning checking if everything went well, the network card says "unidentified network" and "no Internet access". DHCP does not work, and neither does ping when I switch back to static IP. There is nevertheless incoming and outgoing traffic.
I tried to update the drivers of the network card as well as its firmware, but nothing changes.
I tried to connect a USB network adapter, but the problem remains the same; the problem seems to come from Windows and not the card or drivers.
So I tried to run the command "netsh winsock reset" and then restart, but here it does not work.
I do not know what to do while it is imperative that this server works before Monday morning.
Thank you for your help.
EDIT 1:
I tried that without more results:
netsh int ip reset C:\logreset.txt
netsh int tcp set heuristics disabled
netsh int tcp set global autotuninglevel=disabled
netsh int tcp set global rss=enabled
netsh int tcp show global

A: Murphy hit again!
During the night the port of the switch to which the server was connected is dead.
The switch communicates with the connected equipment but the port is isolated from all the rest of the network ...
Coincidence or not? I don't know.

A: Might occur if Windows Firewall considers your network a public network.
In my experience,

*

*you install Windows Server 2012 R2

*Windows Server 2012 R2 defaults to public network

*you update, install antimalware, etc

*you promote to DC

BUT

*

*Windows Server 2012 R2 continues to treat the network as public.
To fix, restart the Network Location Awareness service.
After a restart, Windows Server 2012 R2 correctly detects your network as a domain network, and the right firewall profile activates.


text:
Q: On the Math Mindset I am a soon-to-be high school graduate with inclination towards mathematics. I enjoy doing math, and am relatively good at it, but I dislike the way I am being taught. I feel like I am being taught methods for solving a lot of problems, but I don't see how any of this fits together.
I was considering pursuing a career in mathematics, but I realized I don't really know much about it as a whole as opposed to how to solve specific problems that will appear on some test.
Are there any good books out there about the "math mindset", or whatever it is that it's called?

A: I have spent a TON of time in the math library at Rutgers just thumbing through all the books, and I never really found a book about the "math mindset" that was half decent.  You could do a lot worse than to read stack exchange every day and become a regular on this forum; everyone here is really helpful and you shouldn't be afraid of posting a "silly" question out of fear of being embarrassed; the only thing that upsets people here is when someone doesn't put a sufficient amount of thought/effort into the problem before asking, or else when the question being asked is clearly off topic.
I think that talking with mathematicians about specific problems you are working on will give you a far deeper insight into how mathematicians think than reading some low level book for a popular audience will.
The most important thing in my opinion is not the book you finally choose, but rather the attitude that you should always try to solve EVERY SINGLE problem in whatever math book you read.  You should spend more time solving the problems than reading the sections.
I recommend you pick up "A survey of modern algebra" by Birkhoff and Mclane.  The difficulty level is pretty low, and the problems are numerous and instructive.  One reason I so highly recommend this particular book for you is that "modern algebra" is not only fundamentally important for contemporary mathematics, it also is not taught in high schools generally, not to mention that many of the results are beautiful.  Another great thing about this specific book is that the author's are famous mathematicians, and you can figure out how they think about math just by seeing the organization of how the material is presented and how the results are derived.  The first chapter in this book deals with number theory, but actually contains a very nice introduction to writing logical and rigorous proofs.
I think you should just read through books on specific subjects, and pick the subject you will study based on your current interests and level of knowledge.  Some subjects to start with are:
set theory, metric spaces, complex analysis, group theory, number theory
One thing you might want to try is just to go ahead and check out some books by the great masters.  For example, there is a great set theory book by Frankel (who has the axioms of set theory named after him), and a great book on number theory by Sierpinski; and I recommend both of these not only because they are really well written and basically at the high school level, but because this will give you an insight into how the great masters thought about math.  Finally, if you are feeling confident go ahead and check out Disquisitions Arithmetic by Gauss, just to try your hand at it.
Let me also mention a compilation of writings for a popular audience by Henri Poincare called "The Value of Science".  A large portion of this book deals with physics, but there are two particular passages you should pay attention to for understanding the "math mindset": the first is the discussion of induction, and the second is a fairly famous section where Poincare discusses the internal psychological process he experienced when solving a highly technical problem.
Best of Luck!

A: I think certain parts of The Princeton Companion to Mathematics might be just what you need.  While many of the topics will go over your head at the moment, there is a very lucid introduction to the history and basic points of view of modern mathematics in Parts I and II, as well as a lot of interesting historical overviews and essays in Parts VI and VIII.  And of course much of the book is filled with fascinating mathematics.

A: Here are some further classics that you may find inspiring and enlightening: Polya: How to solve it; Rademacher and Toeplitz: The enjoyment of mathematics; Kac and Ulam: Mathematics and Logic.

A: Unfortunately, a very popular approach to teaching mathematics at the grade school level is to de-emphasize the concepts and focus more on the rote, procedural aspects of the subject.  I don't think many people really like this type of education but it's one of the simpler approaches to teaching. On the positive side, by focusing on the procedural you have a systematic way with which you can judge a students' progress.   In some sense this is a mode of teaching that is dictated largely by the desire for a convienient means of evaluation, rather than being dictated by holding the students' interest, or teaching them valuable things.  The hope is that by learning enough procedures by rote, the underlying concepts somehow sink-in, as if by magic.  I think this does work for many students but by-and-large it's unsatisfactory to almost all involved.  To teach mathematics in any other way with similar objective measures of success tends to be much more time and energy consuming for all involved, as far as I can tell.
To complement Sam Nead's very nice suggestions, I enjoyed reading Devaney's "Introduction to Chaotic Dynamical Systems".  I don't remember when exactly I picked it up, might have been grade 12 or 1st year of university.  Parts of it were over my head at the time, but I was able to digest much of the contents, slowly.  In that regard I think it's useful to take a non-linear approach to learning.  It's useful to have as a goal to understand some high-level topic, and to have a mental roadmap for how you're going to get there. You don't want to be too aggressive on this, though.  Around grade 12, Devaney's text was very useful for me.  It's a book that can be used both for graduate courses and for upper-level undergraduate courses.  So you'll probably see it as several steps ahead of what you're used to.  But it's well-written and well-motivated.  Digest what you can, slow down and think about aspects that appear hard, maybe come back to them a few months later.  Attempt some of the more fun-looking problems at the end of sections.  Do some computer experiments.  That kind of thing.


text:
Q: Binding SelectedItem from dropdownlist to model object in MVC 4 I'm very new with MVC, so bear with me, but I can't seem to bind a value from a SelectList to an instance of the selected object during a postback in MVC 4.
Suppose I have to create a Teacher as a member of a School. I have a ViewModel class defined as such:
public class RegisterTeacherModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    [Required]
    [Display(Name = "School")]
    public School SelectedSchool { get; set; }

    [ScaffoldColumn(false)]
    public Guid UserId
    {
        get;
        set;
    }

    public SelectList PossibleSchools
    {
        get;
        private set;
    }

    public RegisterTeacherModel(IRepository<School> schoolRepo)
    {
        PossibleSchools = new SelectList(schoolRepo, "Id", "Name");
    }
}

And my View:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>RegisterTeacherModel</legend>

        @Html.LabelFor(model => model.UserName)

        @Html.LabelFor(model => model.Email)

        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)

        @Html.LabelFor(model => model.SelectedSchool)

        @Html.DropDownListFor(model => model.SelectedSchool, Model.PossibleSchools)

        <input type="submit" value="Create" />

</fieldset>
}

And finally, my Controller method:
    [HttpPost, ActionName("Create")]
    public ActionResult CreateTeacher(RegisterTeacherModel teacherModel)
    {
        if (ModelState.IsValid)
        {
            try
            {
              ...
            }
         }
    }

But when I receive the RegisterTeacherModel object back in my Create method in the Controller, SelectedSchool is always null. I must be missing something in the way the model binder re-creates the object references on postback. Can anyone point me in the right direction?

A: I think you touched on it with your second post: Try pointing the initial code to Model.SelectedSchool.<IdProperty>

  @Html.DropDownListFor(model => model.SelectedSchool.**<IdProperty>**, Model.PossibleSchools)

A: Well, I found a workaround. I still don't know if I'm missing something, but instead of using a School object in my ViewModel, I replaced it with the SelectedSchoolId as such:
public class RegisterTeacherModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    [Required]
    [Display(Name = "School")]
    public int SelectedSchoolId { get; set; }

    ...
}

And change my View dropdown to use this instead:

    @Html.DropDownListFor(model => model.SelectedSchoolId, Model.PossibleSchools)

And then in my controller, when creating the real model objects I can simply pull the School object from the School repository and associate it with the real Teacher object.


text:
Q: how to produce bigrams without stop words i wrote this function for generating bigrams from string using nltk.bigrams and ignoring stop words and letters but the stop words and letters still appear in the output. please help me to correct the funtion.
       def bigramReturner (tweetString, stopWords):
           bigramFeatureVector = []
           tweetStringG = tweetString.lower()
           tweetStringG = tweetString.split()
           for i in tweetStringG:
               i =replaceTwoOrMore(i)
               i =i.strip('\'"?,.')
               val = re.search(r"^[a-zA-Z][a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$", i)
               if(i in stopWords  is None):
                   continue
               else:
                  for i in nltk.bigrams(tweetStringG):
                        bigramFeatureVector.append(' '.join(i))
           return bigramFeatureVector

A: Try removing the is None check as currently you're comparing True or False with None
   def bigramReturner (tweetString, stopWords):
       bigramFeatureVector = []
       tweetStringG = tweetString.lower()
       tweetStringG = tweetString.split()
       for i in tweetStringG:
           i =replaceTwoOrMore(i)
           i =i.strip('\'"?,.')
           val = re.search(r"^[a-zA-Z][a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$", i)
           if(i in stopWords):
               continue
           else:
              for i in nltk.bigrams(tweetStringG):
                    bigramFeatureVector.append(' '.join(i))
       return bigramFeatureVector


text:
Q: Two programs running the same function twice, One can handle it, One can't. Why? C I'm cross-posting this with the arduino exchange because i'm not sure if it's a problem with my C or something else entirely.
I'm attempting to communicate over wifi using the process library (Part of the arduino yun's librarys) And I'm calling the same functions in the same way in two programs. One program works the other doesn't.
These are the functions:
Process p;    // Create a process and call it "p"
p.begin("curl");  // Process that launch the "curl" command
p.addParameter(b); // Add the URL parameter to "curl"
p.run();    // Run the process and wait for its termination
Console.flush();
Console.println("CurlSetup");
while (p.available() > 0) {
  //Stuff
}

I have successfully called the functions once in my more complicated program but ran into trouble when I tried using the functions twice. I then found the example of using these functions in the IDE and changed it slightly to run the functions twice in the program (to mirror my own program).
My code console printout:
Create String:http://xxx.xxx.xxx.xxx/OpenEMan/register/create.json?apikey=xxxx&nodeMAC=01:02:03:04:05:10&fromAddress=172.16.0.75&timeout=15
"102N"
1Nodeid: 102
Nodeid: 102
0
apikey=xxxx
&node=102
&json=0x0201,0x0000,0x019,0x0
http://172.16.0.158/OpenEMan/register/setup.json?apikey=xxxx
Breaks
Here
http://172.16.0.158/OpenEMan/register/setup.json?apikey=xxxx&node=102
http://172.16.0.158/OpenEMan/register/setup.json?apikey=xxxx&node=102&json=0x0201,0x0000,0x019,0x0
http://172.16.0.158/OpenEMan/register/setup.json?apikey=xxxx&node=102&json=0x0201,0x0000,0x019,0x0&timeout=15
CurlSetup

Just to clarify, this should produce a much larger print out. My program just stops and crashes at this point. The print out of a successful run through would be 2-3 times longer than this.
Modified working example printout:
Unable to connect: retrying (1)...
Unable to connect: retrying (2)... connected!

           `:;;;,`                      .:;;:.
        .;;;;;;;;;;;`                :;;;;;;;;;;:     TM
      `;;;;;;;;;;;;;;;`            :;;;;;;;;;;;;;;;
     :;;;;;;;;;;;;;;;;;;         `;;;;;;;;;;;;;;;;;;
    ;;;;;;;;;;;;;;;;;;;;;       .;;;;;;;;;;;;;;;;;;;;
   ;;;;;;;;:`   `;;;;;;;;;     ,;;;;;;;;.`   .;;;;;;;;
  .;;;;;;,         :;;;;;;;   .;;;;;;;          ;;;;;;;
  ;;;;;;             ;;;;;;;  ;;;;;;,            ;;;;;;.
 ,;;;;;               ;;;;;;.;;;;;;`              ;;;;;;
 ;;;;;.                ;;;;;;;;;;;`      ```       ;;;;;`
 ;;;;;                  ;;;;;;;;;,       ;;;       .;;;;;
`;;;;:                  `;;;;;;;;        ;;;        ;;;;;
,;;;;`    `,,,,,,,,      ;;;;;;;      .,,;;;,,,     ;;;;;
:;;;;`    .;;;;;;;;       ;;;;;,      :;;;;;;;;     ;;;;;
:;;;;`    .;;;;;;;;      `;;;;;;      :;;;;;;;;     ;;;;;
.;;;;.                   ;;;;;;;.        ;;;        ;;;;;
 ;;;;;                  ;;;;;;;;;        ;;;        ;;;;;
 ;;;;;                 .;;;;;;;;;;       ;;;       ;;;;;,
 ;;;;;;               `;;;;;;;;;;;;                ;;;;;
 `;;;;;,             .;;;;;; ;;;;;;;              ;;;;;;
  ;;;;;;:           :;;;;;;.  ;;;;;;;            ;;;;;;
   ;;;;;;;`       .;;;;;;;,    ;;;;;;;;        ;;;;;;;:
    ;;;;;;;;;:,:;;;;;;;;;:      ;;;;;;;;;;:,;;;;;;;;;;
    `;;;;;;;;;;;;;;;;;;;.        ;;;;;;;;;;;;;;;;;;;;
      ;;;;;;;;;;;;;;;;;           :;;;;;;;;;;;;;;;;:
       ,;;;;;;;;;;;;;,              ;;;;;;;;;;;;;;
         .;;;;;;;;;`                  ,;;;;;;;;:

    ;;;   ;;;;;`  ;;;;:  .;;  ;; ,;;;;;, ;;. `;,  ;;;;
    ;;;   ;;:;;;  ;;;;;; .;;  ;; ,;;;;;: ;;; `;, ;;;:;;
   ,;:;   ;;  ;;  ;;  ;; .;;  ;;   ,;,   ;;;,`;, ;;  ;;
   ;; ;:  ;;  ;;  ;;  ;; .;;  ;;   ,;,   ;;;;`;, ;;  ;;.
   ;: ;;  ;;;;;:  ;;  ;; .;;  ;;   ,;,   ;;`;;;, ;;  ;;`
  ,;;;;;  ;;`;;   ;;  ;; .;;  ;;   ,;,   ;; ;;;, ;;  ;;
  ;;  ,;, ;; .;;  ;;;;;:  ;;;;;: ,;;;;;: ;;  ;;, ;;;;;;
  ;;   ;; ;;  ;;` ;;;;.   `;;;:  ,;;;;;, ;;  ;;,  ;;;;

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.4.2

It also breaks either the arduino or the IDE. After running my code and trying to upload more code to the arduino, I get the following error:
avrdude: verification error, first mismatch at byte 0x0000
         0xff != 0x0c
avrdude: verification error; content mismatch

In the IDE and it refuses to upload the code to the arduino.
My code, Ip's and Apikey's blanked out: http://pastebin.com/XZswiKch
Modified arduino example code: http://pastebin.com/t1qm5hrV


text:
Q: How do you make a button from second activity open a third activity? I'm trying to figure out the code to make a button from my second activity open a new third activity.
I just need to know the basic code for opening a third activity from a second activity button......

import android.app.Activity;
import android.os.Bundle;

public class FifthActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fifth_layout);
    }
}

That is my activity.java file where the buttons are located....
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Amazon"
    android:drawableLeft="@drawable/amazon"
    android:drawableStart="@drawable/amazon"
    android:layout_weight="0.07"
    tools:ignore="HardcodedText"
    android:textSize="35sp" />

And that was my Fifth_Layout.xml
And.. I want to be able to open this image button from my second activity to my third activity. I just cant figure out the code to put into MainActivity.Java

A: Do this
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        startActivity(new Intent(view.getContext(), ThirdActivity.class));
    }
});

A: First you have to set a id of button in the layout. Then in onCreate() method you have to write:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fifth_layout);
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            startActivity(new Intent(this, ThirdActivity.class));
        }
    });
}

A: Fifth_Layout.xml
<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Amazon"
    android:drawableLeft="@drawable/amazon"
    android:drawableStart="@drawable/amazon"
    android:layout_weight="0.07"
    tools:ignore="HardcodedText"
    android:textSize="35sp" />

activity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fifth_layout);
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            startActivity(new Intent(this, ThirdActivity.class));
        }
    });
}


text:
Q: string to char to string to int Basically, what this code does is getting a number in any length from the user and sends it back to the user in a digit per digit form plus the sum of all the digits on the given number(e.g. 1234= 1, 2, 3, 4. sum=10). However, I can't make it work on a negative number.
    Scanner s= new Scanner(System.in);

    String num= s.nextLine();

    char arr[]= new char[num.length()];
    int numsarray[]= new int[num.length()];
    String number[]= new String[num.length()];
    int sum=0;

    for(int i=0; i<num.length();i++)
    {
        arr[i]=num.charAt(i);
        System.out.println(arr[i]);

        number[i]=Character.toString(arr[i]);

        numsarray[i]=Integer.parseInt(number[i]);
    }

    for(int i=0;i<num.length();i++)
    {
        sum+=numsarray[i];
    }
    System.out.println("Sum:"+sum);

A: Any reason you do not check first whether the number is less then 0 or not? You could then use abs to make it positive and run it through your function. Takes away the hassle to deal with the hyphen at arr[0]. Of course you should have some bool to store the sign :-)


text:
Q: Probability of A given B or C I know some formulae related to conditional probabilities of events conditional on intersection of two events.
But I have been unable to find any formula for the case where the condition is union of two or more events.
That is, how can I find
$P(A | B\text{ or }C)$
And in general
$P(A | B\text{ or }C\text{ or }\dots\text{ or }X)$
And what can be the continuous analog?
$p(x | y \in [a,b])$
When I already know $p(x | y=t), \forall t \in [a,b]$
Edit: An approach I tried
$ P(A |B\text{ or }C) = \frac{P ((A\text{ and }B)\text{ or }(A\text{ and }C))}{P(B\text{ or }C)}$
$ =\frac {P(A,B)+P(A,C)-P(A,B,C)} {P(B\text{ or }C)} $
For the continuous case I asked, I assume that $y$ can take only one value at a time, so the $P(A,B,C)$ term can be ignored.
I have not tried a derivation, but just by analogy, I guess the continuous expression would be
$ p(x|y \in [a,b]) = \frac { \int_a^b p(x|y) p(y) dy} {P(y \in [a,b])} $
Is the approach for the discrete case correct?
I have just used analogy for the continuous case, is the formula I guessed correct? If yes, how to prove that? If not, what is the correct formula?

A: 1)
$P(A | B \text{ or } C)=P(A|B\cup C)=\frac{P(A\cap(B\cup C))}{P(B\cup C)}$
2)$P(A | B \text{ or } C \text{ or } \dots \color{red}{\text{or }X})$
what is $B \text{ or } X$?
If $X$ is a random variable, I think it is only valid if we  use it like $B\cup \{X\in E\}=\{\omega \in \Omega \mid \omega \in B \text{ or } x(\omega)\in E\}$.
so
$P(A | B \text{ or } C \text{ or } \cdots \text{ or } \{X \in E\})$ can be easily calculated by defining $D=B \cup C  \cup \cdots \cup \{X \in E\}$.
3) $P(X= x|Y\in [a,b])$  for the case  $Y$ is a continues random variable You can easily calculate it if you knowing $P(X\leq x|Y\in [a,b])$.
$$P(X\leq x|Y\in [a,b])=P(\{X \leq  x\}|\{Y\in [a,b]\})=\frac{P(\{X \leq x\} \cap \{Y\in [a,b]\})}{P(\{Y\in [a,b]\})}=\frac{\int_{-\infty}^{x}\int_{y\in [a,b]}f_{(X,Y)}(t , y) dy dt}{P(\{Y\in [a,b]\})}=\frac{\int_{-\infty}^{x} \int_{y\in [a,b]}p(t | y)p(y) dy dt}{P(\{Y\in [a,b]\})}$$.


text:
Q: How to use a SQL inside Teradata UDF? I want to convert a complex query into a reusable and parameterized function.
Thus I am trying to create an UDF in Teradata, but do not understand how to use SQL inside my UDF.
Below is the sample UDF from Oracle database. Can anyone please confirm if & how I can create similar in Teradata ?

   CREATE FUNCTION test_ak (a IN NUMBER)
   RETURN NUMBER
   IS b NUMBER(10);
   BEGIN
          SELECT a+1
          INTO b
          FROM dual ;
     RETURN(b);
   END;
   /