text:
Q: Get Cookies of HTTP Request of ODATA Service im facing the problem to send a put http request to an odata service. It works in Postmen with following steps:

*

*Send a Get-Request with header: x-csrf-token : fetch and safe the token

*Send a Put-Request with header: x-csrf-token : token of Get-Request
I noticed, that postmen got the same SessionID Cookie in the Get and the Put Request.
Now I want to build a fiori App, where I want to call the Odata Service.

*

*I send a HTTP Get-Request with the fetchAPI whit header x-csrf-token : fetch and safe the token

*Send a Put-Request with header: x-csrf-token : token of Get-Request.
Now I get a 403 Forbidden Error.
I checked the network tab in the dev tools of chrome and i compared the cookies of both requests. Theire sessionIDs was not equal so i thought I just need to read the cookies of the Get Request and set a Cookie Header in the Put Request to guarantee that both Requests got the same SessionID.
However this does not seem to be possible. If I read the response Header of my Get Request, i does not get the set-cookie header, although it is shown in the network tab. If i call document.cookies i just get an empty string.
So my first Problem is, that I cant read the cookies of my get request. Due to my internet research, it seems like it doesnt work becauce of cross-side problems. But im not sure about this and I do not know how I can solve this error.
In addition to that, im not able to change the cookie header in my Put request. If I set a header:
Cookie: SAPSESSIONID_ : SessionID (e.g my Postman SessionID), this headerline is not shown in my Network Tab and the Session ID of my Put Request is not the ID i wanted to be setted.
I set some headers for the response, like i read in other questions:
'Access-Control-Allow-Headers' - 'Accept,Accept-Language,X-PINGOTHER,Content-Language,Content-Type,Authorization,Cookie,X-Requested-With,Origin,Host'
'Access-Control-Allow-Credentials' - 'true'
'Access-Control-Allow-Methods' - 'GET, PUT'
'Access-Control-Allow-Origin' - ''
In my request i already set credentials: 'include' so i think it should work. But I'm still not able to read or set any Cookies...
Code:
GET Request:
        const xcsrftokenHeader = new Headers();

        xcsrftokenHeader.append('x-csrf-token', 'fetch');
        xcsrftokenHeader.append('Authorization', 'Basic '+  btoa(username + ":" + password));

        const xcsrftokenRequest = new Request('<myURL>', {
            method: 'GET',
            credentials: 'include',
            //crossDomain: true

        });

        fetch(xcsrftokenRequest)
            .then(response => {

                for (var pair of response.headers.entries()){
                    console.log(pair[0] + " : " + pair[1]);
                    //I would like to see the set-cookie Cookie here
                    if(pair[0] == "x-csrf-token"){
                        xcsrftoken =pair[1];
                    }
                }

            })
            .catch(error => {console.error('Error', error);});

GET (Server)
method RFCCHANGEAFOSET_GET_ENTITYSET.
DATA: ls_header1 TYPE ihttpnvp.
  ls_header1-NAME = 'Access-Control-Allow-Headers'.
  ls_header1-VALUE = 'Accept,Accept-Language,X-PINGOTHER,Content-Language,Content-Type,Authorization,Cookie,X-Requested-With,Origin,Host'.
  set_header( is_header = ls_header1 ).

  DATA: ls_header2 TYPE ihttpnvp.
  ls_header2-NAME = 'Access-Control-Allow-Credentials'.
  ls_header2-VALUE = 'true'.
  set_header( is_header = ls_header2 ).

  DATA: ls_header3 TYPE ihttpnvp.
  ls_header3-NAME = 'Access-Control-Allow-Methods'.
  ls_header3-VALUE = 'GET, PUT'.
  set_header( is_header = ls_header3 ).

  DATA: ls_header4 TYPE ihttpnvp.
  ls_header4-NAME = 'Access-Control-Allow-Origin'.
  ls_header4-VALUE = '<ServerDomain>'.
  set_header( is_header = ls_header4 ).


text:
Q: Woocommerce web site 6-7 second pageloads I have a wordpress based ecommerce website with Woocommerce.
I use WP-Rocket Plugin for cache
I use CND
I use a Cloud dedicated server : 9CPU X 2GHZ 7GB Ram Apache
For cached page pageloads are very good it takes only 1-1.5 second. But uncached page it takes 6-7 seconds and this is a dynamic ecommerce website most pageloads are uncached. In website search and infinite scroll feature which came with my theme are same it takes 5-7 seconds. I try to change my hosting provider and try Kinsta which is a premium wordpress hosting but nothing has changed. What should i do for reducing this pageloads. When i click for a new category grey waiting icon in chrome takes 3-4 seconds and when it turn to blue it only takes 1-2 . I think main problem is this. I will add same screenshots cloud you please check it
This is for unchached page.
This is for infinite scroll
This is for in site search

A: There is very little detailed instructions I can give you based on the fact that this is a debugging project. However, I can provide you with some tools and advice.
The first thing you wan to do is eliminate that it is your hosting. A decent minimal hosting environment should be able to run WordPress and WooCommerce on the Storefront theme (https://wordpress.org/themes/storefront/) with times around 400-600ms with no caching. Better hosting can produce better times. So install that theme and disable ALL plugins except WooCommerce and check your TTFB times. If they are still high, then it is a hosting issue. It may or may not be resource allocation that can be fixed by adjusting the hosting environment. However, that's a different question.
Assuming that the TTFB times reach the target range of 400-600ms in that configuration, you can proceed to determine the cause of your slowdown.
First, enable all of the plugins you are using again except the caching plugin. Check your speed. It should go up some, but not too much. If you are back at the >5000ms then you can bet your issues are with one (or more) of the plugins. Turn them all off and then turn them on one at a time checking the speed after each activation. It is also possible that there is a conflict between plugins. If you find that plugins are your problem, then you should seek out new ones to replace that functionality or do custom development.
Next enable your desired theme. You should do this with all the plugins enabled in case there are dependencies. If this is the cause of your slowdown then you have a couple of options. One is to install some debugging plugins and try to determine if you can fix those issues in a child theme or to work with the theme developer to integrate changes. The second is to find another theme that will meet your needs. And lastly, you can build one yourself or do a child theme of Storefront.
Some good debugging plugins that can show where issues exist are:
Debug Bar - https://wordpress.org/plugins/debug-bar/ (there are additional plugins that add features to the main plugin as well)
Query Monitor - https://wordpress.org/plugins/query-monitor/ (best for database related issues)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why so slow this select query in mysql? Table Schema
database engine is MyISAM
commits (about 500,000,000 rows)
id (int) - PK (indexed)
project_id (int) - FK [project->id] (indexed)
committer_id - FK [user->id] (indexed)
...
projects (about 32,000,000 rows)
 id (int) - PK (indexed)
...
user (about 12,000,000 rows)
 id - PK (indexed)
...

Explain
SELECT COUNT(*)
FROM commits
WHERE committer_id = 30351173

above query is complete in 10 sec.
SELECT project_id , COUNT(*) as commit_count
FROM commits
WHERE committer_id = 30351173
GROUP BY project_id

but, above query is not complete in 2 hours(7,200 sec)
project_id in commits is complete indexing column, but the speed is too slow.
Why is this happening?
Q) How do I speed up the second query?

Additional
SELECT project_id , COUNT(*) AS commit_count
FROM commits
WHERE committer_id = 1891264
GROUP BY project_id

I query another commiter_id is complete 15 sec.
Additional - 2
EXPLAIN SELECT COUNT(*) FROM commits WHERE committer_id = 30351173

output

EXPLAIN SELECT project_id , COUNT(*) AS commit_count
FROM commits
WHERE committer_id = 30351173
GROUP BY project_id

output

A: You should try a covering index like
CREATE INDEX commits_proj_comm_cndx ON commits(committer_id, project_id);

Why
Your query:

*

*selects project_id out of the table

*chooses using committer_id

*groups using project_id
By creating an index where your constant WHERE clauses (here, committer_id) are in the first positions, you allow MySQL to quickly zero on those records which will be involved, before accessing the table. Once it has these records, MySQL can start work. But if in the index there is also the information used for grouping, i.e., project_id, MySQL can start grouping data even before accessing the table. Finally, if all the other information is also present on the index (here this is already done, for it is the same information used by the WHERE), MySQL has no need to access the table at all. An index supplying this information in this order is a covering index for this query.
Of course this is the more advantageous, the more the data you use is small in respect to the full table row; clearly, if you have a 100 GB table and a 75 GB index, the performance gain is small. If you have a 100 GB table and a 1 GB index, you're in for a big win. Especially if the query on the 1 GB index has a low cardinality (e.g. the committer is only responsible for 1% of the data). Then you're reading 10 MB of data instead of 100 GB, and you won't believe the performance increase.
Once you have the index, you do:
SELECT project_id , COUNT(1) AS commit_count
    FROM commits
    WHERE committer_id = 1891264
GROUP BY project_id

This ought to run on the index only.
I said, try, because maintaining indexes has a cost too. It might well be the case that you speed up this SELECT query, at the expense of slowing down INSERTs and UPDATEs, because they need to manage the index as well as the table.
By the way, the COUNT(1) is a personal taste - many regard asterisks in queries as an antipattern, and by using COUNT(1), the query will not show in a grep search, allowing to focus on queries with significant asterisks.

Also, when you do tests like this, remember to do1:

*

*test on slow_id

*test on different_id

*test again on slow_id with a slightly different query (e.g. adding an AS.. alias)

The reason for the third test is that when running the first query MySQL will also load the data in the pool (if using InnoDB, which you don't) and in RAM as well, so that the second query might be faster because pool, memory and any I/O cache have been primed. If so, the third query will also run faster and - provided it is then comparable to the second query of course - the "this query is slow" problem will be revealed as an artifact.
But since queries are cached, you want the same data to be fetched again, not the result being pulled from the cache. So the third query will need to be slightly different to throw the cache off. Otherwise you'd see what seems to be a very fast query, when it actually is anything but.
(1) this is if you run a quick test. Otherwise performance testing is way more complicated than this; the Percona blog has several articles on this topic.

A: This is because with
group by
statement
SQL-Server have to go through every sigle row in your Table.
Possibly a index on project_id will solve the problem.
alter table commits add index (committer_id);


text:
Q: Ubuntu 13.04 to 13.10 upgrade failure I'm trying to upgrade ubuntu my ubuntu 13.04 to 13.10, but there is always this error:
Error during update
A problem occurred during the update. This is usually some sort of
network problem, please check your network connection and retry.
W:Failed to fetch
http://archive.canonical.com/dists/[distro]/partner/source/Sources
404 Not Found [IP: 91.189.92.150 80]
, E:Some index files failed to download. They have been ignored, or
old ones used instead.

It's not the internet connection
 problem. My internet works fine.... i have good connection.
Can someone help me with this problem?
Thanx

A: you have to try with changing to some other server , in deed from best server option.
Open software sources application from dash, from there you can change your software server.


text:
Q: Necessity of Defining Enthalpy One derivation of enthalpy by Kittel and Kroemer uses: $dW' = dW + d(PV) = dU + d(PV) - dQ = dH - dQ$. My understanding is, however, that $dW$ already includes $d(PV)$, so I find it redundant to add $d(PV)$ to the work. If $d(PV)$ and $dW$ are separate, then what kind of work does $dW$ denote (most work done by gases in thermodynamics is expansion and compression from my experience)? Thank you for your help.

A: The main point of defining different thermodynamic potentials is to be able to choose which of the parameters are independent variables and which are response variables. Switching between different pairs of conjugated parameters - $(P,V)$, $(T,S)$, and $(\mu, N)$ - is achieved by using the Legendre transformation. It is the very same Legendre transformation that is used to convert from Lagrangian to Hamiltonian description in the classical mechanics, except that in thermodynamics it is defined with a different sign.
Specifically, enthalpy is particularly useful, e.g., for describing thermodynamics of macromolecules molecules in chemistry, where controlling pressure is more natural than assuming constant volume.

A: Enthalpy is just a very convenient parameter to work with when analyzing many kinds of thermodynamics problems, rather than always writing U+PV.  When you have more experience, you will see how often it comes into play.  For example, for constant pressure expansion of compression of a gas, it is equal to the amount of heat you have to add or remove, respectively.  But this is just the tip of the iceberg.


text:
Q: Active strings in Texmaker There is a facility in WinEdit that: to type $ $ or ( ) or { } or [ ] we need to hit corresponding key only once. For example, if we type Shift+9 we get ( ) directly. This is possible in WinEdit by making some settings in active string. My question is does such facility is available in Texmaker?

A: In TeXmaker you can add the $...$ using Ctrl + Shift + M for an equation in the middle of the text, or  Ctrl + Shift + N for an numbered displayed equation (inserts the equation environment.
You can check this and all the default shortcuts in Options>Configure TeXmaker and in the window the fourth window: Shortcuts is where you can edit them. But if you don't want to change them but add new such as the shortcuts you explained, then I think the best choice to create your own shortcuts is got to User>User Commands and there configure until 5 commands with the combination keys the program gives you.
Perhaps isn't the most comfortable for you or the answer you was waiting, but is the best I know. I hope you find it useful


text:
Q: Как исправить баг в гуглхроме при использовании border-radius? подскажите пожалуйста как исправить баг в хроме.

body{
  background:#1a2b3a;
}
.menu-wrap{
 width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 150px;
}

.menu{
 display: flex;
 margin: 0px;
 padding: 0px;
}

.menu li{
 padding: 30px;
 list-style: none;
 background: #eee;
 border-right: 1px solid #187faf;
 transition: 0.3s;
 position: relative;
 overflow: hidden;
 z-index: 1;
}

.menu li::before{
 position: absolute;
 content: "";
 width: 100%;
 height: 100%;
 background: #1292ce;
 left: 0;
 top: 0;
 display: block;
 z-index: -1;
 /*transition: 0.3s;*/
}

.menu li:hover:before{
 left: -100%;
 z-index: 1;
 transition: 0.5s;
}

.menu li::after{
 position: absolute;
 content: "";
 width: 100%;
 height: 100%;
 background: #1292ce;
 right: 0;
 top: 0;
 display: block;
 z-index: -1;
 /*transition: 0.3s;*/
}

.menu li:hover:after{
 right: -100%;
 z-index: 1;
 transition: 0.5s;
}

.menu li:first-child{
 border-radius: 30px 0 0 0;
}

.menu li:last-child{
 border-radius: 0px 30px 0 0;
 border-right: none;
}

.menu li:hover a{
 color: #1292ce;
 font-size: 16px;
}

.menu li a{
 text-decoration: none;
 color: #fff;
 text-transform: uppercase;
 font-size: 16px;
 font-weight: 600;
 transition: 0.5s;
}

главная страница

О нас

Юридические новости

Полезные сервисы

контакты

При наведение на кнопку "главная страница" несколько раз, в правом и нижнем углу данной кнопки появляется белые точки. во всех остальных браузерах работает нормально. если отключить border-radius то проблемы нет. Подскажите как исправить данную проблему.? может проблема в коде? кто силен в верстке пожалуйста помогите с решением проблемки)

A: протестировал на разных браузерах все одинаково, точек никаких нет!
возможно у вас появляется из-за кроссбраузерности
добавьте к transition
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
 transition: all 0.5s ease;


text:
Q: linear algebra applied in discrete Markov Process We give an abstract description of the discrete Markov process as follows: Consider a system $A$ with $n$-possible states: $S_{1},\ S_{2},\cdots, S_{n}$. In each step of this process, the system randomly alters from one state to another. We use the notation $A(k)= S_{l}$ to denote the event $A$ is in state $S_{l}$ in step $k$.'' Suppose the change of $A$ satisfies the following rule:
     Assume $A(k)= S_{i}$. Then
     $$
 \text{Probability}(A(k+1)= S_{j})=t_{i,j}
 $$
     This number $t_{i,j}$ does not depend on $k$.  We define the transition matrix $T\in M(n,n)$ by setting its $(i,j)$th entry to be $t_{i,j}$. In other words, $T_{i,j}=t_{i,j}$.
Now suppose we know that $A(0)=S_{1}$. We consider the \textbf{row vector}
$$
\vec{v}_{k}=[\text{Probability}(A(k)= S_{1}),\ \text{Probability}(A(k)= S_{2}),\cdots,\  \text{Probability}(A(k)= S_{n})].
$$
Show that for any positive integer $k$, we have
$$\vec{v}_{k}=[1,0,\cdots, 0]\cdot T^{k}.$$


text:
Q: Convertir texto, en lista, sublistas y estas en diccionario Estoy tratando de crear un archivo con un texto y convertirlo en una lista. Posteriormente dividir la lista en sub-listas.
Por último, convertir estas en un diccionario, pero me falta asignarle las keys al diccionario ¿qué me falta?
texto = """1;Carlos;Pérez;05/01/1989
2;Manuel;Heredia;26/12/1973
3;Rosa;Campos;12/06/1961
4;David;García;25/07/2006"""

Creamos el nuevo documento y lo escribimos con el texto anterior
fichero = open ("personas.txt", "w", encoding = "utf8")
fichero.write (texto)
fichero.close()

fichero = open ("personas.txt", "r")
texto = fichero.readlines()

fichero.close()

print(type(texto))
print(texto)
print("\n")

for i,personas in enumerate (texto):
    print (i,personas)

print("\n")

Dividimos la lista en sub-listas
id = []
nombre = []
apellido = []
bday = []
for i in texto:
    i, n, a, b = i.split(";")
    id.append (i)
    nombre.append (n)
    apellido.append (a)
    bday.append (b)

print (id)
print (nombre)
print (apellido)
print (bday)
print("\n")

Unimos listas para convertirlo en un diccionario
personas = {}

personas=[list(x) for x in zip(nombre,apellido,bday)]
dict(zip(id,personas))

print("\n")

for i in personas:
    for k,v in i.items():
        print (k,v)

Muchas gracias Candid Moe, ahora me encuentro con el siguiente TypeError y me vuelvo a atrancar.
Una vez corregido el código como me indicaste, necesito iterar el diccionario con un formato, pero al poner el for me da distintos tipos de error.
Unimos listas para convertirlo en un diccionario
personas = {}
personas = {id[i]: (nombre[i], apellido[i], bday[i]) for i in
range(len(apellido))}

Iteramos y mostramos con formato predefinido:
for id in personas.items():
print ("(id={}) {} \t{} \t{}".format(id[i], nombre[i], apellido[i], bday[i]))

Muchas gracias de nuevo

A: Para crear un diccionario con comprensión se usa:
diccionario = {k: v for some_expression}

La clave es usar "{}" y separar la llave y el valor con un ":". Llave y valor son expresiones.
En este caso sería:
nombre = ["juan", "raul"]
apellido = ["pere<", "soto"]
bday = ["1/1/2000", "2/2/2000"]
id = ["01", "02"]

diccionario = {id[i]: (nombre[i], apellido[i], bday[i]) for i in range(len(nombre))}

print(diccionario)

El valor es una 3-tupla (nombre,apellido,bday). Puedes usar una lista también o cualquier otro objeto de tu conveniencia.
La llave es el id. Dado que todas las listas tienen que ser del mismo largo, usamos el largo de una para controlar la iteración.
El resultado es:
{'01': ('juan', 'pere<', '1/1/2000'), '02': ('raul', 'soto', '2/2/2000')}

Process finished with exit code 0


text:
Q: combine procedure and cursor in sql newbie here.
I am trying to do self-learning about SQL.
Right now, I am having a problem in combining procedure and cursor.
Hereby the case
The Case

Create procedure named 'sp4' that receive StaffName from user's input
  to display StaffName and StaffPosition for every staff which name
  contains the word that has been inputted by user.
  (create procedure, declare cursor, like)

Hereby the code that I have tried it
My Code
CREATE PROCEDURE sp4 (@name VARCHAR(100))
AS
DECLARE cur2 CURSOR
SCROLL
FOR
    SELECT StaffName, StaffPosition
    FROM MsStaff
    OPEN cur2
    DECLARE @pointer AS VARCHAR(100)
    FETCH NEXT FROM cur2 INTO @pointer
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT StaffName, StaffPosition
        FROM MsStaff
        WHERE @pointer = @name
        AND StaffName LIKE '%' + @pointer + '%'

        FETCH NEXT FROM cur2 INTO @name
    END
    CLOSE cur2
    DEALLOCATE cur2

A: Your SELECT statement for the cursor indicates SELECT StaffName, StaffPosition but your FETCH statements don't match that (or each other).
The FETCH is going to load the data from the cursor into your memory variables.  So you need to supply one variable for each column indicated in the SELECT. For example, if you have
DECLARE @staffName VARCHAR(100)
DECLARE @staffPosition VARCHAR(100)

then you can replace both of your fetches with:
FETCH NEXT FROM cur2 INTO @staffName, @staffPosition


text:
Q: Different content on left and right pages I would like to create a document/book/memoir (haven't chosen a class yet) that has completely different content on all the left-hand side pages and different content on all the right-hand side pages.
Ultimately, what I am trying to achieve is to have the actual text on the left-hand side pages and then commentary about the text on the right-hand side pages.
I can also see a similar use if creating a book with dual languages with each language on their own side of the book.
How can I go about setting this up?
PS. I wasn't sure of a proper tag to use for my question.

A: The example below  uses a custom macro, that I called \xxxx in a display of imagination (I left as exercise find a better name), using afterpage.
Usage:
\xxxx{text in left page}{comment in right page}

The comments are conditionally colored to check easily when the comment are shorter that the original text and thus they should not stretch the commented text (always a good idea).
Note that when there are not enough space for the text and/or the comment you should add \newpage twice.
Example:

\documentclass{article}
\usepackage{geometry}
\usepackage{lipsum,xcolor}
\usepackage{afterpage}
\parindent0pt\parskip 2em
\newsavebox\mytext
\newsavebox\mycomment
\newcommand\xxxx[2]{
\savebox\mytext{\parbox[t]{\linewidth}{#1}}
\savebox\mycomment{\parbox[t]{\linewidth}{#2}}
\ifdim\dp\mytext>\dp\mycomment
\noindent\begin{minipage}[t][\dp\mytext][t]{\linewidth}#1\end{minipage}
\afterpage{% shorter comment in blue
\savebox\mytext{\parbox[t]{\linewidth}{#1}}
\noindent\begin{minipage}[t][\dp\mytext][t]{\linewidth}
\color{blue!50!black}#2\end{minipage}}
\else
\noindent\begin{minipage}[t][\dp\mycomment][t]{\linewidth}#1\end{minipage}
\afterpage{% longer comment in red
\savebox\mycomment{\parbox[t]{\linewidth}{#2}}
\noindent\begin{minipage}[t][\dp\mycomment][t]{\linewidth}
\color{red!50!black}#2\end{minipage}}
\fi}

\begin{document}
~\newpage % first odd page
\xxxx{\lipsum[1][1-10]}{Brief comments  in blue}
\xxxx{\lipsum[2][1-4]}{Boring comments in red. \lipsum[3]}
\xxxx{\lipsum[4][1-6]}{Another boring comment \lipsum[5][1-12]}
\xxxx{\lipsum[6]}{There are a hidden cat here.}

\newpage % Blank page for comments
\newpage

\xxxx{\lipsum[7]}{\lipsum[8]}
\xxxx{\lipsum[9]}{\lipsum[10]}
\xxxx{\lipsum[11]}{\lipsum[12]}
\xxxx{\lipsum[13]}{\lipsum[14]}
\xxxx{\lipsum[15]}{\lipsum[16]}

\newpage % Blank page for comments
\newpage

\xxxx{\lipsum[17]}{\lipsum[18]}
\xxxx{\lipsum[19]}{xxxx\lipsum[20]}
\xxxx{\lipsum[21]}{xxxx\lipsum[22]}
\xxxx{\lipsum[23]}{xxxx\lipsum[24]}
\xxxx{\lipsum[25]}{xxxx\lipsum[26]}

\end{document}

But without reinvent the wheel, as commented  John Kormylo, paracol is another (better) option:
\documentclass{article}
\usepackage{geometry,parskip}
\usepackage{lipsum}
\usepackage{paracol}
\begin{document}
~ \newpage
\begin{paracol}[1]{2}
\begin{leftcolumn} \lipsum[1][1-2] \end{leftcolumn}
\begin{rightcolumn} \lipsum[2] \end{rightcolumn}
\end{paracol}
\begin{paracol}[1]{2}
\begin{leftcolumn} \lipsum[3] \end{leftcolumn}
\begin{rightcolumn} \lipsum[4] \end{rightcolumn}
\end{paracol}
\begin{paracol}[1]{2}
\begin{leftcolumn} \lipsum[5] \end{leftcolumn}
\begin{rightcolumn} \lipsum[6] \end{rightcolumn}
\end{paracol}
\end{document}


text:
Q: React binding through constructor - possible to automate? As per recommendations from others, I have been binding class methods in the constructor in React, for example:
constructor(props) {
  super(props);
  this.handleChange = this.handleChange.bind(this);
}

I have components with many methods, and I am binding all of these methods to this.  Argh, what a pain!  To avoid repetitively maintaining this pattern, I built a function that would be called in the constructor in place of all the individual calls; it binds all the methods specific to that class, while a parent class would take care of its own methods moving up the classes.  For example:
function bindClassMethodsToThis(classPrototype, obj) {
    Object.getOwnPropertyNames(classPrototype).forEach(prop => {
        if (obj[prop] instanceof Function && prop !== 'constructor') {
            obj[prop] = obj[prop].bind(obj);
            console.log(`${classPrototype.constructor.name} class binding ${prop} to object`);
        }
    });
}

class A {
    constructor() {
        bindClassMethodsToThis(A.prototype, this);
    }

    cat() {
        console.log('cat method');
    }
}

class B extends A {
    constructor() {
        super();
        bindClassMethodsToThis(B.prototype, this);
    }

    dog() {
        console.log('dog method');
    }
}

let b = new B();

So, React and ES6 gurus, is this a reasonable approach, or I am doing something wrong here?  Should I stick to the individual bindings to this?

A: Your strategy seems sound, though there are some edge cases that you may end up wanting to tackle. A library like react-autobind, which Alexander mentioned, takes care of some of these things for you, and if I were to use this strategy I would probably use a library like this one (or take a look into the source code to get an idea for what it does).
For completeness, some alternative approaches are:

*

*Use class properties and arrow functions (along with any necessary Babel transforms) to create pre-bound methods:
class MyComponent extends React.Component {
  handleChange = () => { /* ... */ }
}

*Use a decorator, like the autobind decorator from core-decorators, along with any necessary Babel transforms (this was the strategy I used previously):
import { autobind } from 'core-decorators'

class MyComponent extends React.Component {
  @autobind
  handleChange() { /* ... */ }
}

*Explore the use of Hooks (currently in alpha) to avoid the problem of binding all together (since state values and setters exists as local variables to be closed over). This is the strategy I've been preferring very recently, but please note it is still in the proposal state and may change. :)

A: Assuming you have Babel setup for it, you can also use arrow functions instead, avoiding the need to bind this:
class Foo extends React.Component {
  handleClick = (event) => {
    event.preventDefault()
  }

  render() {
    return
Click me

  }
}

A: One way to resolve this is to call bind in render:
onChange={this.handleChange.bind(this)}


text:
Q: Passing the string value from view to controller sending only null I want to send some data to controller but i always getting null value in parameter of controller . I look for solution but not reached to solution . Please provide some suggestion or help .
ajax call
 var submittedName = 1;
 $.ajax(
  {
      url: '/api/monitor/Detailsfetch',
      type: "post",
      data: { 'submittedName': submittedName},
      success: function (data) {
          alert("passed");
      },
      error: function (xhr, ajaxOptions, thrownError) {
               alert(thrownError);}
  });

Controller part
  [System.Web.Http.HttpPost]
  public ContentResult Detailsfetch(string submittedName)
    {sone code here}`

A: from the comments and what little information you have provided I'd guess that you route is not set up correctly. If you want to test this (assuming you have not changed the default rule). Try to rename the parameter to id (in both controller and JS). If that works then it's because your route is not configured
see this for help in that case
basically you should have something like this in your application_start
RouteTable.Routes.Add(new Route {
    Url = "[controller]/[action]/[submittedName]",
    RouteHandler = typeof(MvcRouteHandler)
})

A: In this scenario not able to send parameter value using data: { 'submittedName': submittedName} So an alternative coud be loke to pass parameter data in URL itself
/api/monitor/Detailsfetch/?submittedName="+somename+"",

Hope this could help some body !!


text:
Q: How to upgrade node to specific version in macOS Mojave, and update the active path for node? I want to upgrade node to 12.10.0 and npm to 6.11.3, currently I am working on macOS Mojave version 10.14.5
I am using these commands to upgrade the node version to 12.10.0::

*

*sudo npm cache clean -f (force) clear you npm cache

*sudo npm install -g n install n (this might take a while)

*sudo n 12.10.0 upgrade to the specific version

After running the last command it gives me an output like::
installing : node-v12.10.0
       mkdir : /usr/local/n/versions/node/12.10.0
       fetch : https://nodejs.org/dist/v12.10.0/node-v12.10.0-darwin-x64.tar.gz
   installed : v12.10.0 to /usr/local/bin/node
      active : v10.16.3 at /usr/local/opt/node@10/bin/node

When I am checking for node version node -v it still shows me old version 10.16.3
I have tried to add node path, but still, it gives me the same output.
I have used command sudo nano /etc/path and then added /usr/local/bin/node path to it.
Please suggest me how can I upgrade node to 12.10.0 and npm to 6.11.3 version?

A: Step 1: Clean npm cache
sudo npm cache clean -f

Step 2: Install node helper (n) globally using the following command.
sudo npm install -g n

Once node helper is installed. You can either get a specific version like I needed 16.14.1 then you can perform.
sudo n 16.14.1

OR You can get the latest stable version using
sudo n stable

Then you can confirm the version installed
node --version

A: install n (npm module) npm install -g n and run sudo n latest or sudo n <version>

A: Install nvm following below tutorial :
Install nvm with homebrew
As stated in the link above,
Start by :
brew update
brew install nvm
mkdir ~/.nvm
nano ~/.bash_profile

In your .bash_profile file (you may be using an other file, according to your shell), add the following :
export NVM_DIR=~/.nvm
source $(brew --prefix nvm)/nvm.sh

Back to your shell, activate nvm and check it (if you have other shells opened and you want to keep them, do the same) :
source ~/.bash_profile
echo $NVM_DIR

Then with the help nvm install any node version(example v12.14.1) you want :
nvm install v12.14.1
nvm use v12.14.1

to switch to 12.14.1 version.

A: An alternate way to upgrade w/o using brew -
Go to nodejs releases page. The table on this page list the various node release available for download.
Click on the downloads link for the version you need. This will take us to another page to download the node version depending on the OS you are using. For mac, we can download the .pkg format.
After the package is downloaded, we can run it by clicking the downloaded file and hitting 'Next' till we complete.


text:
Q: How to handle a callback url in React I am building a full-stack application, where users upload videos and the server does some manipulation and eventually informs the user if the conversion is complete.
On the front-end, I have React and close the connection, when the upload is finished. In the meantime my server does the conversion and I would like to find a way to inform my front-end that the conversion has finished. How could I do this? Maybe through using some callback url? Thank you


text:
Q: Paytm JS Checkout Module I wanted to integrate with th JS Checkout Module which Paytm has provided.I have done all the things like creating business account.I also have the access keys for both environments.
Js checkout getting started guide says that we can customize the look and feel of the page but my issue is that In my dashboard under Developer Settings the JS Checkout Option is  Disabled.How can I get it enabled?
Can anyone please help me understand this. And guide me on how can I get started with this.
Thanks

A: Is your test data ON? I cannot work on JS checkout with test data on/off mode.


text:
Q: PHP cURL - POST is being sent to an empty page? I'm trying to automate the usage of this site, where users can use temporary E-Mail addresses which can also be specified by them manually. It uses a very simple anti-spam protection by having this <input name="csrf" type="hidden"> input inside the form with a randomized set of characters, which then needs to be included in the POST request. So, if the CSRF is bj152nvua2ob, and I want my new address to be "john@l0real.net", my POST needs to be:
csrf=bj152nvua2ob&mail=john&domain=@l0real.net

Problem is, I can't do this with cURL and PHP. Here's the top of my code:
$ch = curl_init ();

curl_setopt ($ch, CURLOPT_URL, "temp-mail.org/en/option/change/");
// Without CURLOPT_FOLLOWLOCATION, the page is not going to load.
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");

$html = curl_exec ($ch);

Then, after I've got the response, I start generating a new mail address and start getting the CSRF, therefore I've written two simple functions called "generate_mail" and "get_csrf". I've tested both of them, and they seem to work without any issues.
$csrf = get_csrf ($html);
$mail = generate_mail ();
$post = "csrf=$csrf&mail=$mail&domain=@l0real.net";
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);

file_put_contents ("final_response.html", curl_exec ($ch));

curl_close ($ch);

After creating the file final_response.html on my PC and then viewing it, I've noticed that the results aren't what I've expected. Some tries later, I've decided to debug my connection using Fiddler, and then I've noticed something interesting. This is what I get when I use this site with my browser:

and this with cURL:
.
Notice how there is 1 element (excluding the tunnels) against... 4! First element is an empty response, but the second one contains the HTML page. Last two are the same: third is an empty response (and that's where my POST was sent), and forth contains the HTML page with different CSRF and incorrect mail address (the one that was generated by the site itself, not by me). From what I can tell, each time I use curl_exec, it first loads an empty page, but then loads the correct one. All of my requests are being sent to the empty one, thus being ignored later on. Is this a security measure, or I didn't configure cURL correctly? I've tried to provide as much information as I could, showcasing each, and every step of mine, hoping that this problem can be fixed.

A: Solved by adding these lines of code:
curl_setopt ($ch, CURLOPT_POSTREDIR, 3);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $path_to_cookies);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $path_to_cookies);

Now, it works the way intended!


text:
Q: Different colour bars for different bars in a flot bar graph I want to keep different colors for all bars in a flot bargraph. is it possible to do this? I found a way to do this , if i pass the color in a variable for every bars, now with the data i am passing the colours as well inside Variable d1_1,d1_2,d1_3,d1_4,d1_5,d1_6,d1_7 and passing in a variable data1.
I am writing the below-mentioned code, but it is not working, kindly suggest me how to do this.
My code is as mentioned below.
// Colors
var color01 = '#0000FF'; //blue
var color02 = '#FF0000'; //red
var color03 = '#32CD32'; //lime green

var d1_1 = [[{title[0], data[0], color: color01}],[{title[1],  data[1],
color: color01}],[{title[2],  data[2], color: color01}],[{title[3],
data[3], color: color01}],[{title[4],  data[4], color: color01}],[{title[5],
data[5], color: color01}]];
var d1_2 = [{[title[0], data[6]], color: color02},{[title[1],  data[7]],
color: color02},{[title[2],  data[8]], color: color02},{[title[3],
data[9]], color: color02},{[title[4],  data[10]], color: color02},
{[title[5], data[11]], color: color02}];
var d1_3 = [{[title[0], data[12]], color: color03},{[title[1], data[13]],
color: color03},{[title[2], data[14]], color: color03},{[title[3],
data[15]], color: color02},{[title[4], data[16]], color: color02},
{[title[5], data[17]], color: color03}];
var d1_4 = [{[title[0], data[18]], color: color02},{[title[1], data[19]],
color: color02},{[title[2], data[20]], color: color02},{[title[3],
data[21]], color: color03},{[title[4], data[22]], color: color02},
{[title[5], data[23]], color: color02}];
var d1_5 = [{[title[0], data[24]], color: color02},{[title[1], data[25]],
color: color02},{[title[2], data[26]], color: color02},{[title[3],
data[27]], color: color03},{[title[4], data[28]], color: color02},
{[title[5], data[29]], color: color02}];
var d1_6 = [{[title[0], data[30]], color: color02},{[title[1], data[31]],
color: color02},{[title[2], data[32]], color: color02},{[title[3],
data[33]], color: color03},{[title[4], data[34]], color: color02},
{[title[5], data[35]], color: color02}];
var d1_7 = [{[title[0], data[36]], color: color02},{[title[1], data[37]],
color: color02},{[title[2], data[38]], color: color02},{[title[3],
data[39]],
color: color02},{[title[4], data[40]], color: color03},{[title[5],
data[41]],
color: color02}];

var data1 = [
{
    label: xaxis[0],
    data: d1_1,
    valueLabels: { show: true, verticalText: true },
        bars: {
            showValues: true,
            show: true,
            barWidth: 0.13,
            fill: true,
            lineWidth: 0,
            order: 0,
            //fillColor: "#0000FF",
            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.8 } ] }
        },
        //color: "#ffffff"
        color: "#0000FF"
    },
{
    label: xaxis[1],
    data: d1_2,
    bars: {
            showValues: true,
            show: true,
            barWidth: 0.13,
            fill: true,
            lineWidth: 0,
            order: 1,
            //fillColor: "#6495ED",
            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.8 } ] }
        },
        valueLabels: { show: true, verticalText: true },
        //color: "#ffffff"
        color: "#6495ED"
    },
    {
    label: xaxis[2],
    data: d1_3,
    bars: {
            showValues: true,
            show: true,
            barWidth: 0.13,
            fill: true,
            lineWidth: 0,
            order: 2,
            //fillColor: "#90EE90",
            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.8 } ] }
        },
        valueLabels: { show: true, verticalText: true },
        //color: "#ffffff"
        color: "#90EE90"
    },
    {
    label: xaxis[3],
    data: d1_4,
  bars: {
            showValues: true,
            show: true,
            barWidth: 0.13,
            fill: true,
            lineWidth: 0,
            order: 3,
            //fillColor: "#FF0000",
            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.8 } ] }
        },
        valueLabels: { show: true, verticalText: true },
        //color: "#ffffff"
        color: "#FF0000"
    },
    {
    label: xaxis[4],
    data: d1_5,
   bars: {
            showValues: true,
            show: true,
            barWidth: 0.13,
            fill: true,
            lineWidth: 0,
            order: 4,
            fillColor: "#f4b183",
            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.8 } ] }
        },
        valueLabels: { show: true, verticalText: true },
        //color: "#ffffff"
        color: "green"
    },
    {
    label: xaxis[5],
    data: d1_6,
   bars: {
            showValues: true,
            show: true,
            barWidth: 0.13,
            fill: true,
            lineWidth: 0,
            order: 5,
            //fillColor: "yellow",
            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.8 } ] }
        },
        valueLabels: { show: true, verticalText: true },
        //color: "#ffffff"
        color: "yellow"
    },
     {
    label: xaxis[6],
    data: d1_7,
   bars: {
            showValues: true,
            show: true,
            barWidth: 0.13,
            fill: true,
            lineWidth: 0,
            order: 6,
            //fillColor: "silver",
            fillColor: { colors: [ { opacity: 0.3 }, { opacity: 0.8 } ] }
        },
        valueLabels: { show: true, verticalText: true },
        //color: "#ffffff"
        color: "silver"
    }
,
    {
        label: "test"
    }

    ];

var t1 = [];
    for (var i = 0; i < tik.length; i += 1)
        t1.push([i+1, tik[i]]);

function plot_bar_chart(data1){
p = $.plot("#placeholder", data1, {
    xaxis: {
        min: 0,
        max: 6,
        mode: "categories",
        categories: { "PA_IN PROGRESS": 0.5, "PA_IN PROGRESS OPUS": 1.5, "PA_IN PROGRESS MICROWAVE": 2.5, "PA_COMPLETED": 3.5, "PA_CANCELLED": 4.5, "PA_TERMINATION ABNORMALLY": 5.5 },
        tickLength: 0,
        axisLabelUseCanvas: true,
        alignTicksWithAxis: true,
        font:{
            size:12,
            weight:"bold",
            family:"sans-serif",
            variant:"small-caps",
            color: "#000000"
        }
    },
    yaxis: {
        axisLabel: 'Number of Projects',
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 30,
        axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
        axisLabelPadding: 5
    },
    grid: {
        hoverable: true,
        clickable: false,
        borderWidth: 1
    },
    legend: {
        labelBoxBorderColor: "none",
        position: "right"
    },
    series: {
        shadowSize: 1,
    },
});


text:
Q: CAML query items in increments I currently have a sharepoint2010 list that contains roughly 200,000 records.
I want to get each record, tweak it, massage it, and store it in a SQL table.
As of now, I am using the sharepoint 2010 web service method GetListItems like so...
System.Xml.XmlNode nodeListItems = client.GetListItems("guid", "", query, viewFields, RowNumber, queryOptions, null);

querying 200000 records is too much to query at once. How can I get around this? The GetListItems method takes CAML query parameters.
Is there a way to do this in increments, like say 5000 records at a time? How would one structure the CAML query to do that?
Unless someone has a better way of accomplishing this altogether?

A: Yes, there is, you can paginate the results.  The fifth parameter is the page size, you have it set via RowNumber.  Set it to 5000 if you want pages of size 5000.
Details on accessing subsequent pages can be seen from the documentation for the GetListItems method

The GetListItems method supports server-side paging. The XML data
  returned by this method includes a ListItemCollectionPositionNext
  attribute inside the rs:Data element that contains the information to
  support paging. This string contains data for the fields in the sort
  and for other items needed for paging. You should consider this string
  internal and not to be modified; modifying it can produce unexpected
  results. The following example shows the form of this return value
  when paging is supported.
<rs:Data ListItemCollectionPositionNext="
Paged=TRUE&p_ID=100&View=
      %7bC68F4A6A%2d9AFD%2d406C%2dB624%2d2CF8D729901E%7d&PageFirstRow=
      101" Count=1000 >
   <z:row ows_FirstName="Nancy" ows_LastName="Name" ….. />
   ...
</rs:Data>

To get the next page of data, the queryOption parameter is used, as
  shown in the following example.
<QueryOptions>
  <Paging ListItemCollectionPositionNext="
    Paged=TRUE&p_ID=100&View=
    %7bC68F4A6A%2d9AFD%2d406C%2dB624%2d2CF8D729901E%7d&PageFirstRow=
   101" />
</QueryOptions>

So all you need to do is grab the data in that attribute from each page's result set and add it to the query to get the next page.


text:
Q: Checkbox does does not work in VB.Net form I have two checkboxes for two groupboxes to enable visibility or invisibility of each one at a time but somehow one is working(chboNew) the other one(chboIssue) doesn't!
here is the code I have written for it, any help would be appreciated:
Private Sub chboIssue_CheckStateChanged(sender As Object, e As EventArgs) Handles chboIssue.CheckStateChanged
    If chboIssue.Checked = True Then
        gbIssueSearch.Visible = True
        gbNewSearch.Visible = False
        chboNew.Checked = False
    ElseIf chboIssue.Checked = False Then
        gbIssueSearch.Visible = False
    End If
End Sub

Private Sub chboNew_CheckStateChanged(sender As Object, e As EventArgs) Handles chboNew.CheckStateChanged
    If chboNew.Checked = True Then
        gbNewSearch.Visible = True
        gbIssueSearch.Visible = False
        chboIssue.Checked = False
    ElseIf chboIssue.Checked = False Then
        gbNewSearch.Visible = False
    End If
End Sub

A: If user has to choose between new issue and issue search,one at a time.
Then you should use radio buttons, instead of checkbox.
Checkbox gives idea that user can choose both checkboxes at same time.
Which in your case is not true.

A: Changing the name of the checkboxes is not going to solve your issue. I noticed that for your chboNew.CheckStateChanged event handler in your elseif clause you are checking if chboIssue is checked, whereas in your other handler for chboIssue both your if/else clauses look at chboIssue. I'm thinking that may be part of your issue. Also, if only one of these boxes is supposed to be checked at a time, you may want to add logic to automatically uncheck the other whenever one is checked. For instance, in your chboNew handler, "If chboNew.Checked = True Then chboIssue = False", and the inverse in your chboIssue handler. Hope this helps.


text:
Q: How to process groups in series with multiindex in pandas? For example, i have a dataframe with noodles data, it has columns like brand, country, style, stars. The most important ones here are country and style. Country is responsible for country that the noodles were made in, and style is responsible for serving style (bowl, cup, etc). What i want to do, is to find the amount of noodles that used a certain style in each country, and then find the most used one. This is how i did the part of the task:
df = pd.read_csv('data.csv')
res1 = df.groupby(['country', 'style']).count()['brand']
res1

The result of this code looks kinda like this:
Country        Style
Australia      Cup       17
               Pack       5
Bangladesh     Pack       7
Brazil         Cup        2
               Pack       3
Cambodia       Pack       5
Canada         Bowl       8
               Cup       17
               Pack      16

What i actually want to do, is to get the max value in each style group. In my head, result should look kind like this:
Country        Style
Australia      Cup       17
Bangladesh     Pack       7
Brazil         Pack       3
Cambodia       Pack       5
Canada         Cup       17

Also i believe the code should kinda look like this(???), i mean as an idea:
res1.agg_func_to_group('Style', 'max')

Any ideas or suggestions on how to do that?
I could give you the data itself, if needed. Thanks in advance for attention


text:
Q: How to make a UIBarButtonItem NOT scaleToFit? I'm creating a UIBarButtonItem with a custom image:
UIButton *tempSpeedButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWidth, buttonHeight)];
        UIImage *speedImage = [[UIImage imageNamed:@"eye"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [tempSpeedButton setBackgroundImage:speedImage forState:UIControlStateNormal];
        [tempSpeedButton addTarget:self action:@selector(onSpeed) forControlEvents:UIControlEventTouchUpInside];
        tempSpeedButton.contentMode = UIViewContentModeScaleAspectFit;
        UIBarButtonItem* speedButton = [[UIBarButtonItem alloc] initWithCustomView:tempSpeedButton];

The image appears stretched out. How can I make it fit normally?
Thanks!

A: All I had to do was add this:
[tempSpeedButton sizeToFit];


text:
Q: Django Error: could not convert string to float in source code not in my own code When I try run python manage.py migrate to synchronize database I get error
File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 346, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 445, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate
    self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
  File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Library/Python/2.7/site-packages/django/db/migrations/migration.py", line 115, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Library/Python/2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
    field,
  File "/Library/Python/2.7/site-packages/django/db/backends/sqlite3/schema.py", line 179, in add_field
    self._remake_table(model, create_fields=[field])
  File "/Library/Python/2.7/site-packages/django/db/backends/sqlite3/schema.py", line 77, in _remake_table
    self.effective_default(field)
  File "/Library/Python/2.7/site-packages/django/db/backends/base/schema.py", line 211, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
    prepared=False)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 702, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 1804, in get_prep_value
    return float(value)
ValueError: could not convert string to float: Jestem watowcem

models.py file:
# -*- coding: utf-8 -*-
from django.db import models

# Create your models here.

class ProductWithFrames(models.Manager):
    def get_queryset(self):
        return super(ProductWithFrames, self).get_queryset().filter(has_frame=True)

class ProductWithoutFrames(models.Manager):
    def get_queryset(self):
        return super(ProductWithoutFrames, self).get_queryset().filter(has_frame=False)

class Product(models.Model):
    PRODUCT_SIZE = (
        ('50x50', '50x50'),
        ('50x70', '50x70'),
        ('70x50', '70x50'),
    )
    product_id = models.IntegerField()
    product_size = models.CharField(max_length = 5, choices = PRODUCT_SIZE, default='50x50')
    product_price = models.PositiveSmallIntegerField()
    has_frame = models.BooleanField(default = False)

    products = models.Manager()
    products_with_frames = ProductWithFrames()
    products_without_frames = ProductWithoutFrames()

    def _has_frame(self):
        if self.has_frame == True:
            return True
        return False
    # _has_frame.boolean = True
    # has_frame = property(_has_frame)

    def __str__(self):
        if self.has_frame:
            return "Oprawiony rozmiar ramy {} kosztuje {} zl".format(self.product_size, self.product_price)
        else:
            return "Nieoprawiony rozmiar ramy {} kosztuje {} zl".format(self.product_size, self.product_price)

So in my own code I haven't got any String like "Jestem watowcem". I have just removed it for test but error is still visible.
python manage.py makemigration <app> goes correctly
python manage.py migrate - call errors like above
Only one file from Error List is editable and it is manage.py but I haven't edited it since beggining of project.
So if in my own code I haven't got String variable but Python want to tell me that it can't convert value, does anybody know what can I do or where should I remove this variable?


text:
Q: If i click social media buttons of Heise Shariff from tx_news i get 404 error The URL is only partly transferred: https://....org/artikel/
Any idea how to solve this? Any other information needed?
Latest TYPO3 version 7.6.11, tx_news 5.2 and rx_shariff 9.0.0
Thanks for your help.

A: My problem was the canonical tag the missing addQueryString (thanks for the hint to Georg Ringer)
Here is my working code:
page.headerData {
    700 = TEXT
    700 {
    stdWrap.typolink.parameter.data = TSFE:id
    stdWrap.typolink.forceAbsoluteUrl = 1
    stdWrap.typolink.returnLast = url
    stdWrap.typolink.parameter.intval = 1
    stdWrap.typolink.useCacheHash = 1
    stdWrap.typolink.addQueryString = 1
    stdWrap.typolink.addQueryString.method = GET
    stdWrap.typolink.addQueryString.exclude = id, cHash
    htmlSpecialChars = 1
    wrap = <link href="|" rel="canonical" />
  }
}


text:
Q: Error thrown when adding vectorised constraints to JuMP I am trying to reproduce this model - the code in the tutorial is for an old version of JuMP/Julia and does not run.
However, when I try to add the constraint:
@constraint(model, con, c[i = 1:N] .== ( ((1 - τ) * (1 - l[i]) .* w[i]) + e[i]))
I get the error Unexpected assignment in expression 'c[i = 1:N]'.
Here is the reprex:
using Random
using Distributions
using JuMP
using Ipopt

Random.seed!(123)
N = 1000
γ = 0.5
τ = 0.2

ϵ = rand(Normal(0, 1), N)
wage = rand(Normal(10, 1), N)
consumption = (γ * (1 - τ) * wage) + (γ * ϵ)
leisure = (1 - γ) .+ (( 1 - γ) * ϵ) ./ (( 1 - τ ) * wage)

model = Model(Ipopt.Optimizer)
@variable(model, c[i = 1:N] >= 0)
@variable(model, 0 <= l[i = 1:N] <= 1)
@constraint(model, con, c[i = 1:N] .== ( ((1 - τ) * (1 - l[i]) .* w[i]) + e[i]))
@NLobjective(model, Max, sum(γ *log(c[i]) + (1-γ)*log(l[i]) for i in 1:N ) )

Does anyone know why this is being thrown and how to fix it?
Any and all help appreciated!
Running Julia 1.5.1

A: With the c[i = 1:N] in JuMP yo can only define variables.
With the constraints one way you could do is just:
w = wage # not in your code
e = ϵ  # not in your code
@constraint(model, con[i = 1:N], c[i] == ( ((1 - τ) * (1 - l[i]) .* w[i]) + e[i]))

A: Przemyslaw's answer is a good one. If you want to stick with the vectorized syntax, you can go
N = 1_000
e = rand(N)
w = rand(N)
τ = 0.2
model = Model()
@variable(model, c[i = 1:N] >= 0)
@variable(model, 0 <= l[i = 1:N] <= 1)
@constraint(model, c .== (1 - τ) .* (1 .- l) .* w .+ e)

Here is the JuMP documentation for constraints https://jump.dev/JuMP.jl/stable/constraints


text:
Q: JavaScript window.open onclick ('url') I just figured out that I needed this link to be inside a data tag, because the data uses " ", and I can't include both.
Is this possible to do with document.getElementById("id")?
Or do I need another script for this? As you can tell I'm not the best with JavaScripts yet. Hope to learn a thing or two.
Pop

<a href="#" class="emotes show-pop btn btn-default top" data-title="Settings" data-content="Pop">

A: You need to escape the " in the attribute value
<a href="#" class="emotes show-pop btn btn-default top" data-title="Settings" data-content="Pop">

A: After referring this stackoverflow post, I tried to reproduce your code as below. Thing you missed is that you need to escape '<','>' and '"'
Pop


text: Q: Term for a function from ℕ to ℕ where every element of the codomain is hit infinitely many times? The sequence A000120 is a familiar example of such a function. For other examples, see the answers to this question: Existence of a sequence that has every element of $\mathbb N$ infinite number of times


text:
Q: Help solving a error in openGL I am making a group work in openGL, and when i try to open the file that my partner gave me i have this error:
-------------- Build: Debug in CG ---------------
Linking console executable: bin/Debug/CG
ld: library not found for -lGL
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings
I've seen the same code working in his computer.
Is it cause he is working in Windows? and i am working in MacOSX? I am using CodeBlocks IDE.
Can anyone help me solving this?

A: The OpenGL library is actually a Framework on MacOSX.
It should link correctly if you replace -lGL by -framework OpenGL.

A: Try something like the below, as jweyrich said, OpenGL is a framework in Mac OS X:
gcc -framework OpenGL -framework GLUT -o test test.c

A: Check that you have the actual library, and that -lGL is the correct flag. The name of the library may be different on your system.


text:
Q: Add array to another array of larger size I have an array A of size 5000, and a smaller array B of arbitrary size but smaller than A. My smaller array always produces new values which I do not want to loose hence I add them to the array A and continue, however I am stuck because whenever I try to copy the smaller to the larger instead of appending from where it was left of it completely erases the prior values and array A becomes equal to array B.
offset = offset + B.length;
System.arraycopy(B, 0, A, offset, B.length);

This statement is in a loop that updates B everytime.

A: It would be a much better idea to use ArrayLists instead. An ArrayList is essentially an array with infinite capacity. You can just keep adding stuff and it will never run out of room. It also adds things to the end for you, without you having to compute the end index. So, if you make A and B ArrayLists, then your code becomes the following:
A.addAll(B);

That's it.

A: First of all, take a look at this link, and look at the section explaining the length parameter: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html. I think your problem resides in the length argument being passed in.
Also the statement offset = offset + B.length; should come after the loop, because you are passing in a variable size A.length + B.length, as supposed to just B.length, which is were you want to place array B.
the argument where A is is the destination array. So you have to redeclare A to be the length of offset.
Hope this helps.


text:
Q: DiscordPy Extension 'cogs.economy' raised an error: TypeError: object NoneType can't be used in 'await' expression I get the following error when i run my bot.
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: TypeError: object NoneType can't be used in 'await' expression

I have the extension economy.py in the folder cogs. economy.py:
from discord.ext import commands

class Economy(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author != self.client.user:
            await message.channel.send("hello")

    @commands.command()
    async def ping(self, ctx):
        await ctx.send("pong")

def setup(client):
    client.add_cog(Economy(client))

and my client.py has:
import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.message_content = True

prefix = "?"

client = commands.Bot(command_prefix=prefix, intents=intents)
@client.event
async def on_ready():
    await client.load_extension('hello')
    await client.load_extension('cogs.economy')
    print("Bot is ready")

client.run(token=token)

I have tried async-await for the setup but i still cant around this. This is my first time coding a bot. The 'hello' has just a command in it, and it works just fine. I have no idea how there is a NoneType object here.
Thanks.
Edit: Full Error
Traceback (most recent call last):
File "D:\Documents\PythonProjects\DiscordBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 946, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "D:\Documents\PythonProjects\DiscordBot\venv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\PythonProjects\DiscordBot\exp_bot.py", line 51, in on_ready
await client.load_extension('cogs.economy')
File "D:\Documents\PythonProjects\DiscordBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "D:\Documents\PythonProjects\DiscordBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: TypeError: object NoneType can't be used in 'await' expression

A: You didn't show FULL error message but it shows problem with await setup(self)
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/bot.py", line 946, in _load_from_module_spec
    await setup(self)
TypeError: object NoneType can't be used in 'await' expression

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/home/furas/main.py", line 18, in on_ready
    await client.load_extension('cogs.economy')
  File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/bot.py", line 1012, in load_extension
    await self._load_from_module_spec(spec, name)
  File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/bot.py", line 951, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: TypeError: object NoneType can't be used in 'await' expression

and it may suggest that setup() has to use async.
When I use async def setup(client) then I gets different error
/home/furas/cogs/economy.py:19: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
  client.add_cog(Economy(client))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

which may suggest that add_cog() has to use await

Code works for me when I add async and await.
async def setup(client):
    await client.add_cog(Economy(client))

BTW:
Documentation for load_extension also shows async def setup()


text:
Q: AssertJ: negating isEqualToComparingFieldByFieldRecursively I have this code for checking if an object is equals to another one comparing all fields recursively using JUnit 5 and AssertJ:
assertThat(financialDataContainer2.getStandardisedBooking())
    .isEqualToComparingFieldByFieldRecursively(initialBooking);

How can you have an assertion in AssertJ which is the negation of this one? Basically I want to be able to check if two objects are not equal by comparing recursively all fields.

A: See my answer to
How do I negate assertions in AssertJ?
In your case the code would be:
assertThat(Collections.singleton(actual)).noneSatisfy(actual ->
  assertThat(actual).isEqualToComparingFieldByFieldRecursively(unexpected)
);


text:
Q: SWT - Using EditingSupport in my TableViewer In my main dailog, I have a JFace TableViewer.  The last column of the table is a ComboBoxCellEditor.  They have the option of No, Yes, Both.  This all works as designed.
But here is my issue.

*

*If the user selects Both for the value.

*I need to run a method that will get current row data from the Array

*Change the value from both to No

*Make a copy of the data then change the value to Yes

*Add both back in to the Array

*Refresh the table

Table Example
From -
1002 | 001   | sss   |  part | both(user changed from default)

To -
1002 |  001  |  sss  |  part |  No

1002 |  001  |  sss  |  part | Yes

I am trying to figure out after both is selected how to run the method to do the rest.  I am assuming it has to be some sort of a listener.  Please have a look at my EditingSupport code and show me where I would start my method to do the rest.
public class OptionEditingSupport extends EditingSupport
{
    private ComboBoxCellEditor cellEditor;

    public OptionEditingSupport(ColumnViewer viewer) {
        super(viewer);
        cellEditor = new ComboBoxCellEditor(((TableViewer)viewer).getTable(), new String[]{"No", "Yes", "Both"}, SWT.DROP_DOWN);
        //cellEditor.setValue(0);
    }
    protected CellEditor getCellEditor(Object element) {
        return cellEditor;
    }
    protected boolean canEdit(Object element) {
        return true;
    }
    protected Object getValue(Object element) {
        return 0;
    }
    protected void setValue(Object element, Object value)
    {
        if((element instanceof AplotDatasetData) && (value instanceof Integer)) {
            Integer choice = (Integer)value;
            //String option = (choice == 0? "Yes":"No":"Both");
            String option = ((AplotDatasetData)element).getMarkupValue();;
            if(choice == 0) {
                option = "No";
            }
            else if(choice == 1) {
                option = "Yes";
            }
            else {
                option = "Both";
            }
            ((AplotDatasetData)element).setMarkupValue(option);
            getViewer().update(element, null);
        }
    }
}

A: As far as I understood your question, you want to duplicate one of your objects, add it to you model and refresh the viewer.
And all this should happen when the user selects "both" in the combobox. You already know, when this happens. You will end up in the else case of your setValue method. Then you can do what you have to do there:
protected void setValue(Object element, Object value)
{
    if((element instanceof AplotDatasetData) && (value instanceof Integer)) {
        Integer choice = (Integer)value;

        String option = ((AplotDatasetData)element).getMarkupValue();

        if(choice == 0) {
            option = "No";
        }
        else if(choice == 1) {
            option = "Yes";
        }
        else {
            option = "Both";

            // create a copy of your element
            // add it to your model
            // update the viewer
        }

        getViewer().update(element, null);
    }

}


text:
Q: How I Can make Scrolling toolbar with search box like amazone Hi I want to make scrollable toolbar with searchbox. on scrolling toolbar should be hide toolbar and show search box. Give me some suggestion that how i can build this kind of UI for my application.
Here i want something like this.

Here i am posting my xml design that is doing functionality near by this design but still it need furnishing.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:context=".MainActivity">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways|snap|exitUntilCollapsed"
                app:statusBarScrim="?attr/colorAccent">

                <androidx.constraintlayout.motion.widget.MotionLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    app:layoutDescription="@xml/collapsing_toolbar">

                    <View
                        android:id="@+id/toolbars"
                        android:layout_width="match_parent"
                        android:layout_height="120dp"
                        android:background="#efefef" />

                    <androidx.appcompat.widget.SearchView
                        android:id="@+id/search_view"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginTop="56dp"
                        android:layout_marginEnd="16dp"
                        android:background="@android:color/white"
                        android:elevation="4dp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />

                </androidx.constraintlayout.motion.widget.MotionLayout>

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#efefef"
                    android:minHeight="?attr/actionBarSize"
                    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

                    <androidx.appcompat.widget.SearchView
                        android:id="@+id/search_view_2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:visibility="gone"
                        android:layout_marginStart="16dp"
                        android:layout_marginEnd="?android:attr/actionBarSize"
                        android:background="@android:color/white"
                        android:elevation="4dp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />

                </androidx.appcompat.widget.Toolbar>

            </com.google.android.material.appbar.CollapsingToolbarLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nestedScrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <FrameLayout
                android:id="@+id/fragment_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="56dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </androidx.core.widget.NestedScrollView>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:layout_marginEnd="0dp"
            android:background="?android:attr/windowBackground"
            app:labelVisibilityMode="labeled"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />

    </androidx.constraintlayout.widget.ConstraintLayout>

*

*res/xml/collapsing_toolbar.xml

<Transition
    motion:constraintSetStart="@id/start"
    motion:constraintSetEnd="@+id/end">
    <OnSwipe
        motion:dragDirection="dragDown"
        motion:touchAnchorId="@id/toolbars"
        motion:touchAnchorSide="bottom" />
    <OnSwipe />
</Transition>

<ConstraintSet android:id="@+id/start">
    /** Very simple animation no need for start state*/

</ConstraintSet>

<ConstraintSet android:id="@+id/end">
    <Constraint
        android:id="@id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="0dp"
        android:layout_marginEnd="24dp"
        android:elevation="4dp"
        motion:layout_constraintEnd_toEndOf="parent"
        motion:layout_constraintStart_toStartOf="parent"
        motion:layout_constraintTop_toTopOf="parent" />

    <Constraint
        android:id="@id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp" />

</ConstraintSet>

below code placed in on Create Mehod
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initUI();

          nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                boolean isSearchViewVisible = isVisible(v);

                if (isSearchViewVisible){
                    searchView.setVisibility(View.GONE);
                    searchViewMain.setVisibility(View.VISIBLE);
                } else{
                    searchView.setVisibility(View.VISIBLE);
                    searchViewMain.setVisibility(View.GONE);
                }

            }
        });

    }

private boolean isVisible(View view){
    Rect scrollBounds = new Rect();
    nestedScrollView.getDrawingRect(scrollBounds);

    float top = 0f;
    View view1 = view;

    while (view1 instanceof NestedScrollView){
        top += (view1).getY();
        view1 = (View)view1.getParent();
    }

    float bottom = top + view.getHeight();
    return scrollBounds.top < bottom && scrollBounds.bottom >top;
}

A: You could use two searchviews (one inside toolbar and the other below toolbar) to achieve this. In your layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ScrollSearchActivity">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:context=".MainActivity">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#efefef"
                android:minHeight="?attr/actionBarSize"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

                <androidx.appcompat.widget.SearchView
                    android:id="@+id/search_view_2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:visibility="gone"
                    android:layout_marginStart="16dp"
                    android:layout_marginEnd="?android:attr/actionBarSize"
                    android:background="@android:color/white"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

            </androidx.appcompat.widget.Toolbar>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nestedScrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorPrimary"
                    android:padding="4dp">

                    <androidx.appcompat.widget.SearchView
                        android:id="@+id/search_view"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginEnd="16dp"
                        android:background="@android:color/white"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />
                </FrameLayout>

                <FrameLayout
                    android:id="@+id/fragment_container"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginBottom="56dp"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

            </LinearLayout>

        </androidx.core.widget.NestedScrollView>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:labelVisibilityMode="labeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Then in your activity, toggle the visibility of the search in the toolbar when the searchview below it is scrolled in and out of the screen.
public class ScrollSearchActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scroll_search_2);

        final SearchView mainSearchView = findViewById(R.id.search_view);
        final SearchView toolbarSearchView = findViewById(R.id.search_view_2);
        final NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView);

        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                boolean isSearchViewVisible = isSearchViewVisible(v,mainSearchView);

                if (isSearchViewVisible){
                    toolbarSearchView.setVisibility(View.GONE);
                    mainSearchView.setVisibility(View.VISIBLE);
                } else{
                    toolbarSearchView.setVisibility(View.VISIBLE);
                    mainSearchView.setVisibility(View.GONE);
                }

            }
        });
    }

    private boolean isSearchViewVisible(NestedScrollView nestedScrollView, View view){
        Rect scrollBounds = new Rect();
        nestedScrollView.getDrawingRect(scrollBounds);

        float top = 0f;
        View view1 = view;

        while (!(view1 instanceof NestedScrollView)){
            top += (view1).getY();
            view1 = (View)view1.getParent();
        }

        float bottom = top + view.getHeight();
        return scrollBounds.top < bottom && scrollBounds.bottom >top;
    }
}

You should get something like this:

EDIT
Use this in place of your isVisible() method
private boolean isViewVisible(NestedScrollView nestedScrollView, View view){
        Rect scrollBounds = new Rect();
        nestedScrollView.getDrawingRect(scrollBounds);

        float top = 0f;
        View view1 = view;

        while (!(view1 instanceof NestedScrollView)){
            top += (view1).getY();
            view1 = (View)view1.getParent();
        }

        float bottom = top + view.getHeight();
        return scrollBounds.top < bottom && scrollBounds.bottom >top;
    }

And call it this way boolean isSearchViewVisible = isSearchViewVisible(nestedScrollView,mainSearchView);

A: If you want to achieve an animation like in the gif and actually even better, you can use the new MotionLayout the gist of it is that you create your two states and swipe action in a motion scene. and MotionLayout will take care of everything.
Your layout file (This is only for the header. You can basically define your start state in the layout file)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutDescription="@xml/sample_collapsing_animation_scene">

    <View
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/md_green_300" />

    <androidx.appcompat.widget.SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/md_white_1000"
        android:elevation="4dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginStart="36dp"
        android:layout_marginEnd="36dp"
        android:layout_marginTop="40dp"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/your_scrolling_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar"/>

</androidx.constraintlayout.motion.widget.MotionLayout>

Your motion scene (Where you define your states and swipe triggers)
<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@id/start">
        <OnSwipe
            motion:dragDirection="dragUp"
            motion:touchAnchorId="@id/your_scrolling_content"
            motion:touchAnchorSide="top" />
        <OnSwipe />
    </Transition>

    <ConstraintSet android:id="@+id/start">
        /** Very simple animation no need for start state*/
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">

        <Constraint
            android:id="@id/search_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="24dp"
            android:layout_marginTop="0dp"
            android:layout_marginEnd="24dp"
            android:elevation="4dp"
            motion:layout_constraintEnd_toEndOf="parent"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent" />

        <Constraint
            android:id="@id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="56dp" />
    </ConstraintSet>
</MotionScene>

That's all you need, but in a real app, things can be a bit different.
Here is the link for MotionLayout
Here is a great reference on creating a CollapsingToolbar feel using motion layout.

A:
To achieve something similar to this, just paste this code inside your XML Layout:
      <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <com.google.android.material.appbar.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true">

                <com.google.android.material.appbar.MaterialToolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_scrollFlags="scroll|enterAlways" />

                <androidx.appcompat.widget.LinearLayoutCompat
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginHorizontal="10dp"
                    android:background="@color/white"
                    android:orientation="horizontal">

                    <androidx.appcompat.widget.AppCompatEditText
                        android:id="@+id/etSearch"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:background="@null"
                        android:drawableStart="@drawable/ic_toolbar_search"
                        android:drawablePadding="@dimen/margin_6"
                        android:hint="@string/search_hint"
                        android:imeOptions="actionSearch"
                        android:inputType="text"
                        android:maxLines="1"
                        android:padding="5dp"
                        android:textColor="@color/black"
                        android:textColorHint="@color/text_hint"
                        android:textSize="@dimen/text_size_13sp" />

                    <androidx.appcompat.widget.AppCompatImageView
                        android:id="@+id/ivCLear"
                        android:layout_width="@dimen/xlarge_margin"
                        android:layout_height="@dimen/xlarge_margin"
                        android:layout_gravity="center_vertical"
                        android:layout_marginEnd="@dimen/margin_6"
                        android:src="@drawable/ic_close"
                        android:visibility="gone" />
                </androidx.appcompat.widget.LinearLayoutCompat>
            </com.google.android.material.appbar.AppBarLayout>
        </androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
Q: How to use ZooKeeper with Hadoop for sharing a read/write variable among reducers My question is:
How can I use ZooKeeper with Hadoop, such that all reducers can getData() / setData() to one shared znode?
My use case is that I need to share a global read/write variable among reducers in my MapReduce job. I am trying to use ZooKeeper for this purpose.
I created a ZooKeeper object that creates a znode and gives it an initial value. Next step is that I need all reducers to be able to getData() / setData() for this znode. This requires passing the ZooKeeper object to all reducers, which I don't know how to do it. I tried to serialize the ZooKeeper object and pass it to reducers (through Configuration properties or through distributed cache), but ZooKeeper class is not serializable.
ZooKeeper tutorials and all examples I could find illustrate ZooKeeper with multi-threaded applications, but none of them show how to use ZooKeeper with mappers or reducers.

A: You cannot pass the ZooKeeper object itself to the mappers/reducers. Just identify the config needed to instantiate the ZooKeeper object  within the mapper/reducer (like connectionString) and pass it via Configuration properties.
The interaction with ZooKeeper within mapper/reducers does not differ from the a usual Java program.


text:
Q: How to pass the webservice results as an input list for a batch apex class? i read the documentation and it has been given like the one given below.
global class UpdateInvoiceFields implements Database.Batchable<sObject>{
   global final String Query;
   global final String Entity;
   global final String Field;
   global final String Value;

   global UpdateInvoiceFields(String q, String e, String f, String v){
             Query=q; Entity=e; Field=f;Value=v;
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC,
                       List<sObject> scope){
      for(Sobject s : scope){s.put(Field,Value);
      }      update scope;
   }

   global void finish(Database.BatchableContext BC){

   }

}

also, the code snippet which is used to invoke the above batch is given below,
// Query for 10 invoice statements
String q = 'SELECT Description__c FROM Invoice_Statement__c LIMIT 10';
String e = 'Invoice_Statement__c';
String f = 'Description__c';
String v = 'Updated description';
Id batchInstanceId = Database.executeBatch(new UpdateInvoiceFields(q,e,f,v), 5);

Instead of using a query to invoke a batch, i need to send a custom list which is not a sobject to the batch to start with. Is that possible? Any ideas?
Thanks,
Baskaran

A: Would be great to learn more about what is driving your requirement to update fields this way (third party system?). But it's definitely possible, you can hand in a non-SObject iterable like this:
public class InvoiceFieldUpdater implements Database.Batchable<FieldDto> {

    /**
     * You will need to massage the response
     * from your web service into this class.
     */
    public class FieldDto {
        String id;
        String entity;
        String field;
        String value;
    }

    private List<FieldDto> dtos;

    public InvoiceFieldUpdater(List<FieldDto> dtos) {
        this.dtos = dtos;
    }

    public Iterable<FieldDto> start(Database.BatchableContext context) {
        return this.dtos;
    }

    /**
     * You can dynamically instantiate the correct
     * type of SObject for performing the update.
     */
    public void execute(Database.BatchableContext context, List<FieldDto> scope) {
        FieldDto dto = scope[0];

        SObject invoice = (SObject)Type.forName(dto.entity).newInstance();
        invoice.put(dto.field, dto.value);
        invoice.Id = dto.id;
        update invoice;
    }

    public void finish(Database.BatchableContext context) {}
}

Example usage:
List<InvoiceFieldUpdater.FieldDto> dtos = new List<InvoiceFieldUpdater.FieldDto>();
InvoiceFieldUpdater.FieldDto dto;

dto = new InvoiceFieldUpdater.FieldDto();
dto.id = '001d000000UaWiX';
dto.entity = 'Account';
dto.field = 'Name';
dto.value = 'Herp Derp Doop';
dtos.add(dto);

dto = new InvoiceFieldUpdater.FieldDto();
dto.id = '001d000000UaWiZ';
dto.entity = 'Account';
dto.field = 'Name';
dto.value = 'Foo Bar Baz';
dtos.add(dto);

dto = new InvoiceFieldUpdater.FieldDto();
dto.id = '001d000000UaWiW';
dto.entity = 'Account';
dto.field = 'Name';
dto.value = 'One Two Three';
dtos.add(dto);

Database.executeBatch(new InvoiceFieldUpdater(dtos), 1);


text:
Q: Clever way of creating a full factorial sampling from struct fields I have (for example) this struct array in MATLAB
g=struct();
g.var1=[0,1,2];
g.var2=[5,6,7];
g.var3={'a','b','c'};
...

I want to create a cell array that samples (meshgrids) all fields one by one
Wanted a cell array;
M×N cell array
{[0]}    {[5]}    {'a'}
{[0]}    {[5]}    {'b'}
{[0]}    {[5]}    {'c'}
{[1]}    {[5]}    {'a'}
{[1]}    {[5]}    {'b'}
{[1]}    {[5]}    {'c'}
{[2]}    {[5]}    {'a'}
{[2]}    {[5]}    {'b'}
{[2]}    {[5]}    {'c'}
{[0]}    {[6]}    {'a'}
{[0]}    {[6]}    {'b'}
{[0]}    {[6]}    {'c'}
{[1]}    {[6]}    {'a'}
{[1]}    {[6]}    {'b'}
{[1]}    {[6]}    {'c'}
...
...

I want my code to work for all general cases, such as an input struct with only 1 field or many fields.
What is a clever way of coding this?

A: You can use any of the answers to this question to get all combinations of numeric vectors. I'll define the top answer as the function getIndices and use the output indices to operate on your generic structure g.
The only extra handling you have to have is getting numeric arrays and cell arrays to place nice, I simply added an isnumeric check to convert accordingly.
flds = fieldnames( g ); % get structure fields
% Get indices of fields (1:n for each field) and get combinations
idx = cellfun( @(fld) 1:numel(g.(fld)), flds, 'uni', 0 );
idx = getIndices( idx );
% Create output
out = cell(size(idx,1),numel(flds));
for ii = 1:numel(flds)
    if isnumeric( g.(flds{ii}) )
        out(:,ii) = num2cell( g.(flds{ii})(idx(:,ii)) );
    else
        out(:,ii) = g.(flds{ii})(idx(:,ii));
    end
end

function combs = getIndices( vectors )
    % Source: https://stackoverflow.com/a/21895344/3978545
    n = numel(vectors); %// number of vectors
    combs = cell(1,n); %// pre-define to generate comma-separated list
    [combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); %// the reverse order in these two
    %// comma-separated lists is needed to produce the rows of the result matrix in
    %// lexicographical order
    combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1
    combs = reshape(combs,[],n); %// reshape to obtain desired matrix
end