text:
Q: Issue to return int from a method i need to return a int variable from a method that i show below, but with my code, method not return int variable...i don't know why!
I hope that you can help me!
Thanks in advance everybody!
    public int checkLogin(final String emaill, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    Log.i("ciao1", "["+response+"]");

                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite

                        String uid = jObj.getString("uid");
                        id= jObj.getInt("id");
                        System.out.println("BEFORE STORE THE USER IN SQLITE____ID:"+id);

                        idd= jObj.getInt("id");
                        System.out.println("BEFORE STORE THE USER IN SQLITE___ID:"+idd);

                        System.out.println("BEFORE STORE THE USER IN SQLITE ID:"+id);

                        JSONObject user = jObj.getJSONObject("user");

                        String name = user.getString("name");
                        String cognome = user.getString("cognome");

                        String emaill = user.getString("email");
                        String email2 = user.getString("email2");
                        String numero_appartamento = user.getString("numero_appartamento");
                        String nome_edificio = user.getString("nome_edificio");
                        String zona_metropolitana = user.getString("zona_metropolitana");

                        String created_at = user
                                .getString("created_at");
                        Log.i("ciao2", "[" + jObj + "]");

                        // Inserting row in users table
//                        db.addUser(name,cognome, emaill,email2,numero_appartamento,nome_edificio,zona_metropolitana,uid, created_at);
                        db.addUser(name, cognome, emaill, email2, numero_appartamento, nome_edificio, zona_metropolitana, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
//                                MainActivity.class);
                                ScrollableTabsActivity.class);
                        intent.putExtra("EXTRA_SESSION_ID", id);

                        startActivity(intent);
                        finish();

                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }

        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", emaill);
                params.put("password", password);
                System.out.println(params);
                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

        return idd;

    }

A: Volley requests are async, so when you try to return an int, the request is likely not done yet. If you want to return values from a Volley request use callback interfaces.
public void getInt(final VolleyCallback callback) {
    StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            callback.onSuccess(<PASS INTEGER RESULT HERE>);
        }
    });
}

public interface VolleyCallback{
    void onSuccess(int result);
}

Example usage:
public void onResume(){
    super.onResume();
    getInt(new VolleyCallback(){
         @Override
         public void onSuccess(int result){
             //do stuff here with the int
         }
    });
}

A:  public StringRequest checkLogin(final String emaill,final CallbackInterface callback, final String password) {

        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    Log.i("ciao1", "["+response+"]");

                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite

                        String uid = jObj.getString("uid");
                        id= jObj.getInt("id");
                        System.out.println("BEFORE STORE THE USER IN SQLITE____ID:"+id);

                        idd= jObj.getInt("id");
                        System.out.println("BEFORE STORE THE USER IN SQLITE___ID:"+idd);

                        System.out.println("BEFORE STORE THE USER IN SQLITE ID:"+id);

                        JSONObject user = jObj.getJSONObject("user");

                        String name = user.getString("name");
                        String cognome = user.getString("cognome");

                        String emaill = user.getString("email");
                        String email2 = user.getString("email2");
                        String numero_appartamento = user.getString("numero_appartamento");
                        String nome_edificio = user.getString("nome_edificio");
                        String zona_metropolitana = user.getString("zona_metropolitana");

                        String created_at = user
                                .getString("created_at");
                        Log.i("ciao2", "[" + jObj + "]");

                        // Inserting row in users table
//                        db.addUser(name,cognome, emaill,email2,numero_appartamento,nome_edificio,zona_metropolitana,uid, created_at);
                        db.addUser(name, cognome, emaill, email2, numero_appartamento, nome_edificio, zona_metropolitana, uid, created_at);

                         callback.onSuccess(idd);//implement this in your MainActivity.java

                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }

        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", emaill);
                params.put("password", password);
                System.out.println(params);
                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

        return strReq;

    }

public interface CallbackInterface {
    void onSuccess(int result);
}


text:
Q: I'm trying to launch a 'jupyter notebook' by making a clickable shell script on osx 10.14 I want to make a file that will
-open terminal and execute 'jupyter notebook' in the command line.
I am running Mac osx 10.14 (Mojave) I have jupyter notebook tested operational. Any pointers would help.

A: Found an answer from another thread that will work for the time being.
https://stackoverflow.com/a/46995543/12496767
I'll probably be adding more specific requirements later and updating this thread as it develops.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node: is Express-validator isString() necessary? I'm using Node/Express/Express-Validator and all my request variables are coming in as strings to the server.
But doesn't that make certain checks irrelevant? Like 'isString()' below?
router.post('/create/company', multer().none(), [
    body('companyName')
    .isString()
    .withMessage('Please enter a string')
    .isLength({ min: 1, max: 50 })
    .withMessage('Enter a company name between 1 and 50 characters')
], adminController.createCompany);

Sorry if it's obvious, but I hadn't really thought about it until I started testing my routes and now I'm wondering if I should even check? There's also obviously a gap in my knowledge here, just wondering what I'm missing!
Thanks

A: So it's probably just an oversight on my part (although I can't see anything about it anywhere in the docs), but just in case it helps anyone else, in my actual code I was chaining escape() and trim() before isString(), and these were converting the number to a string.


text:
Q: goormIDE: Send an editor's line to the terminal I am trying the goormIDE.
In REPL languages, such as Python or R, I would like to send individual lines from the editor to the terminal.
goormIDE gives the possibility to create custom run commands. Is it possible to create a command working on the current editor line rather than the whole file?


text:
Q: Is there a way to workaround the Xamarin.Forms Tizen ListView rowheight property limitation for TV? I am trying to find an alternative to set the row height of a ListView in Tizen platform for TV.
As we know there is a limitation related to the RowHeight property in Xamarim ListView for Tizen.
This property is just ignored so I cannot set the height of the rows in my ListView.
Is there a workaround or an alternative way of doing this?

A: Did you use a TextCell? You cannot set the height of a TextCell. Its Height property is ignored.
However, if you use a ViewCell instead, you can change its height.


text:
Q: Why use build tools like Autotools when we can just write our own makefiles? Recently, I switched my development environment from Windows to Linux. So far, I have only used Visual Studio for C++ development, so many concepts, like make and Autotools, are new to me. I have read the GNU makefile documentation and got almost an idea about it. But I am kind of confused about Autotools.
As far as I know, makefiles are used to make the build process easier.

*

*Why do we need tools like Autotools just for creating the makefiles? Since all knows how to create a makefile, I am not getting the real use of Autotools.

*What is the standard? Do we need to use tools like this or would just handwritten makefiles do?

A: You are talking about two separate but intertwined things here:

*

*Autotools

*GNU coding standards

Within Autotools, you have several projects:

*

*Autoconf

*Automake

*Libtool

Let's look at each one individually.
Autoconf
Autoconf easily scans an existing tree to find its dependencies and create a configure script that will run under almost any kind of shell. The configure script allows the user to control the build behavior (i.e. --with-foo, --without-foo, --prefix, --sysconfdir, etc..) as well as doing checks to ensure that the system can compile the program.
Configure generates a config.h file (from a template) which programs can include to work around portability issues. For example, if HAVE_LIBPTHREAD is not defined, use forks instead.
I personally use Autoconf on many projects. It usually takes people some time to get used to m4. However, it does save time.
You can have makefiles inherit some of the values that configure finds without using automake.
Automake
By providing a short template that describes what programs will be built and what objects need to be linked to build them, Makefiles that adhere to GNU coding standards can automatically be created. This includes dependency handling and all of the required GNU targets.
Some people find this easier. I prefer to write my own makefiles.
Libtool
Libtool is a very cool tool for simplifying the building and installation of shared libraries on any Unix-like system. Sometimes I use it; other times (especially when just building static link objects) I do it by hand.
There are other options too, see StackOverflow question Alternatives to Autoconf and Autotools?.
Build automation & GNU coding standards
In short, you really should use some kind of portable build configuration system if you release your code to the masses. What you use is up to you. GNU software is known to build and run on almost anything. However, you might not need to adhere to such (and sometimes extremely pedantic) standards.
If anything, I'd recommend giving Autoconf a try if you're writing software for POSIX systems. Just because Autotools produce part of a build environment that's compatible with GNU standards doesn't mean you have to follow those standards (many don't!) :) There are plenty of other options, too.
Edit
Don't fear m4 :) There is always the Autoconf macro archive. Plenty of examples, or drop in checks. Write your own or use what's tested. Autoconf is far too often confused with Automake. They are two separate things.

A: Autotools are needed because Makefiles are not guaranteed to work the same across different platforms. If you handwrite a Makefile, and it works on your machine, there is a good chance that it won't on mine.

A: Do you know what unix your users will be using? Or even which distribution of Linux? Do you know where they want software installed? Do you know what tools they have, what architecture they want to compile on, how many CPUs they have, how much RAM and disk might be available to them?
The *nix world is a cross-platform landscape, and your build and install tools need to deal with that.

Mind you, the auto* tools date from an earlier epoch, and there are many valid complaints about them, but the several projects to replace them with more modern alternatives are having trouble developing a lot of momentum.
Lots of things are like that in the *nix world.

A: Autotools is a disaster.
The generated ./configure script checks for features that have not been present on any Unix system for last 20 years or so. To do this, it spends a huge amount of time.
Running ./configure takes for ages. Although modern server CPUs can have even dozens of cores, and there may be several such CPUs per server, the ./configure is single-threaded. We still have enough years of Moore's law left that the number of CPU cores will go way up as a function of time. So, the time ./configure takes will stay approximately constant whereas parallel build times reduce by a factor of 2 every 2 years due to Moore's law. Or actually, I would say the time ./configure takes might even increase due to increasing software complexity taking advantage of improved hardware.
The mere act of adding just one file to your project requires you to run automake, autoconf and ./configure which will take ages, and then you'll probably find that since some important files have changed, everything will be recompiled. So add just one file, and make -j${CPUCOUNT} recompiles everything.
And about make -j${CPUCOUNT}. The generated build system is a recursive one. Recursive make has for a long amount of time been considered harmful.
Then when you install the software that has been compiled, you'll find that it doesn't work. (Want proof? Clone protobuf repository from Github, check out commit 9f80df026933901883da1d556b38292e14836612, install it to a Debian or Ubuntu system, and hey presto: protoc: error while loading shared libraries: libprotoc.so.15: cannot open shared object file: No such file or directory -- since it's in /usr/local/lib and not /usr/lib; workaround is to do export LD_RUN_PATH=/usr/local/lib before typing make).
The theory is that by using autotools, you could create a software package that can be compiled on Linux, FreeBSD, NetBSD, OpenBSD, DragonflyBSD and other operating systems. The fact? Every non-Linux system to build packages from source has numerous patch files in their repository to work around autotools bugs. Just take a look at e.g. FreeBSD /usr/ports: it's full of patches. So, it would have been as easy to create a small patch for a non-autotools build system on a per project basis than to create a small patch for an autotools build system on a per project basis. Or perhaps even easier, as standard make is much easier to use than autotools.
The fact is, if you create your own build system based on standard make (and make it inclusive and not recursive, following the recommendations of the "Recursive make considered harmful" paper), things work in a much better manner. Also, your build time goes down by an order of magnitude, perhaps even two orders of magnitude if your project is very small project of 10-100 C language files and you have dozens of cores per CPU and multiple CPUs. It's also much easier to interface custom automatic code generation tools with a custom build system based on standard make instead of dealing with the m4 mess of autotools. With standard make, you can at least type a shell command into the Makefile.
So, to answer your question: why use autotools? Answer: there is no reason to do so. Autotools has been obsolete since when commercial Unix has become obsolete. And the advent of multi-core CPUs has made autotools even more obsolete. Why programmers haven't realized that yet, is a mystery. I'll happily use standard make on my build systems, thank you. Yes, it takes some amount of work to generate the dependency files for C language header inclusion, but the amount of work is saved by not having to fight with autotools.

A: First of all, the Autotools are not an opaque build system but a loosely coupled tool-chain, as tinkertim already pointed out. Let me just add some thoughts on Autoconf and Automake:
Autoconf is the configuration system that creates the configure script based on feature checks that are supposed to work on all kinds of platforms. A lot of system knowledge has gone into its m4 macro database during the 15 years of its existence. On the one hand, I think the latter is the main reason Autotools have not been replaced by something else yet. On the other hand, Autoconf used to be far more important when the target platforms were more heterogeneous and Linux, AIX, HP-UX, SunOS, ..., and a large variety of different processor architecture had to be supported. I don't really see its point if you only want to support recent Linux distributions and Intel-compatible processors.
Automake is an abstraction layer for GNU Make and acts as a Makefile generator from simpler templates. A number of projects eventually got rid of the Automake abstraction and reverted to writing Makefiles manually because you lose control over your Makefiles and you might not need all the canned build targets that obfuscate your Makefile.
Now to the alternatives (and I strongly suggest an alternative to Autotools based on your requirements):
CMake's most notable achievement is replacing AutoTools in KDE. It's probably the closest you can get if you want to have Autoconf-like functionality without m4 idiosyncrasies. It brings Windows support to the table and has proven to be applicable in large projects. My beef with CMake is that it is still a Makefile-generator (at least on Linux) with all its immanent problems (e.g. Makefile debugging, timestamp signatures, implicit dependency order).
SCons is a Make replacement written in Python. It uses Python scripts as build control files allowing very sophisticated techniques. Unfortunately, its configuration system is not on par with Autoconf. SCons is often used for in-house development when adaptation to specific requirements is more important than following conventions.
If you really want to stick with Autotools, I strongly suggest to read Recursive Make Considered Harmful (archived) and write your own GNU Makefile configured through Autoconf.

A: The answers already provided here are good, but I'd strongly recommend not taking the advice to write your own makefile if you have anything resembling a standard C/C++ project. We need the autotools instead of handwritten makefiles because a standard-compliant makefile generated by automake offers a lot of useful targets under well-known names, and providing all these targets by hand is tedious and error-prone.
Firstly, writing a Makefile by hand seems a great idea at first, but most people will not bother to write more than the rules for all, install and maybe clean. automake generates dist, distcheck, clean, distclean, uninstall and all these little helpers. These additional targets are a great boon to the sysadmin that will eventually install your software.
Secondly, providing all these targets in a portable and flexible way is quite error-prone. I've done a lot of cross-compilation to Windows targets recently, and the autotools performed just great. In contrast to most hand-written files, which were mostly a pain in the ass to compile. Mind you, it is possible to create a good Makefile by hand. But don't overestimate yourself, it takes a lot of experience and knowledge about a bunch of different systems, and automake creates great Makefiles for you right out of the box.
Edit: And don't be tempted to use the "alternatives". CMake and friends are a horror to the deployer because they aren't interface-compatible to configure and friends. Every half-way competent sysadmin or developer can do great things like cross-compilation or simple things like setting a prefix out of his head or with a simple --help with a configure script. But you are damned to spend an hour or three when you have to do such things with BJam. Don't get me wrong, BJam is probably a great system under the hood, but it's a pain in the ass to use because there are almost no projects using it and very little and incomplete documentation. autoconf and automake have a huge lead here in terms of established knowledge.
So, even though I'm a bit late with this advice for this question: Do yourself a favor and use the autotools and automake. The syntax might be a bit strange, but they do a way better job than 99% of the developers do on their own.

A: For small projects or even for large projects that only run on one platform, handwritten makefiles are the way to go.
Where autotools really shine is when you are compiling for different platforms that require different options.  Autotools is frequently the brains behind the typical
./configure
make
make install
compilation and install steps for Linux libraries and applications.
That said, I find autotools to be a pain and I've been looking for a better system.  Lately I've been using bjam, but that also has its drawbacks.  Good luck finding what works for you.

A: I dont feel I am an expert to answer this but still give you a bit analogy with my experience.
Because upto some extent it is similar to why we should write Embedded Codes in C language(High Level language) rather then writing in Assembly Language.
Both solves the same purpose but latter is more lenghty, tedious ,time consuming and more error prone(unless you know ISA of the processor very well) .
Same is the case with Automake tool and writing your own makefile.
Writing Makefile.am and configure.ac is pretty simple than writing individual project Makefile.


text:
Q: ValueError: operands could not be broadcast together with shapes (6,) (12,) For a list of arrays, I wrote a simple code. Let say that
A=[[1,2,3,4,5,6], [7,8,9,10,11,12], [2,5,6,7,8,1], [3,3,3,3,3,3]].
I want to write a function that for a simple function f(X,Y)=X+Y where X, Y are arrays of A, provide the inverse.
function should take Q and predict X and Y for it. To do it, I wrote a function that for each query array Q, it start to compute all f(A[i],A[j]) and then compute |f(A[i],A[j])-Q| and create a 4*4 of these differences. My problem is that my function does not work and get error.
d=np.full((4, 4), np.inf)
def prediction(Q):
    for i in range(4):
        for j in np.arange(i, 4):
            o= np.asarray(A[i])*1.2+np.asarray(A[j])
            d[i,j]= np.linalg.norm(np.asarray(o)-np.asarray(Q))
    return d

I defined c as: c=A[1]+A[3]
and error I get is:
ValueError                                Traceback (most recent call last)
<ipython-input-120-456401dffe19> in <module>
----> 1 prediction(c)

<ipython-input-117-8b76ff003549> in prediction(Q)
      4         for j in np.arange(i, 4):
      5             o= np.asarray(A[i])*1.2+np.asarray(A[j])
----> 6             d[i,j]= np.linalg.norm(np.asarray(o)-np.asarray(Q))
      7     return d

ValueError: operands could not be broadcast together with shapes (6,) (12,)

why is this happening?


text:
Q: jquery code to javascript pure on select box Hello I'm having trouble passing this code from jquery to pure js
i have this:

function xd() {
  const dropDown = document.querySelector(".dropdown-el");
  dropDown.addEventListener("click", event(event));
  function event(e){
    e.preventDefault();
    e.stopPropagation();
    dropDown.classList.add('expanded')

  }
}
.dropdown-el {
     margin-top: 20vh;
     min-width: 12em;
     position: relative;
     display: inline-block;
     margin-right: 1em;
     min-height: 2em;
     max-height: 2em;
     overflow: hidden;
     top: 0.5em;
     cursor: pointer;
     text-align: left;
     white-space: nowrap;
     color: #444;
     outline: none;
     border: 0.06em solid transparent;
     border-radius: 1em;
     background-color: #cde4f5;
     transition: 0.3s all ease-in-out;
}
 .dropdown-el input:focus + label {
     background: #def;
}
 .dropdown-el input {
     width: 1px;
     height: 1px;
     display: inline-block;
     position: absolute;
     opacity: 0.01;
}
 .dropdown-el label {
     border-top: 0.06em solid #d9d9d9;
     display: block;
     height: 2em;
     line-height: 2em;
     padding-left: 1em;
     padding-right: 3em;
     cursor: pointer;
     position: relative;
     transition: 0.3s color ease-in-out;
}
 .dropdown-el label:nth-child(2) {
     margin-top: 2em;
     border-top: 0.06em solid #d9d9d9;
}
 .dropdown-el input:checked + label {
     display: block;
     border-top: none;
     position: absolute;
     top: 0;
     width: 100%;
}
 .dropdown-el input:checked + label:nth-child(2) {
     margin-top: 0;
     position: relative;
}
 .dropdown-el::after {
     content: "";
     position: absolute;
     right: 0.8em;
     top: 0.9em;
     border: 0.3em solid #3694d7;
     border-color: #3694d7 transparent transparent transparent;
     transition: 0.4s all ease-in-out;
}
 .dropdown-el.expanded {
     border: 0.06em solid #3694d7;
     background: #fff;
     border-radius: 0.25em;
     padding: 0;
     box-shadow: rgba(0, 0, 0, 0.1) 3px 3px 5px 0px;
     max-height: 15em;
}
 .dropdown-el.expanded label {
     border-top: 0.06em solid #d9d9d9;
}
 .dropdown-el.expanded label:hover {
     color: #3694d7;
}
 .dropdown-el.expanded input:checked + label {
     color: #3694d7;
}
 .dropdown-el.expanded::after {
     transform: rotate(-180deg);
     top: 0.55em;
}

              <input
                type="radio"
                name="sortType"
                value="Relevance"
                checked="checked"
                id="sort-relevance"
              />Relevance
              <input
                type="radio"
                name="sortType"
                value="Popularity"
                id="sort-best"
              />Product Popularity
              <input
                type="radio"
                name="sortType"
                value="PriceIncreasing"
                id="sort-low"
              />Price Low to High
              <input
                type="radio"
                name="sortType"
                value="PriceDecreasing"
                id="sort-high"
              />Price High to Low
              <input
                type="radio"
                name="sortType"
                value="ProductBrand"
                id="sort-brand"
              />Product Brand
              <input
                type="radio"
                name="sortType"
                value="ProductName"
                id="sort-name"
              />Product Name

and this is the jquery code that I need to pass to javascript:
$('.dropdown-el').click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).toggleClass('expanded');
  $('#'+$(e.target).attr('for')).prop('checked',true);
});
$(document).click(function() {
  $('.dropdown-el').removeClass('expanded');
});

Basically I tried to add an event to add the class and remove it, but without success, I can't think of how to add and remove the class: "expanded" correctly
Could someone help me how can I fix this?

A: 1st: You need to call the xd() function
2nd: Instead of event(event) you can use function(e){ event(e);  }
3rd: To remove the class use .remove instead of .add
I changed the nested functions to expand and close .. see the next code

function xd() {
  const dropDown = document.querySelector(".dropdown-el");
  dropDown.addEventListener("click", function(e){expand(e)});
  document.addEventListener("click", close);
  function expand(e){
    e.preventDefault();
    e.stopPropagation();
    dropDown.classList.add('expanded');
  }
  function close(){
    dropDown.classList.remove('expanded');
  }
}
xd();
.dropdown-el {
     margin-top: 20vh;
     min-width: 12em;
     position: relative;
     display: inline-block;
     margin-right: 1em;
     min-height: 2em;
     max-height: 2em;
     overflow: hidden;
     top: 0.5em;
     cursor: pointer;
     text-align: left;
     white-space: nowrap;
     color: #444;
     outline: none;
     border: 0.06em solid transparent;
     border-radius: 1em;
     background-color: #cde4f5;
     transition: 0.3s all ease-in-out;
}
 .dropdown-el input:focus + label {
     background: #def;
}
 .dropdown-el input {
     width: 1px;
     height: 1px;
     display: inline-block;
     position: absolute;
     opacity: 0.01;
}
 .dropdown-el label {
     border-top: 0.06em solid #d9d9d9;
     display: block;
     height: 2em;
     line-height: 2em;
     padding-left: 1em;
     padding-right: 3em;
     cursor: pointer;
     position: relative;
     transition: 0.3s color ease-in-out;
}
 .dropdown-el label:nth-child(2) {
     margin-top: 2em;
     border-top: 0.06em solid #d9d9d9;
}
 .dropdown-el input:checked + label {
     display: block;
     border-top: none;
     position: absolute;
     top: 0;
     width: 100%;
}
 .dropdown-el input:checked + label:nth-child(2) {
     margin-top: 0;
     position: relative;
}
 .dropdown-el::after {
     content: "";
     position: absolute;
     right: 0.8em;
     top: 0.9em;
     border: 0.3em solid #3694d7;
     border-color: #3694d7 transparent transparent transparent;
     transition: 0.4s all ease-in-out;
}
 .dropdown-el.expanded {
     border: 0.06em solid #3694d7;
     background: #fff;
     border-radius: 0.25em;
     padding: 0;
     box-shadow: rgba(0, 0, 0, 0.1) 3px 3px 5px 0px;
     max-height: 15em;
}
 .dropdown-el.expanded label {
     border-top: 0.06em solid #d9d9d9;
}
 .dropdown-el.expanded label:hover {
     color: #3694d7;
}
 .dropdown-el.expanded input:checked + label {
     color: #3694d7;
}
 .dropdown-el.expanded::after {
     transform: rotate(-180deg);
     top: 0.55em;
}

    <input
      type="radio"
      name="sortType"
      value="Relevance"
      checked="checked"
      id="sort-relevance"
    />Relevance
    <input
      type="radio"
      name="sortType"
      value="Popularity"
      id="sort-best"
    />Product Popularity
    <input
      type="radio"
      name="sortType"
      value="PriceIncreasing"
      id="sort-low"
    />Price Low to High
    <input
      type="radio"
      name="sortType"
      value="PriceDecreasing"
      id="sort-high"
    />Price High to Low
    <input
      type="radio"
      name="sortType"
      value="ProductBrand"
      id="sort-brand"
    />Product Brand
    <input
      type="radio"
      name="sortType"
      value="ProductName"
      id="sort-name"
    />Product Name

How to remove a class from elements in pure JavaScript?
How can I change an element's class with JavaScript?
How to get the HTML for a DOM element in javascript
How to get innerHTML of this element in javascript?
How to change HTML element value using javascript?
.parents() without jquery - or querySelectorAll for parents


text:
Q: Loading icon on IndicatingAjaxButton and IndicatingAjaxLink not showing I am having issues with the loading icon on the IndicatingAjaxButton and
IndicatingAjaxLink. Previously I was on Wicket 9.0.0-M4 and the icons were working
fine. But after upgrading to Wicket 9.0.0-M5 (or later versions), I'm not
able to see the loading icon any longer.
I checked and found that the AjaxIndicatorAppender now has the
hidden attribute instead of the style=display:none. However, when I click
the IndicatingAjaxButton, it will still append the style=display:inline as
before (with the hidden attribute still present).
I've not done any changes to the dependency, only upgrade the Wicket versions. Is there anything that I would need for the upgrade for the button to work?
Please advise. Thank you.


text:
Q: How to access elements from a javascript array for an email sent with PHP/HTML So I am working on a webpage that generates a javascript array from the date element in html.
That array itself works fine, and I am able to print it to the webpage by using a command like this:
document.getElementById("demo").innerHTML = week[0];

to access the "week" array generated within javascript and to paste it to an HTML span element on the webpage.
However, this is a webpage that sends emails using the data that the user inputs to the page, and while I am able to get all of the rest of the data from the user, I am unsure as to how to grab the data from this javascript array for the email.
The email is currently formatted using HTML with php variables. I thought about using a php array, but every solution I look up for that seems either to be for a different case or too complicated for me to dissect and repurpose.
So what I need is a solution like one of the following:
-The ability to copy this javascript array into a php array that I can then access for the email.
-The ability to access this javascript array within the HTML for the email
This is all contained within a php file on server (the HTML markup, the javascript functions and the php).
Thank you,
Michael
EDIT: I found this thread: Pass Javascript Array -> PHP
      and tried their solution with this code:
Javascript:
JSON.stringify(week);

PHP:
$datesOfWeek = json_decode($_POST['week']);

But whenever I try to access the elements of the array and print them out in the email, nothing prints out for these elements.

A: I'm not sure what you exactly want to achieve but if you want to send a data from js (on client) along with form data to php script (on server) you should simply serialize your array and put as value of additional (hidden) form field. In php script you can somehow deserialize a value of that field (it depends on the format of you choice)
//EDIT: Here is js script example that can you use http://jsfiddle.net/zyt2kcmv/
var myArrayToSend = ["val1", "val2"]
var arrayField = document.querySelector("[name=jsArray]");
arrayField.value = JSON.stringify(myArrayToSend)

On the server side you just need to deserialize value of $_POST["jsArray"] (use library for json or simple regex). Instead of JSON.stringify you can use myArrayToSend.join(";") and then use split method in pho to "deserialize" that string.


text:
Q: Python PyMongo Count Occurrences of Array Item The values I need to count are an array of values so rather than $myField being the key to an item, it's the array elements I need to count so the number of corn, wheat, barley in all the documents.
"myField": [
  "corn",
  "wheat"
],

This is the code for a single item:
for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

A: Now it's time for $unwind, which transforms an array of values into a series of documents, each with a single value where the array had been:
c = MongoClient().test.collection
c.delete_many({})
c.insert_many([
    {"myField": ["corn", "wheat"]},
    {"myField": ["corn", "barley"]},
    {"myField": ["hops"]},
])

for result in c.aggregate([{
    "$unwind": "$myField"
}, {
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

The output:
barley: 1
wheat: 1
hops: 1
corn: 2


text:
Q: Regex Grouping - Matching / Not Matching occurrences I was practicing my regex groups in VB.Net while reading my new cookbook and wondered if it's possible to group One set of chars, numbers or what ever the desired match should be into One group and what ever else does not match into another. Keep in mind this is only for fun and about me learning. Example string i will match.
HelloWorld123
Public Class Form1
Private Sub foo()
    Dim text = "HelloWorld123"
    Dim m = New System.Text.RegularExpressions.Regex("(?i)[a-z]").Matches(text)

End Sub
End Class

So now all the letters are in group 0, thats fine but how can i list ANY thing else into group 1 thats not in group 0? A better example would be say i had a list of chars !"£ that i wanted in group 0 and any thing else in group 1, the only way i could possible think and thats not saying this would work is duplication. ([!""£])([^!""£]) not saying thats valid but my concern is if this lists grows so does the duplication.

A: Well you could negate the character class, e.g. [^a-z] will match any character except a through z, and then use an alternation (|) to capture them separately:
Dim m = New System.Text.RegularExpressions.Regex("(?i)[a-z]|([^a-z])").Matches(text)

But for that matter, you could just match any character (.) like this:
Dim m = New System.Text.RegularExpressions.Regex("(?i)[a-z]|(.)").Matches(text)

Here, anything that's not matched by the first pattern, [a-z], will be matched by the second pattern, ., and captured in group 1. This works because the regex engine will attempt to find matches starting from the first pattern on the left of the alternation, then moving to the right.


text:
Q: Advanced text editor control for .NET Windows apps I'm looking for a control that will help me to create HTML code for inserted text.
It should be something like extended RichTextBox, where I can:

*

*write some text inside,

*format my text using basic functions (fonts, sizes, colors, etc.),

*link images,

*export my text as HTML.

It could be WPF control as well.
Good example is StackOverflow's post editor:

A: You are asking for a WYSIWYG text input.
This normally works by a javascript class, which overrides a multiline textbox.
When the input is submitted to the server, it is then supplied as HTML.
This is one I have used in the past.
http://www.tinymce.com/
There are loads, as this is a common requirement.
If you want others, search google for "WYSIWYG editors".
Hope that helps.


text:
Q: Crop uiimage as screen size My application have an function that allow user to move and scale the image just like setting allowsEditing = YES with UIImagePickerController.
My approach is having a scrollview which allow user to zoom with level 1-4
There is only a image view on the scrollview.
At the end, I want to crop the image as the screen size. How can I do it?

A: The trick is to capture the layer of the view containing the scaled / rotated image. In this case you need to capture the scrollview layer NOT the image itself.
I have a UIImage capture category for this...check out my article and download the source code.
UPDATE: to crop part of the image as per the comment below...
First capture the whole view then crop the image to the specified rect using the following method in the UIImage+Resize category (also in the article...)
- (UIImage *)croppedImage:(CGRect)bounds;


text:
Q: What would be the opposite of onclick="myFunction()"? NOT A DUPLICATE because I'm asking for an "offclick" event (if any) for the purpose of hiding an element, not how to hide the element.
I have a container with display: none; that it's only shown when clicking on a <textarea> tag by using onclick="myFunction()". However, I'd like to set the container back to display: none; once it is clicked outside the <textarea>.
Is there any offclick equivalent for this?
  function myFunction() {
  $('.testing').css({
    display: 'inline-block'
  });
}

.testing {
  display: none;
}

  <textarea onclick="myFunction()" placeholder="Write something..."></textarea>

A: Most probably you will have to look into onMouseUp event.
https://www.w3schools.com/jsref/event_onmouseup.asp

A: You can use onblur attribute within your html tag and give it the function from your javascript.
For example, here i have an input, and when i click and write stuff there, the background color of the input changes to green, but when i click outside the input, the background color changes back to white.
Hope this helped. ^^
<input type="text" onclick="makeBackgroundColorGreen()" onblur="resetBackgroundColortoWhite">

A: You'd need a listener at the window level and then hide it depending on whether the click was made outside the textarea (target), but only if the textarea is visible, otherwise it would be pointless making the comparison.

A: $(document).click(function(event) {
    if (!$(event.target).is(".testing")) {
        $(".testing").hide();
    }
});

A:     menu.onclick = () =>{
  menu.classList.add('fa-times');
  navbar.classList.add('active');
}

    enter code here

window.onscroll = () =>{
  menu.classList.remove('fa-times');
  navbar.classList.remove('active');
}


text:
Q: Kotlin/Native Garbage collection on iOS and Android I need to develop a multiplatform module in Kotlin Native for iOS and Android. According to kotlinlang documentation:

Objective-C and Swift use reference counting. Kotlin/Native has it's own garbage collection too. Kotlin/Native garbage collection is integrated with Objective-C/Swift reference counting.

Does it mean that Kotlin/Native compiled for iOS does not use CMS (Concurrent Mark Sweep) and uses ARC(Automatic Reference Counting)?
Is it possible that common module which written in Kotlin and compiled for iOS might leak and the same module compiled for Android might be completely fine?

A: Kotlin/Native does not use Concurrent Mark-Sweep garbage collector even on Android. It uses an automated reference counter with a cycle collector to collect cyclical garbage (https://github.com/JetBrains/kotlin-native/blob/master/FAQ.md). So should behave more-or-less same way on both platforms.


text:
Q: What kind of forces would follow only the second part of shell theorem? What kind of forces would follow only the second part of shell theorem? General expression of a force which would cancel out inside a uniform hollow shell. What about any closed surface?

A: I don't think that there is a general expression but most of the $1/r^2$  proportional following forces are cancelling in a sphere and for electrostatic force they can be cancelled inside any closed conductor where charges can redistribute.


text:
Q: What are possible ways of assigning an array's first and last item as well as the array of items in between each to a separate variable? let's say I have the following data array
["New York", "Madrid", "Roma"]

And I have 2 other variables and another array
firstValue = '';
middlesValues = []
lastValue = ''

output
firstValue = 'New York'
middlesValues = ['Madrid']
lastValue = 'Roma'

And I would like for example to put the first value in the array each time in a variable, the middle values in an array and the last value in the last variable.
And if I have only two values in the array, to put only the first value and the last one in the 2 variables.
How can I proceed.

A: Use array.slice to get the subarray, returns an empty array if you only have 2 elements.

const array= ["New York", "Madrid", "Roma"];

const firstValue = array[0];
const middlesValues = array.slice(1, array.length - 1);
const lastValue = array[array.length - 1];

console.log(firstValue);
console.log(middlesValues);
console.log(lastValue);

A: Use Array#shift to get the first element, Array#pop to get the last, and the rest would be the middle ones:

const partition = (arr = []) => {
  const array = [...arr];

  const firstValue = array.shift();
  const lastValue = array.pop();
  const middlesValues = array;

  return { firstValue, middlesValues, lastValue};
}

console.log( partition(["New York", "Madrid", "Boston", "Roma"]) );
console.log( partition(["New York", "Madrid", "Roma"]) );
console.log( partition(["New York", "Madrid"]) );
console.log( partition(["New York"]) );
console.log( partition([]) );

A: The approach depends on whether the OP wants the original data to be mutated or not.
The shortest non mutating way is to use a combination of array destructuring and pop ...
let [firstValue, ...middlesValues] = array;
let lastValue = middlesValues.pop();

possible approaches could be ...

// - approach does not mutate the original data.
// - it does so by using array destructuring and `pop`.
let sampleData = ["New York", "Madrid", "Roma", "Paris"];

let [firstValue, ...middlesValues] = sampleData;
let lastValue = middlesValues.pop();

console.log({ firstValue, lastValue, middlesValues, sampleData });

sampleData = ["New York", "Madrid"];

[firstValue, ...middlesValues] = sampleData;
lastValue = middlesValues.pop();

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log('\n');

// - approach does not mutate the original data.
// - it does so by uitlizing `at` and `slice`.
sampleData = ["New York", "Madrid", "Roma", "Paris"];

firstValue = sampleData.at(0);
lastValue = sampleData.at(-1);
middlesValues = sampleData.slice(1, -1);

console.log({ firstValue, lastValue, middlesValues, sampleData });

sampleData = ["New York", "Madrid"];

firstValue = sampleData.at(0);
lastValue = sampleData.at(-1);
middlesValues = sampleData.slice(1, -1);

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log('\n');

// - approach does mutate the original data.
// - it does so by by choosing the proven way of `shift` and `pop`.
sampleData = ["New York", "Madrid", "Roma", "Paris"];

firstValue = sampleData.shift();
lastValue = sampleData.pop();
middlesValues = sampleData;

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log(
  '(middlesValues === sampleData) ?..',
  (middlesValues === sampleData)
);
sampleData = ["New York", "Madrid"];

firstValue = sampleData.shift();
lastValue = sampleData.pop();
middlesValues = sampleData;

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log(
  '(middlesValues === sampleData) ?..',
  (middlesValues === sampleData)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }


text:
Q: Running an application using JavaScript I have an application (IP2SI2IP.exe ) and I wrote this command in JS to run it :
<script type="text/javascript">
function run(){
wshShell=new ActiveXObject("Wscript.shell"
);
wshShell.Run("C:/Windows/System32/cmd.exe",1,false)
wshShell.Run("IP2SI2IP /S /N xxx.SES",1,false)
}
</script>

This app converts the specific file with SES extension (for example : xxx.SES ) IP unit to SI unit. Anytime when I have a new input file (for example yyy.SES), I have to re-type it manually in front of the IP2SI2IP /S /N command the run it again.
I'm looking for another command that it can first: find the file with SES extension from the related folder then puts this SES file in front of the "IP2SI2IP /S /N" command and run it by itself.
Thanks!


text:
Q: Differentiate between albums and images in Imgur gallery First of all, apologies as this is quite a narrow topic so I understand if it is removed. Imgur links come in several formats, as below:
http://i.imgur.com/kMoI9Vn.jpg
http://i.imgur.com/f7VXJQF
http://imgur.com/S1dZBPm
http://imgur.com/a/liD3a
http://imgur.com/gallery/HFoOCeg

In the Imgur API docs, there are relevant two endpoints. One for albums and the other for images. Normally, there is no issue distinguishing between an image, and an album as album URLs are prefixed with /a/.
However, the following are both valid gallery URLs:
http://imgur.com/gallery/HFoOCeg
http://imgur.com/gallery/clWTb

The first is an image, and the second is an album. The gallery category has two relevant endpoints, image and album. Trying to use submit a request for an album to the image endpoint and vice versa results in a 404 error.
Is there any way when provided with just the ID (eg: HFoOCeg) to determine if it is an album or image without sending multiple requests?

A: If you are using ajax, you might find this helpful.  It picks through the data from https://api.imgur.com/3/gallery/{hash} and puts a condition in the success function to distinguish an album from a single image.  So far it seems to work.  Incidentally, re my comment above, I have found out that album and image ids are not consistently 5 and 7 chars long respectively.
Grab the hash from a url like http://imgur.com/gallery/vTTHZ whatever way you like.
Then:
var thehash = 'vTTHZ';
$.ajax({
      type: "GET",
      url: "https://api.imgur.com/3/gallery/" + thehash,
      dataType: "json",
      headers:{
      'Authorization':'Client-ID xxxxxxxxxxxxxx'
      },
      success: function(data) {
       if(data.data.is_album === true) {
        var dlength = data.data.images.length;
        for(i=0; i < dlength; i++) {
         $('#mydiv').append('
' + data.data.images[i].link + '
');
         }
       } else
       {
        $('#mydiv').html('
' + data.data.link + '
');
       }
        console.log(data);
      }
    });


text:
Q: Should I write "WP page" or "WP's page? I am writing a scientific paper and must refer to a page of Wikipedia (WP for short). Should I write "WP page" or "WP's page"? "WP's page" seems to me to be correct, but somehow it sounds strange...

A: I'm not so sure about the abbreviation WP, but this is a question about a common process in the development of the English language where a noun, especially a genitive becomes functionally an adjective.
For example, I am typing on a computer keyboard. The intent here is "computer's keyboard"  or "keyboard of the computer" -- both being the two forms of genitive in English. But over time the genitive noun "computer's" have become shortened to simply an adjectival form of the noun, "computer keyboard."
This morning I drove to work in a car, powered by an engine. The engine was the "car's engine" but we usually just call it in the shortened form "car engine". In Washington DC is a monument to our 16th President, but today it is not called Lincoln's Memorial, it is called the Lincoln Memorial. It was paid for by the United States' government (genitive), but is now managed by the United States government.
If you had a web site Fernando, a page on it would be Fernando's page, because you are not as well known as Wikipedia. However, Wikipedia is well known and ubiquitous enough that I think Wikipedia page would be considered the normal usage.
With your abbreviation though, it might not work as well.


text:
Q: Unmatched quotation mark issue in SAS As is known to all, SAS needs special care to quotation marks inside a sentence.
E.g.
%let quoted="I'd like to";
data temp;
    set temp;
    quoted="&quoted";
run;

error is encounterred when submitting.
In fact I need to copy data to one dataset from another one, in which there are a lot of records containing quotation marks. When assigning, error occurrs and data step stop executing, causing rest of the code to be invalid. So in this case, it's impossible to modify original data set by adding duplicated quotation marks, which doesn't make sense.
So instead of having to add a duplicated one, like, "I''d like to", is there any other way of avoiding the error, or making data step keeping executing?
Thanks,

A: When using the macro language (including the %let command) you do not want to use quotes to identify text strings.  To place a single quote in a string you must use one of the macro utility masking functions such as %str().  The correct syntax to place a single unmatched quote in a macro variable using %let is shown below.  The % symbol before the single quote is an escape character to tell SAS that the following character (a single quote) should be used as a literal.  Also note that I've removed the double quotes from the %let as they are not required.
%let quoted=%str(I%'d like to);
data temp;
    quoted="&quoted";
run;

Cheers
Rob

A: I'm not sure what you're trying to achieve in the actual situation, but in the above situation it can be solved removing the double quotation marks in the data step.
%let quoted="I'd like to";
data temp;
    set temp;
    quoted=&quoted;
run;


text:
Q: How do I make certain tables searchable by google? I'm using perl, and I want others to find certain issues on my site using google. How can I do that?
In wordpress (php) there is this option:

I would like my blog to be visible to
  everyone, including search engines
  (like Google, Bing, Technorati) and
  archivers

I would like to do the same using perl.

A: *

*Express the data in HTML (I'd use a combination of Template-Toolkit and DBIx::Class (assuming you mean a database table))

*Expose it over HTTP (I'd tend towards Catalyst for this)

*Link to it (or use a sitemap xml)

A: Your HTML content (Of course, you have to find a way to display your data in HTML - either static HTML pages or dyanmic content) could be crawled and archived by Google without any effort on your part (this happens all the time, and is probably how most people do it), but it could help if you submit a google sitemap. Here's a page with more about Google Sitemaps: http://www.google.com/sitemap.html
Also, search on google for "Google sitemap" to get more info ;)
Beware though: SEO (Search Engine Optimization) is not an exact science (despite what anyone tells you).

A: What David Dorward said.
Google will not look into your database; you must create web pages containing all the information you want exposed and then point google to those pages by submitting a sitemap.


text:
Q: Sencha Touch 2 : Is it possible to achieve inheritance for view objects? I need some suggestions on the following aspect.
BackGround:
I am working on Sencha 2 MVC Application.
In my application, I have a toolbar on several screens.
Currently, I have created a class for the toolbar and then adding the toolbar using xType on the required views as xType: 'customizedToolbar'.
But instead of that,I want to declare a parent class where this toolbar is defined and then extend this parent class from all other child classes so I can avoid adding the toolbar everytime using xType.
For an example, below is the sample application,
Ext.application({
            app:'testmixin',
            autoCreateViewport: true,
        launch: function()    {

// Parent Class
        Ext.define('MyParentClass', {
            extend: Ext.Panel,
                mixinConfig: {
                        id: 'myMixinIdentifier'
                         },
                config: {
                // Is there a way that the items defined in this class will be added in the child class
                items:[

                    {
                        xtype : 'emailfield',
                        name : 'name',
                        id : 'userName',
                        placeHolder : 'Email',

                    },

                    ]

                    },

                });

                // Main Class
    Ext.define('MyMainClass', {
    // Benefit of using mixins is that you can add to your class with one
    // or more mixins, rather than by extending another class
            extend: Ext.Panel,
            mixins: {
                myMixinIdentifier: 'MyParentClass'
            },

        constructor: function(config) {
            this.callParent(arguments);
            this.sample();
            },
        });

    var panel = Ext.create('MyMainClass');
            panel.test('abc');
            panel.test1('abc');
            Ext.Viewport.add(panel);

}

    });

Is is possible to add an item in the Parent class and it will be added automatically in the child class thru inheritance?
Thanks
  Gendaful

A: The following code does not use mixing but basic class inheritance :
Ext.Loader.setConfig({
    enabled : true
});

Ext.application({
    name : ('SF' || 'SenchaFiddle'),

    launch : function() {

        Ext.define('PanelWithToolbar', {
            extend: 'Ext.Container',
            xtype: 'panelwithtoolbar',

            config: {
                items: [{
                    xtype: 'toolbar',
                    docked: 'top'
                }]
            }
        });

        Ext.define('PanelA', {
            extend: 'PanelWithToolbar',
            xtype: 'panela'
        });

        Ext.define('PanelB', {
            extend: 'PanelWithToolbar',
            xtype: 'panelb'
        });

        Ext.create('Ext.TabPanel', {
            fullscreen: true,
            tabBarPosition: 'bottom',

            defaults: {
                styleHtmlContent: true
            },

            items: [
                {
                    xtype: 'panela',
                    title: 'Home',
                    iconCls: 'home',
                    html: 'Home Screen'
                },
                {
                    xtype: 'panelb',
                    title: 'Contact',
                    iconCls: 'user',
                    html: 'Contact Screen'
                }
            ]
        });
    }
});

Here is the fiddle


text:
Q: FullSimplify fail with general assumption Assume I want to simplify this:
-a^(-1) ** b^(-1) + (b ** a)^(-1)

given assumption:
$\frac{1}{b\_\text{**}a\_}=\frac{1}{a\_}\text{**}\frac{1}{b\_}$
Then it correctly evaluate to 0. But when I give this assumption:
$\frac{\text{n$\_$}}{\text{x$\_$}\text{**}\text{y$\_$}}=\frac{\text
   {n$\_$}}{\text{y$\_$}}\text{**}\frac{\text{n$\_$}}{\text{x$\_$}
   }$
it fail to calculate correctly.
When expand assumptions to InputForm, I see that
$\frac{1}{b\_\text{**}a\_}=\frac{1}{a\_}\text{**}\frac{1}{b\_}$ is ((b_)**(a_))^(-1) == (a_)^(-1)**(b_)^(-1), and
$\frac{\text{n$\_$}}{\text{x$\_$}\text{**}\text{y$\_$}}=\frac{\text
   {n$\_$}}{\text{y$\_$}}\text{**}\frac{\text{n$\_$}}{\text{x$\_$}
   }$ is (n_)/(x_)**(y_) == ((n_)/(y_))**((n_)/(x_)).
So, maybe the difference between ^(-1) and / make Simplify run wrong.
Question:

*

*Why don't Mathematica always use /?

*Why does Simplify think 1/a different from a^(-1)?

A: I think the problem is because the pattern n_/x_ ** y_ doesn't match the expression 1/b ** a. You can see that in the full form:
FullForm[1/b ** a]
(*Power[NonCommutativeMultiply[b,a],-1]*)

FullForm[n/x ** y]
(*Times[n,Power[NonCommutativeMultiply[x,y],-1]]*)

So this deosn't work
Simplify[- (1/a) ** (1/b) + 1/b ** a,
 Assumptions -> {n_/x_ ** y_ == (n_/y_) ** (n_/x_)}]
(* -(1/a) ** (1/b) + 1/b ** a *)

but this does
Simplify[- (c/a) ** (c/b) + c/b ** a,
 Assumptions -> {n_/x_ ** y_ == (n_/y_) ** (n_/x_)}]
(* 0 *)

The simplest way to deal with problem is to treat it as a special case:
assums = {n_/x_ ** y_ == (n_/y_) ** (n_/x_), 1/x_ ** y_ == (1/y_) ** (1/x_)};

Simplify[- (1/a) ** (1/b) + 1/b ** a, Assumptions -> assums]
Simplify[- (2/a) ** (2/b) + 2/b ** a, Assumptions -> assums]
Simplify[- (c/a) ** (c/b) + c/b ** a, Assumptions -> assums]
(* 0 *)
(* 0 *)
(* 0 *)

Edit
A better way would be define a transformation function:
trans[exp_] := exp /. {(n_/y_) ** (n_/x_) -> n/x ** y, 1/x_ ** y_ -> (1/y) ** (1/x)}

Simplify[-(1/a) ** (1/b) + 1/b ** a, TransformationFunctions -> {Automatic, trans}]
Simplify[-(2/a) ** (2/b) + 2/b ** a, TransformationFunctions -> {Automatic, trans}]
Simplify[-(c/a) ** (c/b) + c/b ** a, TransformationFunctions -> {Automatic, trans}]
Simplify[(1/2) ** (1/3) - 1/3 ** 2, TransformationFunctions -> {Automatic, trans}]
(* 0 *)
(* 0 *)
(* 0 *)
(* 0 *)


text:
Q: Angular loading bar error I am getting error with angular loading bar
            var _responseError = function (rejection) {
            $http = $http || $injector.get('$http');
            var authData = localStorageService.get('authorizationData');
            var authService = $injector.get('authService');

            if (rejection.status === 401 && authData && authData.isActive == 'true') {
                var deferred = $q.defer(); // defer until we can re-request a new token
                var data = "grant_type=refresh_token&refresh_token=" + authData.refreshToken + "&client_id=" + authData.clientId;
                var baseAddress = $injector.get('baseAddress');
                var dateFormat = "YYYY-MM-DD HH:mm:ss";

                // Get a new token... (cannot inject $http directly as will cause a circular ref)
                $injector.get("$http")
                    .post(baseAddress + 'login', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
                    .then(function (loginResponse) {
                        if (loginResponse.data) {
                            localStorageService.set('authorizationData',
                             {
                                 token: loginResponse.data.access_token,
                                 tokenExpire: loginResponse.data['.expires'],
                                 refreshToken: loginResponse.data.refresh_token,
                                 refreshTokenExpire: loginResponse.data.refreshTokenExpire,
                                 userName: authData.userName,
                                 roleName: loginResponse.data.roleName,
                                 isUserAdmin: loginResponse.data.isUserAdmin,
                                 clientId: 'Self',
                                 isActive: loginResponse.data.isActive
                             });
                            // now let's retry the original request
                            $injector.get("$http")(rejection.config).then(function (response) {
                                // we have a successful response - resolve it using deferred
                                deferred.resolve(response);
                            }, function (response) {
                                deferred.reject(); // something went wrong
                            });
                        }
                        else {
                            deferred.reject(); // login call didn't give us data
                        }
                    },
                    function (response) {
                        // token retry failed, redirect so user can login again
                        deferred.reject(rejection);
                        if (!authInterceptorServiceFactory.isPopup) {
                            authInterceptorServiceFactory.isPopup = true;
                            var hr = moment.utc(moment(new Date()).diff(moment(new Date(authData.refreshTokenExpire)))).format("H");
                            var strHr = hr == 1 ? ' hour' : ' hours';

                            var min = moment.utc(moment(new Date()).diff(moment(new Date(authData.refreshTokenExpire)))).format("m");
                            if (min == 0) {
                                min = 1;
                            }

                            var strMin = min == 1 ? ' minute' : ' minutes';

                            var loginInfo = {
                                userName: authData.userName,
                                password: '',
                                expiryTime: moment.utc(moment(new Date()).diff(moment(new Date(authData.refreshTokenExpire)))).format("HH:mm:ss")
                            };

                            var ngDialog = $injector.get('ngDialog');
                            ngDialog.openConfirm({
                                template: '/app/account/loginDialog.html',
                                className: 'ngdialog-theme-default',
                                controller: 'loginDialogController',
                                showClose: false,
                                data: loginInfo
                            }).then(function (value) {
                                authInterceptorServiceFactory.isPopup = false;
                                //only refresh if GET request was executed
                                if (rejection.config.method == "GET")
                                    $window.location.reload();
                            }, function (reason) {
                                authInterceptorServiceFactory.isPopup = false;
                                // User has decided to logout from login modal so clear all
                                //authentication information, reject the request and redirect to login
                                blockUI.stop();
                                authService.logOut();
                                $location.path('/login');
                                return;
                            });
                        }
                    });

                return deferred.promise; // return the deferred promise
            }
            else if ((rejection.status === 401 && !authData) || (rejection.status === 401 && authData.isActive == 'false')) {

                    blockUI.stop();
                    authService.logOut();
                    $location.path('/login');
            }
            else if (rejection.status === 403) {
                // Unauthorized =  Access Forbidden 403
                // Before navigating away, we need to clear the change tracker changes, otherwise the changes alert will appear.
                blockUI.stop();
                changeTrackerService.clearAllScopeChanges();
                $location.path('/unauthorized');

            }
            return $q.reject(rejection); // **I am getting error here**
        }

and the error is
TypeError: Cannot read property 'config' of undefined
    at error (https://localhost:44303/Scripts/angular-block-ui.js?v=1.3:176:26)
    at https://localhost:44303/Scripts/angular.min.js?v=1.3:109:276
    at h.c.$get.h.$eval (https://localhost:44303/Scripts/angular.min.js?v=1.3:123:139)
    at h.c.$get.h.$digest (https://localhost:44303/Scripts/angular.min.js?v=1.3:120:220)
    at h.c.$get.h.$apply (https://localhost:44303/Scripts/angular.min.js?v=1.3:123:406)
    at p (https://localhost:44303/Scripts/angular.min.js?v=1.3:80:284)
    at J (https://localhost:44303/Scripts/angular.min.js?v=1.3:84:338)
    at XMLHttpRequest.t.onload (https://localhost:44303/Scripts/angular.min.js?v=1.3:85:367) undefined(anonymous function) @ angular.min.js?v=1.3:101b.$get @ angular.min.js?v=1.3:75(anonymous function) @ angular-block-ui.js?v=1.3:19(anonymous function) @ angular.min.js?v=1.3:109c.$get.h.$eval @ angular.min.js?v=1.3:123c.$get.h.$digest @ angular.min.js?v=1.3:120c.$get.h.$apply @ angular.min.js?v=1.3:123p @ angular.min.js?v=1.3:80J @ angular.min.js?v=1.3:84t.onload @ angular.min.js?v=1.3:85
angular.min.js?v=1.3:101 TypeError: Cannot read property 'ignoreLoadingBar' of undefined
    at config.responseError (https://localhost:44303/Scripts/loading-bar.js?v=1.3:129:32)
    at https://localhost:44303/Scripts/angular.min.js?v=1.3:109:276
    at h.c.$get.h.$eval (https://localhost:44303/Scripts/angular.min.js?v=1.3:123:139)
    at h.c.$get.h.$digest (https://localhost:44303/Scripts/angular.min.js?v=1.3:120:220)
    at h.c.$get.h.$apply (https://localhost:44303/Scripts/angular.min.js?v=1.3:123:406)
    at p (https://localhost:44303/Scripts/angular.min.js?v=1.3:80:284)
    at J (https://localhost:44303/Scripts/angular.min.js?v=1.3:84:338)
    at XMLHttpRequest.t.onload (https://localhost:44303/Scripts/angular.min.js?v=1.3:85:367) undefined

A: Don't Use Min For Development
The first thing you need to do in you index page is change the version of Angular you are using.
From
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

To
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js"></script>

Using min is great from production because its smaller and there for faster to interoperate but it has very misleading errors.
Once you have switched to the full Angular post your new error in an edit and I'll add to this answer.


text:
Q: Increment and decrements item quantity based on id (S.NO) I have an app in which allows the user to increment or decrement the in-stock quantity of an item.  When I click an increment or decrement button, all the items are changed at once.  Only the item from the clicked row should get changed.  What am I doing wrong?

html code
  <ion-content class="item">

  <ion-list *ngIf="showList">
      <ion-item *ngFor="let item of items">
        {{ item }}
      </ion-item>
    </ion-list>

  <ion-list>

      <ion-item>
        <ion-row >
          <ion-col width-15>SNo</ion-col>
          <ion-col width-25>PartNo</ion-col>
          <ion-col width-25>Qty</ion-col>
          <ion-col width-15>Price</ion-col>
          <ion-col width-20>Action</ion-col>
        </ion-row>
      </ion-item>

        <ion-item *ngFor="let list of quickOrder; let i = index">
          <ion-row>
            <ion-col width-15>{{list.SNo}}</ion-col>
            <ion-col width-25>{{list.PartNo}}</ion-col>
            <ion-col width-25 class="add">
            <button clear (click)="incrementQty()"><ion-icon name="add-circle" ></ion-icon></button>{{qty}}
            <button clear (click)="decrementQty()"><ion-icon name="remove-circle" ></ion-icon></button>
          </ion-col>
            <ion-col width-15>{{list.Price}}</ion-col>
            <ion-col width-20><button clear (click)="delete(i)"><ion-icon name="close-circle"></ion-icon></button></ion-col>
          </ion-row>
        </ion-item>

  </ion-list>

      <button padding (click)="addToCart();">Add to Cart</button>

</ion-content>

.ts file
import { Component} from '@angular/core';
import { NavController, Slides} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/titlepage/titlepage.html',
})
export class titlePage {
  qty:any;
  constructor(private nav: NavController) {
    this.qty = 1;
  }

  // increment product qty
  incrementQty() {
    console.log(this.qty+1);
    this.qty += 1;
  }

  // decrement product qty
  decrementQty() {
    if(this.qty-1 < 1 ){
      this.qty = 1
      console.log('1->'+this.qty);
    }else{
      this.qty -= 1;
      console.log('2->'+this.qty);
    }
  }
}

A: Since the list is an array of items, the quantity of the items should be present in the list as well. Having only one quantity attribute means it impacts the entire list.
I believe the quick order array looks something like this now
[{SNo: 1, PartNo: S23456, Price: 2500}, {...}, ...]

One way of solving this would be to have a quantity attribute for each item so the quickOrder array looks like
[{SNo: 1, PartNo: S23456, Price: 2500, qty: 3}, {...}, ...].

And the increment and decrement functions also take the index similar to the delete function. The increment function is shown below
incrementQty(index: number) {
    this.quickOrder[index].qty += 1;
}

A better option would be to construct a separate quickOrderItem component which contains its own increment and decrement functions and use the current component as a container for it.
Hope this helps.

A: <ion-card *ngFor="let product of cart; let index=index">

 ₹ {{ item_qty *  product.price  }}

<ion-card>

import { Component, OnInit } from '@angular/core';
import {  NavController, NavParams } from 'ionic-angular';

@Component({
selector: 'page-cart',
templateUrl: 'cart.html',
})
export class CartPage implements OnInit {

item_qty:any;

constructor()
{this.item_qty=1;}

// increment item
inc(){
this.item_qty += 1;
console.log(this.item_qty + 1);
}

//decrements item

dec(){
if(this.item_qty-1 < 1){
this.item_qty = 1;
console.log('item_1->' + this.item_qty)
}
else{
this.item_qty -= 1;
console.log('item_2->' + this.item_qty);
}
}

}


text:
Q: how can i add items to an list view with custom adapter each time i click on the button? what i am trying to do is something look like add to cart thing but on my android app , first of all i have add to cart activity which has all the values i need when i press the button i send my data as put extra to cartList Activity and it display on row and each time i press the button on some item it clear the array and display only one row ! but what i really need to do is when each time i press the button i want it to add on the previous items and display them all .. here is my add to cart activity :
public class AddToCart extends Activity{

    EditText quantity=null;
    TextView total=null;
    TextView name=null;
    TextView price=null;
    TextView ava=null;
    double totalprice=0.0;

    ArrayList<String> listOfItemNames = new ArrayList<String>();
    List<listClass>testList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.info);
        Intent test = getIntent();

        Intent intent = getIntent();
        final String itemprice = intent.getStringExtra("price");
        final String itemname = intent.getStringExtra("item");
        final String itemava = intent.getStringExtra("ava");
        final int imagehandler=intent.getIntExtra("image", 0);
        Log.e("image handler",imagehandler+"");
         name=(TextView)findViewById(R.id.textView2);
         price=(TextView)findViewById(R.id.textView4);
         total=(TextView)findViewById(R.id.textView7);
         ava=(TextView)findViewById(R.id.textView9);
        quantity=(EditText)findViewById(R.id.editText1);
        Button addtocart=(Button)findViewById(R.id.button1);
        ImageView imageview=(ImageView)findViewById(R.id.imageView1);

        name.setText(itemname);
        price.setText(itemprice);
        ava.setText(itemava);
        imageview.setImageResource(imagehandler);

            addtocart.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    final String quantityvalue=quantity.getText().toString();
                    CharSequence currentavaiable=ava.getText();
                    int currentava=Integer.parseInt((String) currentavaiable);
                    Editable checked = quantity.getText();
                    String checkquantity=checked.toString();
                    Log.e("checked ",checked+"");
                    Log.e("check quantity",checkquantity);
                    try{

                if(checkquantity==null){
                    Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
                }

                else{
                    int x=0;
                    double y=0.0;
//                  String xvalue=quantity.getText().toString();
                     x = Integer.parseInt(quantityvalue);
                     Log.e("x",x+"");
                     y = Double.parseDouble(itemprice);
                    Log.e("x",x+"");
                    Log.e("y",y+"");
                     totalprice=x*y;
                    total.setText(totalprice+"");
                    Toast.makeText(AddToCart.this,"your item added succesfully !", Toast.LENGTH_LONG).show();

                }

                Intent newintent=new Intent(AddToCart.this,CartList.class);
                newintent.putExtra("itemname",itemname);
                newintent.putExtra("itemprice",itemprice);
                newintent.putExtra("itemquantity",quantityvalue);
                newintent.putExtra("totalprice",totalprice);
                newintent.putExtra("image", imagehandler);

                startActivity(newintent);
                }//view
                    catch(Exception e){
                        e.printStackTrace();
                    }
                }
            });
    }
}

and here is cart list class :
public class CartList extends Activity {
    ListView list;

    List<CartItems> detailsList = new ArrayList<CartItems>();
    ArrayList<String> listtest=new ArrayList <String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.cart_list);

        initializeComponents();

        detailsList = SetAdapterList();

        CustomAdapter adapter=new CustomAdapter(this,detailsList);

        list.setAdapter(adapter);

    }

    private void initializeComponents()
    {
        list=(ListView)findViewById(R.id.listView1);
    }

    private List<CartItems> SetAdapterList()
    {
        // TODO Auto-generated method stub

        CartItems details;

         List<CartItems> detailsList = new ArrayList<CartItems>();

         try{
         Intent newintent = getIntent();
         final String itemname = newintent.getStringExtra("itemname");
        final String itemprice = newintent.getStringExtra("itemprice");
        final String itemquantity = newintent.getStringExtra("itemquantity");
        final double totalprice = newintent.getDoubleExtra("totalprice", 0.0);
        String totprice=String.valueOf(totalprice);
//      ArrayList <String> itemnames=new ArrayList<String>();
         listtest.add(itemname);
         Log.e("listtest",listtest+"");
        final int imagehandler=newintent.getIntExtra("image", 0);
        Log.e("image handler",imagehandler+"");
        for(int i = 0; i< listtest.size(); i++)
        {
        details = new CartItems(itemname,itemprice,itemquantity,totprice,imagehandler);
        detailsList.add(details);
        }

         }
         catch(Exception e){
             e.printStackTrace();
         }
            return detailsList;
    }

}

and here is my custom adapter :
public class CustomAdapter extends ArrayAdapter<CartItems> {

    Context context;
    List<CartItems>Clist = new ArrayList<CartItems>();

    public CustomAdapter(Context context, List<CartItems> detailsList) {
        super(context, R.layout.single_row, R.id.textView1, detailsList);
        // TODO Auto-generated constructor stub

        this.context=context;
        this.Clist = detailsList;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row=inflater.inflate(R.layout.single_row, parent,false);
        ImageView myimage=(ImageView) row.findViewById(R.id.imageView1);
        TextView items=(TextView)row.findViewById(R.id.textView1);
        TextView totalprice=(TextView)row.findViewById(R.id.textView2);

        items.setText(Clist.get(position).getItemName());
        totalprice.setText(Clist.get(position).getTotalPrice());
        myimage.setImageResource(Clist.get(position).getImage());

        return row;
    }

}

here is my itemcart class :
public class CartItems {

    private String itemName;
    private String itemPrice;
    private String Quantity;
    private String totalPrice;
    private int image;

    public CartItems(String itemname,String itemprice, String quantity, String totalprice2, int image){
        this.itemName=itemname;
        this.itemPrice=itemprice;
        this.Quantity=quantity;
        this.totalPrice=totalprice2;
        this.image=image;
    }
//getter and setters
}

please can anyone help me?? i am so despaired !!

A: You are resetting you arraylist everyime. Instead you add item to it each time you select an item. Follow these steps:
1)change your setadapter function to return item, not itemlist.
private CartItems SetAdapterList()
    {
        // TODO Auto-generated method stub

        CartItems details;
      try{
         Intent newintent = getIntent();
         final String itemname = newintent.getStringExtra("itemname");
        final String itemprice = newintent.getStringExtra("itemprice");
        final String itemquantity = newintent.getStringExtra("itemquantity");
        final double totalprice = newintent.getDoubleExtra("totalprice", 0.0);
        String totprice=String.valueOf(totalprice);
//      ArrayList <String> itemnames=new ArrayList<String>();
         listtest.add(itemname);
         Log.e("listtest",listtest+"");
        final int imagehandler=newintent.getIntExtra("image", 0);
        Log.e("image handler",imagehandler+"");
        for(int i = 0; i< listtest.size(); i++)
        {
        details = new CartItems(itemname,itemprice,itemquantity,totprice,imagehandler);

        }

         }
         catch(Exception e){
             e.printStackTrace();
         }
            return details;
    }

2) after getting this value, just add it to your arraylist. like this:
CartItems item = SetAdapterList();
detailsList.add(item);

Now, when you populate your listView, detailsList will be having all previously selected items too. Just clear detailsList when you want to reset.

A: 1) Add new items to your  detailsList.
2) Call notifyDataSetChanged() for adapter.


text:
Q: How can I write multiple lines to a textbox using python win32? I have a C program that has a textbox component. I want to have a python GUI write text to this text box. Currently, I can write to the textbox HWND using:
def winFunc(hwnd, lparam):
    s = win32gui.GetWindowText(hwnd)
    if s == "":
        win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, 0, lparam)

hwnd = win32gui.FindWindow("Graph Program", None)
win32gui.EnumChildWindows(hwnd, winFunc, text)

This code will write text to the textbox but it cannot append text on a newline to the textbox. Is it possible to read in the text that is currently in the textbox or is it possible to add text to a textbox? I am new to using the windows API. Also, Is it possible to write text as a different color? The text box class is RICHEDIT20A.

A: Appending text

*

*Send an EM_SETSEL message to move the selection to the end of the rich edit control. Use WM_GETTEXTLENGTH to find out how many characters are in the edit control.

*Send an EM_REPLACESEL message to replace the selection. If the selection point is at the end of the control, then replacing is the same as appending.

Don't attempt to use WM_GETTEXT & WM_SETTEXT since it rapidly becomes inefficient, not to mention the fact that the formatting is not preserved.
Formatting text
Use the EM_SETCHARFORMAT to format text.  More details over at MSDN.


text:
Q: How many parameters in this specific linear model with interaction? I have a question where I am not sure about the answer:

A linear model has the following characteristics:
*A dependent variable ($y$)
*One continuous variable ($x_l$), including a quadratic term ($x_1^2$)
*One categorical ($d$ with 3 levels) predictor variable and an interaction term ($d \times x_1$)
How many parameters, including the intercept, are associated with this
  model?

So I thought about:
$y=\beta_0 + \beta_1 x_1 + \beta_2 x_1^2 + \beta_3 d$ + $\beta_4dx_1$
I thought I need 5 parameters for this model, but I was told the answer would be 7. So I guess I did the interaction wrong. So it seems to me I have to model each level of d with x1 with a single interaction. But how would I write this down and why do I need this?

A: The model has 7 parameters because of the 3-category categorical variable which will have 2 ``main effects'' parameters in the model (1 of the categories is omitted as the reference category). There will also be  a parameter for the interaction between each of the levels of the categorical variable with the continuous variable:

*

*Continuous variable main effect

*Quadratic effect

*Category 1 main effect

*Category 2 main effect

*Continuous variable $\times$ category 1 interaction effect

*Continuous variable $\times$ category 2 interaction effect

*Intercept

Using your notation, the regression equation should be
$$y=\beta_0 + \beta_1 x_1 + \beta_2 x_1^2 + \beta_3 d_1 + \beta_4 d_2 + \beta_5d_1x_1 + \beta_6d_2x_1$$

A: I think you need to consider your categorical variable d as three different dummy variables following the value d can take. That would make two more variables, hence 7 variables in total. Does that make any sense?


text:
Q: My pod gets OOM-killed status, but doesn't get killed. Why? I've configured a CronJob with a YAML file (apiVersion: batch/v1beta1) with resource requests and limits, the pod is successfully instantiated and works till its natural end, but when terminates I saw it marked as OOMKilled.
My pod is working with a Docker container, which is started with a bash script that invokes some Java tools (like maven). I tried to setup a MAVEN_OPTS and JAVAOPTS like this:
        env:
          - name: JAVA_OPTS
            value: "-Xms256M -Xmx1280M"
          - name: MAVEN_OPTS
            value: "-Xms256M -Xmx1280M"

That are values lower than the ones of the configured limit in the YAML.
I'd expected that the pod stops in complete status as the last echo of my ENTRY_POINT bash script is shown in the log of the pod but I get the OOMKilled.

A: When Containers have resource requests specified, the scheduler can make better decisions about which nodes to place Pods on. But keep in mind: Compute Resources (CPU/Memory) are configured for Containers, not for Pods.
If a Pod container is OOM killed, the Pod is not evicted. The underlying container is restarted by the kubelet based on its RestartPolicy.
Your container being terminated by OOMKill does not imply the pod to become in a Completed/Error status (unless you're using the RestartPolicy: Never).
If you do a kubectl describe on your pod, the container will be in Running state, but you can find the last restart cause in Last State. Also, you can check how many times it was restarted:
State:          Running
  Started:      Wed, 27 Feb 2019 10:29:09 +0000
Last State:     Terminated
  Reason:       OOMKilled
  Exit Code:    137
  Started:      Wed, 27 Feb 2019 06:27:39 +0000
  Finished:     Wed, 27 Feb 2019 10:29:08 +0000
Restart Count:  5


text:
Q: Find same observations of a list/matrix in another matrix For a marketing class I have to write a function that calculates the retention rate of the customers (probability that a customer still is a customer). I've come so far that I isolated the ids of the individual customers and stored them in the matrix first.transactions.data. I then split them into cohorts (group of customers by time) with split() and stored them in the list cohort.
Now comes my problem: I calculated another sub-matrix from the full data set called final.period.data where I will calculate the retention rate. However, therefore I have to isolate the ids in final.period.data for each cohort. My instructor told me that I should create an additional column in final.period.data that shows TRUE or FALSE depending on whether the cohort's id and final.period.data's id are the same. For this I tried to use exists, but I always receive error messages. I tried the following:
final.period.data <- if(exists(cohort$'1'$id, where = final.period.data$id) final.period.data$same = TRUE)

but always receive error messages such as: unexpected symbol or invalid first argument. I also tried to convert the list cohort into a matrix but this didn't help either. How do I have to change the exist command or is there a simpler way to locate cohort's ids in final.period.data?
Thank you for your help.

A: You can just create a function that does what you want:
funct <-(final.period.data){
 if (final.period.data$cohort =='1' & final.period.data$id ==<condition2>){
   #Change the number for the TRUE condition}
 else{ #If it doesn't fit the two conditions
  #Change the number for the FALSE condition}
}
vector <- c(nrow(final.period.data))
final.period.data <- cbind(vector)

And use it as the apply function. Here will you find more information about apply
But I usually do it with a for loop, first creating the new column and then adding it to the data frame.


text:
Q: Trying to scrape a dynamic javascript table with Selenium, but getting "Unable to locate element" How can I scrape the information of this website (https://polkadot.subscan.io/account/12xtAYsRUrmbniiWQqJtECiBQrMn8AypQcXhnQAc6RB6XkLW?tab=transfer) using Selenium?
The main goal is to scrape the "From, To, Value and Time" information and add it to a pandas dataframe, then "play with it".
Since I can't scrape it, I can't add it to a dataframe.
I've tried, and failed using basic "inspect, and copy xpath" methods in chrome.
Here's the code:
link = "https://dotscan.com/account/13UVJyLnbVp9RBZYFwFGyDvVd1y27Tt8tkntv6Q7JVPhFsTB?tab=transfers"
driver.get(link)
download_btn = driver.find_element(By.XPATH, "//*[@id='rc-tabs-3-panel-1']/div/div[1]/div/table/tbody/tr[1]/td[6]/div/a")
download_btn.click()

This is the error message I get:

Message: no such element: Unable to locate element

A: You don't need Selenium for this, regular requests would be enough. If you open your browser and check the Network tab inside dev tools, you can see that it is getting data from API, in your case the endpoint is https://polkadot.webapi.subscan.io/api/v2/scan/transfers and parameters are row=10, page=0, and address=12xtAYsRUrmbniiWQqJtECiBQrMn8AypQcXhnQAc6RB6XkLW.
If you combine it all together and provide the User-Agent as it seems to be required for the API to respond, you can come up with this instead:
import requests

header = {"User-Agent": "Mozilla/5.0"}
params = {
    "row": 10,
    "page": 0,
    "address": "12xtAYsRUrmbniiWQqJtECiBQrMn8AypQcXhnQAc6RB6XkLW"
}

result = requests.get(
    "https://polkadot.webapi.subscan.io/api/v2/scan/transfers",
    params=params,
    headers=header
)

print(result.json())


text:
Q: passing javascript variable from visual force component to apex controller how to pass jquery variable from visual force component to apex controller?
The requirement is ,need to validate by checking the storage available in salesforce while uploading files ,
if the files are exceeded the limit need to show feedback message
here the script is in visualforce component
we used dropzone for file uploading

A: If your controller is using a @RemoteAction method, you can directly pass whatever params you want when calling that method.
If not, you can declare an apex:actionFunction with nested apex:param tag, which will become aliased as a JS function that you can simply call from your jQuery code. example:
<apex:actionFunction name="myValidator" action="{!yourControllerValidatorMethod}" rerender="">
    <apex:param name="param1" value="" assignTo="{!someControllerProperty}" />
</apex:actionFunction>

then in your javascript, you can easily call it like this:  myValidator(yourJqueryVariable);


text:
Q: Finding column combination that forms distinct entry in Oracle I have a very bizarre situation where I have a tons of tables in a database and I need to find which column combination make entries distinct.
There is no documentation, and for reasons, we can't use the "official" primary key which is an SID.
The "non-official" primary key can be a combination of 1 to 300 columns.
Do you guys have any idea on how I can output the right column list for each table in the database?
I feel like doing select distinct for each columns combination is a bit overkill, since some table have 300 columns!
Any tips or insight would be appreciated!
Thank you.


text:
Q: Can't connect to server with SSH, Showing " ssh: connect to host 178.128.60.26 port 22: Connection timed out" in Windows 10 When I am trying to connect to a server via ssh it is throwing an error "ssh: connect to host 178.128.60.26 port 22: Connection timed out". My operating system is windows 10. And I am using Git bash for connecting via ssh. Checked the blocked ports in the firewall. Port number 22 is open for all networks. I already connected to the server via ssh but now I can't.

A: Check first if you can ping the server.
But if you do:

*

*either the server itself is not running the ssh daemon service (but then the error woudl more likely be "connection refused")

*or it is, but on a non-conventional port (your ssh call would need to be ssh -p <another_port> ...) (again, the error would more likely be "connection refused")

*or its firewall rules prevents any incoming ssh request: that would actually generate a time out.
If the remote machine is a Linux one: sudo service ufw status (assuming you have access to said server, or you can ask an administrator to check)


text:
Q: How can I write a Haskell function to query a database? So I'm trying to write a database layer in Haskell, to interface with a SQLite DB. I'm following instructions from the book Real World Haskell, in the chapter about databases. This is what I have so far:
{-# LANGUAGE FlexibleContexts #-}

import Database.HDBC
import Database.HDBC.Sqlite3

db = "dev.db"
conn = connectSqlite3 db

getPerson person =
  quickQuery' conn "select name from person where name like ?" [toSql person]

main :: IO ()
main = do
  print $ getPerson "Michael"

But I get the error:
Could not deduce (IConnection (IO Connection))
     arising from a use of 'quickQuery''
   from the context: convertible-1.1.1.0:Data.Convertible.Base.Convertible
                       a SqlValue
     bound by the inferred type of
              getPerson :: convertible-1.1.1.0:Data.Convertible.Base.Convertible
                             a SqlValue =>
                           a -> IO [[SqlValue]]

Which as a Haskell beginner I don't really understand. I can put a type annotation on getPerson, but that doesn't really seem to fix it.

A: This code compiled
{-# LANGUAGE FlexibleContexts #-}

import Database.HDBC
import Database.HDBC.Sqlite3
import Data.Convertible.Base

db :: String
db = "dev.db"

getPerson :: (Convertible a SqlValue, IConnection conn) => conn -> a -> IO [[SqlValue]]
getPerson conn person =
  quickQuery' conn "select name from person where name like ?" [toSql person]

main :: IO ()
main = do
    conn <- connectSqlite3 db
    person <- getPerson conn "Michael"
    print person

connectSqlite3 :: FilePath -> IO Connection so value of conn should be extract in IO monad.
Maybe there is better way to write this using bind to pass connection to quickQuery but I don't know, I have never use this library, just guessing from the type in ghci