text:
Q: Does static data member specialization in CRTP violate ODR? First of all, I know this question might seem a duplicate. But I've read many posts with a similar question and didn't find an answer.
Second of all, I haven't had any issue with my solution so far. So I'm asking rather if my solution is a correct one with no pitfalls.
Suppose I have a class template Particle which is supposed to be a base class in the CRTP and is intended to have a static variable fName which may differ from instance to instance:
Base
Particle.h
#pragma once

#include <iostream>
#include <string>

template<typename CONCRETE_PARTICLE>
class Particle
{
    private :
        static const std::string fName;

    public :
        static const std::string& GetName() { return fName; }
};

// Default name. If I'm not mistaken this is fine regarding ODR.
template<typename CONCRETE_PARTICLE>
const std::string Particle<CONCRETE_PARTICLE>::fName = "Unknown";

So other particles inherit (and instantiate) from this class. Suppose the user creates a new Particle and they should have a choice either to specify a name of their new particle or not. In the latter case the name would be "Unknown".
Unnamed particle
Tachyon.h
#pragma once

#include "Particle.h"

class Tachyon : public Particle<Tachyon>
{
    public :
        Tachyon();
        ~Tachyon() = default;
};

with nothing special in the Tachyon.cpp (I made .cpp files in order to check that ODR isn't violated).
On the other hand, what if the name is to be specified. What should they do?
Named particle
Muon.h
#pragma once

#include "Particle.h"

class Muon : public Particle<Muon>
{
    public :
        Muon();
        ~Muon() = default;

};

// Specification declaration (???)
// Tell the compiler that Particle<Muon>::fName is defined somewhere
// and not to take the default value into account (???)
template<>
const std::string Particle<Muon>::fName;

Muon.cpp
#include "Muon.h"

Muon::Muon() {}

template<>
const std::string Particle<Muon>::fName = "Muon";

Main.cpp
#include "Muon.h"
#include "Tachyon.h"

int main()
{
    std::cout << Particle<Muon>::GetName() << "\n"; // prints "Muon"
    std::cout << Particle<Tachyon>::GetName() << "\n"; // prints "Unknown"
    return 0;
}

As I said I don't get any error and the program works as intended. But I am a bit confused by the mix of CRTP + ODR + static data member declaration/definition so the question.

A: It's not clear exactly what rule you think this might violate, but this program is well formed.  In particular, explicit specializations of a templated static variable are definitions only if they have an initializer ([temp.expl.spec]/14).  (Non-member variable templates instead use extern to merely declare specializations.)  Nor is there any use of the primary template before the explicit specialization is declared so long as the derived class doesn't do so.
That said, you could easily avoid using specializations here entirely: use SFINAE to detect a member fName and return"Unknown" if there's none.  Or just look up fName as CONCRETE_PARTICLE::fName to use any declared there.  (Incidentally, don't use MACRO_NAMES for template parameters.)


text:
Q: Ordering matrices by column I Have this matrix:
matrix:

[['I' 'N' 'T' 'E' 'R' 'E' 'S' 'T' 'I' 'N' 'G']

['D' 'G' 'F' 'F' 'G' 'D' 'A' 'A' 'D' 'V' 'A']

['A' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ']]

Want to order like this, without changing the position of the following rows in alphabethic order, only the first row:
matrix

[['E' 'E' 'G' 'I' 'I' 'N' 'N' 'R' 'S' 'T' 'T']

 ['F' 'D' 'A' 'D' 'D' 'G' 'V' 'G' 'A' 'F' 'A']

 [' ' ' ' ' ' 'A' ' ' ' ' ' ' ' ' ' ' ' ' ' ']]

Is there any way i can do this with numpy?

A: Assuming this input:
array([['I', 'N', 'T', 'E', 'R', 'E', 'S', 'T', 'I', 'N', 'G'],
       ['D', 'G', 'F', 'F', 'G', 'D', 'A', 'A', 'D', 'V', 'A'],
       ['A', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']],
      dtype='<U1')

Use indexing and np.argsort:
out = matriz_senha[:, np.argsort(matriz_senha[0])]

Output:
array([['E', 'E', 'G', 'I', 'I', 'N', 'N', 'R', 'S', 'T', 'T'],
       ['F', 'D', 'A', 'D', 'D', 'G', 'V', 'G', 'A', 'F', 'A'],
       [' ', ' ', ' ', 'A', ' ', ' ', ' ', ' ', ' ', ' ', ' ']],
      dtype='<U1')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we conclude that $gH=Hg$? Suppose $G$ is an infinite group and $H$ is an infinite subgroup of $G$.
Let $g\in G$.
Suppose $\forall h\in H\ \exists h'\in H$ such that $gh=h'g$.
Can we conclude that $gH=Hg$?
What if $G$ and $H$ are of finite orders?

A: If $g$ is a fixed element, all we can conclude is that $gHg^{-1}\subseteq H$. This does not necessarily imply $xHx^{-1}\subseteq H$ for other elements $x\in G$. Nor does it even mean $gHg^{-1}=H$ since it's possible for the conjugate $gHg^{-1}$ to be a proper subset of $H$. There are some examples here as well as numerous other examples in links. My favorite is letting $\alpha$ be the automorphism of $\mathbb{Q}$ defined by the formula $\alpha(x)=\frac{1}{2}x$, forming the semidirect product $\mathbb{Q}\rtimes\langle \alpha\rangle$, then considering the strict containment $\langle 2\rangle \subset \alpha\langle 2\rangle\alpha^{-1}=\langle 1\rangle$.
The conjugation map $x\mapsto gxg^{-1}$ is bijective, so $|gHg^{-1}|=|H|$, which means if $H$ is finite then the containment $gHg^{-1}\subseteq H$ implies $gHg^{-1}=H$.
If $gHg^{-1}\subseteq H$ for all $g\in G$, then $gHg^{-1}=H$ for all $g\in G$. To see this, replace $g$ with $g^{-1}$ then notice $g^{-1}H(g^{-1})^{-1}\subseteq H$ is equivalent to $H\subseteq gHg^{-1}$, so both containments mean equality.


text:
Q: Securing Cookie Based Authentication I am currently re factoring one of my web applications and I was hoping for some advice on improving my security.
I'll note that the application is in ASP.net and the current implementation prevents me from using integrated authentication. This is also in no way an application that requires high security, I just like having my bases covered.
In the past I've stored the id and a token .
The token is a hash of the user's ID + the user's Salt (reusing the value from the auth info)
When a user visits the site the ID is checked against the token and authed accordingly.
It occurs to me that there is a big hole here.
Theoretically if someone got their hands on a salt value all they'd need to do is guess the hash algorithm and iterate through the possible IDs until they got in. I don't expect this to happen, but it still seems like a mistake.
Any advice on how to properly confirm that user cookies haven't been altered?

A: The best way is to store a session ID as the cookie value.
Whenever user logs in, you create a record in database or some other session store with a random session ID. Put the ID in a cookie. When you see the cookie later, you can retrieve all user information from database.
This approach has following advantages,

*

*It's very secure. Session ID is simply a random number. You don't have to worry about compromised key or salt.

*The cookie can be easily revoked from server. All you have to do is to remove the session record and that renders the ID useless.

*The cookie value can be really short.

If this doesn't work for you, try encryption. Hash would be my last choice. Hash itself is useless. You have to store user id and other information in a different cookie in clear. You ended up expose user information.

A: Two ways:

*

*Encrypt it with a Symmetric algorithm (AES).

This is good because it lets you decrypt it; but it may be argued that you don't need to decrypt it (depending on what else you store in there).

*Hash and Sign it. Again this uses a private key, so even if someone knows the exact contents, they can't reproduce the hash, because they need the private key.

I'd probably (and have previously) go with option #1.

A: The way most web sites do it is to authenticate the use and if successful they send the browser a cookie to store and send in any subsequent requests. If an attacker were able to get hold of the token (before it expired) they will be able to impersonate the user.
Because of this the cookie and authentication process should always be carried out over a https session. The only realsitic way an attacker has to get hold of the cookie then is to intercept it on the end user's computer and if they are able to do that they can probably install a key stroke logger and get the user's password anyway.
As to what kind of token to use it doesn't matter so long as it's pseudo-random enough to make it computationally expensive for an attacker to guess. I myself use GUIDs. if you need extra information in the cookie apart from just a sessionid you could append a GUID to it and then probably hash or encrypt it just for a belt and braces approach.

A: why not only store the hash in the cookie, or any other pseudorandom number? Then check against the database to get the user ID.
Other things:
Make the cookie http only, ie cannot be set with javascript
If it is an option, make it only be transmitted with https data


text:
Q: How to verify that urls are redirected its respective page in Selenium? I am trying to automate - verification of top nav links of https://www.zillow.com.

For that I am matching actual urls with expected urls. But in page class method this line retruns null. I don't get it why?
String urlp = locator.all_topnav_links.get(i).getAttribute("href");

Method in page class:
public void verify_topnav_links() {
        System.out.println("Started");
        for (int i = 0; i < locator.all_topnav_links.size(); i++) {
            System.out.println(locator.all_topnav_links.size());
            if (locator.all_topnav_links.get(i).isDisplayed() == true) {
                String link=locator.all_topnav_links.get(i).getText();
                System.out.println(link);
                String urlp = locator.all_topnav_links.get(i).getAttribute("href");
                System.out.println("Links are : " + urlp);
                // now click link one by one
                locator.all_topnav_links.get(i).click();
                driver.navigate().back();
                // 2 verify before url with current opened url
                //Assert.assertEquals(urlp, driver.getCurrentUrl());

            }

Locator in locator class:
@FindAll({@FindBy(xpath = "//ul[@data-zg-section='main']/li")})
    public List<WebElement> all_topnav_links;

Test case in test class:
@Test
    public void verify_TopNav_links()
    {

        hpage.verify_topnav_links();
    }

Also I am not sure whether this correct approach or not. Can anybody tell me the best approach to verify this scenario.
Note: This zillow.com will starts to display captcha if we open multiple times using selenium. To ignore it manually remove catpcha parameters from the url when test case is getting executed.

A: It appears you need to use
//ul[@data-zg-section='main']/li/a

here
@FindAll({@FindBy(xpath = "//ul[@data-zg-section='main']/li")})
    public List<WebElement> all_topnav_links;

This xpath
//ul[@data-zg-section='main']/li

Seems to contain multiple elements. But you're trying to access the href attribute directly. The li here doesn't have a href attribute.


text:
Q: Clever references to theorem lists I would like an automatic solution to referencing theorem environments containing lists using cleveref. In other words, if Corollary 1.2 contains parts (a) and (b), I want \cref to output "Corollary 1.2(a)" when referring to that theorem part. Horever, in proofs and similar situations, I want to be able to refer to, say, "part (a)" without having "1.2" in front.
Much of the solution is already available in this excellent answer, which contains the following example. However, as you see, I cannot write simply "(a)" without having the "1.2" part attached to it. How can this solution be modified to allow references to individual theorem parts without also getting the theorem number?
EDIT: I might add that I am actually going to use the ntheorem package to produce theorems, but I assume that it does not really change anything in the solution. And I think it is better to build upon the existing example.

\documentclass[english]{amsart}
\usepackage{babel}
\usepackage{enumitem}  % for '\newlist' and '\setlist' macros
\usepackage[colorlinks=true]{hyperref}
%%\usepackage{amsthm}  % is loaded automatically by amsart document class
\usepackage[nameinlink]{cleveref}

\newtheorem{thm}{Theorem}[section]
\crefname{thm}{Thm.}{Thms.} % singular and plural forms of label

\newtheorem{cor}[thm]{Corollary}
\crefname{cor}{Cor.}{Cors.} % singular and plural forms of label

\newlist{enumthm}{enumerate}{1} % set up a dedicated enumeration env.
\setlist[enumthm]{label=\upshape(\alph*),ref=\upshape\thethm(\alph*)}
\crefalias{enumthmi}{thm} % alias 'enumthmi' counter to 'thm'

\newlist{enumcor}{enumerate}{1} % set up a second dedicated enumeration env.
\setlist[enumcor]{label=\upshape(\alph*),ref=\upshape\thecor(\alph*)}
\crefalias{enumcori}{cor} % alias 'enumcori' counter to 'cor'

\begin{document}
\setcounter{section}{1} % just for this example

\begin{thm}\label{Thm:One}
The following properties hold:
\begin{enumthm}
    \item\label{Thm:One:1} \(1>0\)
    \item\label{Thm:One:2} \(0<1\)
\end{enumthm}
\end{thm}

\begin{cor}\label{Thm:Two}
The following properties hold as well:
\begin{enumcor}
    \item\label{Thm:Two:1} \(2>1\)
    \item\label{Thm:Two:2} \(1<2\)
\end{enumcor}
\begin{proof}
\ref{Thm:Two:1} follows from \ref{Thm:One:1} by adding 1 on both sides. Similarly, \cref{Thm:Two:2} follows from \cref{Thm:One:2}.
\end{proof}
\end{cor}

\end{document}

A: cleveref stores the values of the enumi counter. You can extract them and then format them (I didn't try to add links, but this is possible to):
\documentclass[english]{amsart}
\usepackage{babel}
\usepackage{enumitem}  % for '\newlist' and '\setlist' macros
\usepackage[colorlinks=true]{hyperref}
%%\usepackage{amsthm}  % is loaded automatically by amsart document class
\usepackage[nameinlink]{cleveref}

\newtheorem{thm}{Theorem}[section]
\crefname{thm}{Thm.}{Thms.} % singular and plural forms of label

\newtheorem{cor}[thm]{Corollary}
\crefname{cor}{Cor.}{Cors.} % singular and plural forms of label

\newlist{enumthm}{enumerate}{1} % set up a dedicated enumeration env.
\setlist[enumthm]{label=\upshape(\alph*),ref=\upshape\thethm(\alph*)}
\crefalias{enumthmi}{thm} % alias 'enumthmi' counter to 'thm'

\newlist{enumcor}{enumerate}{1} % set up a second dedicated enumeration env.
\setlist[enumcor]{label=\upshape(\alph*),ref=\upshape\thecor(\alph*)}
\crefalias{enumcori}{cor} % alias 'enumcori' counter to 'cor'

\makeatletter
\newcounter{subcreftmpcnt} %
\newcommand\alphsubformat[1]{(\alph{#1})} %adapt ....
\newcommand\subcref[2][\alphsubformat]{%
\ifcsname r@#2@cref\endcsname
  \cref@getcounter {#2}{\mylabel}%
  \setcounter{subcreftmpcnt}{\mylabel}%
  \alphsubformat{subcreftmpcnt}%
 \else ?? \fi}
\makeatother
\begin{document}
\setcounter{section}{1} % just for this example

\begin{thm}\label{Thm:One}
The following properties hold:
\begin{enumthm}
    \item\label{Thm:One:1} \(1>0\)
    \item\label{Thm:One:2} \(0<1\)
\end{enumthm}
\end{thm}

\begin{cor}\label{Thm:Two}
The following properties hold as well:
\begin{enumcor}
    \item\label{Thm:Two:1} \(2>1\)
    \item\label{Thm:Two:2} \(1<2\)
\end{enumcor}
\begin{proof}
\subcref{Thm:Two:1} follows from \ref{Thm:One:1} by adding 1 on both sides. Similarly,  \subcref{Thm:Two:2}  follows from \cref{Thm:One:2}.

\end{proof}
\end{cor}

\end{document}

A: I've interpreted your requirements and objectives as follows. First, the document has one or more important theorem-like environments (e.g., "Theorem") which may have multiple parts. When cross-referencing these parts individually, the cross-references should display the full (i.e., composite) number as well as the label "Theorem". Second, there are other, less important theorem-like environments (e.g., "Corollary") which may also have multiple parts. However, when cross-referencing parts of the less-important environments, only the sub-number (or letter) should be shown, not the full composite number. Moreover, the word "part" rather than "corollary" should be used as a label prefix.
If this understanding is correct, the following code should do what you're looking for. (If you don't want the label names to be part of the hypertargets, remove the option nameinlink while loading cleveref.)

\documentclass{article}
\usepackage{amsmath,amsthm}
\usepackage{enumitem}  % for '\newlist' and '\setlist' macros
\usepackage[colorlinks=true]{hyperref}
\usepackage[nameinlink]{cleveref}

\newtheorem{thm}{Theorem}[section]
\newtheorem{cor}[thm]{Corollary}

\newlist{enumthm}{enumerate}{1} % a dedicated enum. env.
   \setlist[enumthm]{label=\upshape(\alph*),
                     ref=\upshape\thethm(\alph*)}
\newlist{enumcor}{enumerate}{1} % another dedicated enum. env.
   \setlist[enumcor]{label=\upshape(\alph*)}

\crefname{thm}{Thm.}{Thms.}
\crefname{cor}{Cor.}{Cors.}
\crefname{enumthmi}{Thm.}{Thms.}
\crefname{enumcori}{part}{parts}

\begin{document}
\setcounter{section}{1} % just for this example

\begin{thm}\label{Thm:One}
The following properties hold:
\begin{enumthm}
    \item\label{Thm:One:a} $1>0$
    \item\label{Thm:One:b} $0<1$
\end{enumthm}
\end{thm}

\begin{cor}\label{Thm:Two}
The following properties hold as well:
\begin{enumcor}
    \item\label{Thm:Two:a} $2>1$
    \item\label{Thm:Two:b} $1<2$
\end{enumcor}
\begin{proof}
\Cref{Thm:Two:a} follows from \cref{Thm:One:a} by adding 1 on both sides. Similarly, \cref{Thm:Two:b} follows from \cref{Thm:One:b}.
\end{proof}
\end{cor}

\Cref{Thm:One:a,Thm:One:b} \dots;
\cref{Thm:Two:a,Thm:Two:b} of \cref{Thm:Two} \dots
\end{document}


text:
Q: Visible content of 2 variables in bash is the same, but the length is different These 2 variables will have the same visible content
  x_sign1="aabbccdd_and_somthing_else"

  var1="...."
  [........]
  x_sign2=$(echo -n "${var1}${var2}${var3}" | shasum -a 256)
  echo $x_sign2

  ====>
  aabbccdd_and_somthing_else -

Note the "-" in the end.
However, their lengths will be different. Even though the x_sign2 doesn't contain a new line symbol. To ensure this:
  x_sign22=$(echo -n "${var1}${var2}${var3}" | shasum -a 256 | tr -d '\n')

But:
  echo ${#x_sign1}
  ====> 64
  And:

And:
  echo ${#x_sign2}

  ====> 67

  echo ${#x_sign22}

  ====> 67

The difference is 3 symbols. The visible content is identical.
Also, when I make a request via curl to a REST API which needs that value of a signature, x_sign1 always succeeds, whereas x_sign2 doesn't -- "wrong signature"
Why? How to fix that?

A: $ echo foo |shasum -a 256
b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c  -
                                                                ^^

Note that there are two spaces in the output of shasum before the filename. When the input is taken from stdin, shasum prints a dash as the filename.
If you run echo foo | shasum | od -c you can check that, and see the newline at the end also. The newline, however, is removed by the command substitution, so removing it explicitly with tr doesn't do anything. (see here and here)
The two spaces and the dash are three characters that cause the difference in your counts.
To get just the hash, you could use parameter expansions to remove anything after the first space, e.g.:
$ h=$(echo foo | shasum -a 256)
$ h=${h%% *}
$ printf ">%s<\n" "$h"
>b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c<

The ${var%%pattern} expands to the value of var with the longest suffix matching pattern removed.


text:
Q: Windows batch Do was unexpected at this time Can anyone please find here that why I am getting error "Do was unexpected at this time"?
echo
for /F "tokens=*" %%A in (myfile.txt) do (
    S:
    cd \WRO_Regression_results\%%A

    FOR /F %%i IN ('dir /b /ad-h /o-d') DO (
        SET b=%%i
        GOTO :found
    )
    echo No subfolder found
    goto :eof

    echo Most recent subfolder: %b%
    cd %b%
    dir

    find /c "O K" tooling.report
    if %errorlevel% equ 1 goto notfound
    echo found
    goto done

    :notfound
    echo notfound
    goto done

    :done
)

pause

A: I believe the problem is that you're attempting to define labels within the FOR loop. This is probably not allowed (though I know of no definitive reference for CMD syntax). Here's a slightly modified version of your script (with :found defined).
echo
for /F "tokens=*" %%A in (myfile.txt) do (
    S:
    cd \WRO_Regression_results\%%A

    FOR /F %%i IN ('dir /b /ad-h /o-d') DO (
        SET b=%%i
        GOTO :found
    )
    echo No subfolder found
    goto :eof

    echo Most recent subfolder: %b%
    cd %b%
    dir
)

:found
find /c "O K" tooling.report
if %errorlevel% equ 1 goto notfound
echo found
goto done

:notfound
echo notfound
goto done

:done

pause

If you wanted found and notfound to execute for every item in the loop, you could do something like this. Delayed expansion is necessary to access variables that change within the FOR loop(s). CALL can be used to treat labels like subroutines. AFAIK, there's no way to break out of a FOR loop in CMD, so the FOUND variable is a sentinel value that prevents b from being set after the first iteration through the loop. If you describe the expected behavior of your script, I would have a better idea how to achieve the desired goal.
SETLOCAL ENABLEDELAYEDEXPANSION

echo for /F "tokens=*" %%A in (myfile.txt) do (
    S:
    cd \WRO_Regression_results\%%A

    SET FOUND=0
    FOR /F %%i IN ('dir /b /ad-h /o-d') DO (
        IF NOT !FOUND!==1 (
            SET b=%%i
            SET FOUND=1
        )
    )
    IF !FOUND!==1 (CALL :found) ELSE (CALL :notfound)

    echo Most recent subfolder: %b%
    cd %b%
    dir )

:found
find /c "O K" tooling.report
if %errorlevel% equ 1 goto notfound
echo found
EXIT /B

:notfound
echo notfound
EXIT /B

:done

pause


text:
Q: Checking variable type in Ruby I have an issue checking variable types in ruby. Here is a sample code of python that I would like to replicate in ruby. I would like to check the input type: whether string, int, or list, and proceed to a specific printing action.
def printing (input):
    if type(input) == type(""):
        pass
    elif type(input) == type(1):
        pass
    elif type(input) == type([]):
        pass
    elif type(input) == type({}):
        pass
    elif type(input) == type(()):
        pass

I cannot find a method that will do this in ruby. The code below is what I want it to look like. I am assuming that I have to check the type at the case stage.
def printing (element)
    case element
    when element.type("")
        puts element
    when element.type(2)
        puts element
    when element.type({})
        element.each_pair { |name, val|  print "#{name} : #{value}"}
    when element.type([])
        element.each {|x| print x}
    end
end

A: I think you are looking for Object#class. Here:
element = {}
element.class
# => Hash
a = []
a.class
# => Array

This will make your switch case as follows:
case element
when String
 # do something
when Fixnum
 # do something
when Hash
 # do something
when Array
 # do something
end

Note:
As mentioned by @ndn in comments below, case statement should not have .class in it (which I had initially in my answer). You can find the explanation here.

A: This is not the "correct answer", I would simply like to point out that you should not use type in python you should use isinstance instead
isinstance(input, list) # test for list
isinstance(inpit, [float, int]) # test for number

if you are using python 3 you can check for abstract base classes
import collections
isinstance(input, collections.abs.Sequence) # sequence = tuple, list and a lot of other stuff that behaves that way


text:
Q: How the Sugar Record model will be created for given JSON I have following JSON and I want to create Sugar Record Class for it to store it in a database but I am not able to figure out weather I will need multiple model class or single would be enough please help me with this.
{
    "command": "AN",
    "tripId": 0,
    "tripData": {
        "DeviceId": "30050",
        "DispatcherId": 1,
        "PaxLimit": 50,
        "DriverId": 6,
        "Trips": [{
            "Stops": [{
                "Id": 1,
                "ScheduleTime": "06:00"
            }, {
                "Id": 5,
                "ScheduleTime": "07:00"
            }],
            "RouteId": 5,
            "ToStopId": 5,
            "TripId": 123,
            "FromStopId": 1
        }]
    }
}

A: It really depends on the object you want to store. Because Sugar doesn't support 1 to many relationships. I see your Trips and Stops attributes (in the JSON) are both arrays in the JSON. It is not possible to save that in the Sugar database. Because you cannot store a List with Sugar.
You can choose for yourself if you would like one single class containing all attributes that are in the JSON object. The other options is to use Nested Classes.
It doesn't matter what option you choose because you can get the data out of the JSON and put it in the right Class. The only thing that is important is that you can't use Lists in a Class.
So it really is your own choice if you use one or multiple classes.


text:
Q: Are there any jEdit syntax highlighting modes for Objective-J I have found some in the Cappuccino website (vim, textmate and SubEthaEdit), but not for jEdit, and unfortunately I'm just starting on Objective-J so can't make my own. If anyone has got one of them lying around it would be greatly appreciated.

A: According to the JEdit features page it already supports Objective C.

A: One of my favorite things about JEdit is how easy it is to define a new syntax highlighting mode.  I work in a land in which every fool wants to create his own custom configuration file language and I've gotten to where I can create a new approximate syntax highlighting mode in about 5 minutes.  I start by copying a mode that is similar to the new language I wanted to create and then iteratively refining the edit mode as I learn more parts of the language. I did this with Specman ( a hardware verification language ) as I was going through the intro course.


text:
Q: C# List to JSON using Newtonsoft, What am I doing wrong? I am relatively new to C# but as a test, I am trying to convert List to JSON but I get an empty JSON file. Can someone tell me what I am doing wrong?
I have a class Book
class Book
 {
    string _title { get; set; }
    string _author { get; set; }

    public Book() { }
    public Book(string title = "",
                string author = "")
    {
        _title = title;
        _author = author;
    }
    public override string ToString()
    {
        string info = $"Title: {_title} by {_author}";
        return info;
    }
}

And this is my main class
static void Main(string[] args)
    {
        string path = @"C:\Users\Zinox\Desktop\xml\";
        string xmlPath = path + "books.xml";
        string listJson = path + "Booklist.json";

        string openFile = File.ReadAllText(xmlPath);

        Book book = new Book();
        List<Book> booklist = new List<Book>();

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(openFile);

        XmlNode root = doc.DocumentElement;

        foreach (XmlNode b in root)
        {
            booklist.Add(new Book(
                    b.SelectSingleNode("title").InnerText,
                    b.SelectSingleNode("author").InnerText
                ));
        }

        string listData = JsonConvert.SerializeObject(booklist,
Newtonsoft.Json.Formatting.None);

        File.WriteAllText(listJson, listData);
    }
}

Ans this is the output I am getting.
[{},{},{},{},{},{},{},{},{},{},{},{}]

Thanks in advance.


text:
Q: Getting schema deserialisation error : Invalid default for field While running kafka consumer, i am getting following error:
Caused by: org.apache.kafka.common.errors.SerializationException: Error deserializing Avro message for id 13
Caused by: org.apache.avro.AvroTypeException: Invalid default for field key_id: "null" not a ["null",{"type":"string","avro.java.string":"String"}]
    at org.apache.avro.Schema.validateDefault(Schema.java:1512)
    at org.apache.avro.Schema.access$300(Schema.java:86)
    at org.apache.avro.Schema$Field.<init>(Schema.java:493

My avro schema is like this :
{ "name": "key_id", "type": [ "null", "string" ], "default": "null"},

I have tried multiple options to solve this problem, but it is still there.

A: You need to set "default": null, as opposed to "default":"null":
{ "name": "key_id", "type": [ "null", "string" ], "default": null},


text:
Q: Update wp_query every week What I'm trying to achieve: my homepage displays 3 random posts from each of 5 different categories. That part is easy.
What's a little unique and I can't quite figure out how to accomplish, I would like those posts to change automatically every week.
That way if the user comes back a couple times during the week, they see the same posts, but on a weekly basis the query should update to make it essentially look like a bunch of new content has been added (or at least previously written content is now featured).
How would I go about doing that? Thanks.

A: I see two approaches: via cron job... or website / page cache which lasts 1 week.
In case you want to do the cache option: you just need to add 'orderby'   => 'rand' to your WP_Query and install a caching plugin for your page, then set it up for 1 week.
CronJob: you need to setup a script which starts every week. For this you need to setup the cron job for your WordPress - https://www.siteground.com/tutorials/wordpress/real-cron-job/, then with the help of wp_schedule_event you can create a weekly task to update your posts.

A: A nice middle way between caching and cronjob is to use transients
You can write a little function that handles the setting and getting of transients.
$posts = get_transient( 'recent_posts' );
if ( false == $posts ) :
$posts = new WP_Query( array (
  'orderby' => 'rand',
  'fields' => 'ids'
));
set_transient( 'recent_posts', $posts, 60*60*12 );
endif;
return $posts;

In the transient you store the ids of the posts that you've called before in a WP_Query. You then set the expiry of the transient for a week and your function just checks if there is a transient already. If not, create a transient with your random posts ids.
The code isn't tested, it's merely an example of how it can be used. Let me know how it goes!


text:
Q: Is it possible to automatically locate a java RMI registry in the LAN? I'm not an expert in RMI at all, but I was wondering if there is any way to automatically detect a remote registry in the LAN. Why do I need this? I am programming a multiplayer game and I would like that when you start the game, it looks for an already running server. If the program doesn't find a rmiregistry in the LAN, it starts one itself. If another client starts the game within a LAN, he will find the rmiregistry of the player who already started the game. Is something like that possible? Thanks for any help.

A: The Jini Naming and Discovery Service is a (rather large) implementation of exactly this.

A: At the least, I think you'll have to specify an address and a port range to scan.
This project rmi registry monitor is a small application that is able to monitor a registry(using address and port) a list its contents. It is open source so you can browse the code and learn from it.


text:
Q: do i want rolling_apply? I have a data frame that has a number of subjects completing a number of trials (1:800) and I want to add a "block" column...  There are 80 trials per block.  I feel like rolling_apply could be the solution, but I can't seem to make it work.
I could do some sort of thing were every value of "trial" between two increments gets set at a certain block, but it seems like rolling_apply should do this.  I'd really like to do this, but it isn't possible:
grouped = df.groupby('sid')
df['block'] = pd.rolling_cumcount(grouped, 80)

There are 10 blocks and 800 trials...
blocks = range(10)
increments = range(800)[0::80]

I have this:
  SID  Trial
    1    0
    1    1
    1    2
    1    3
    1    4
    1    5
    2    0
    2    1
    2    2
    2    3
    2    4
    2    5

What I want to end up with is (only I have 10 blocks, with 80 trials each):
SID  Trial  Block
1    0      0
1    1      0
1    2      0
1    3      1
1    4      1
1    5      1
2    0      0
2    1      0
2    2      0
2    3      1
2    4      1
2    5      1

Thanks

I ended up just doing this, which probably isn't an optimal solution, but works fine:
# add a block to each subject
block = np.arange(1,11)
block_array = np.repeat(block, 80)
blocks_all = np.tile(block_array, df['sid'].nunique())
df['block'] = blocks_all

A: I'd use groupby's cumcount:
In [11]: g = df.groupby(['SID', 'Trial'])

In [12]: g.cumcount()
Out[12]:
0     0
1     0
2     0
3     1
4     1
5     1
6     0
7     0
8     0
9     1
10    1
11    1
dtype: int64

And just set this to the column:
In [13]: df['Block'] = df.groupby(['SID', 'Trial']).cumcount()


text:
Q: Remove repeated values from list I need to remove the repeated values from the list lista and put them in another list or in the same.
Distinct() doesn't work. listasemrepetidos returns the same as lista.
List<XYZr> lista = new List<XYZr>();
List<XYZr> listasemrepetidos = new List<XYZr>();
lista.Add(new XYZr(Convert.ToDouble(data[1].Replace('.', ',')), Convert.ToDouble(data[2].Replace('.', ',')), Convert.ToDouble(data[3].Replace('.', ',')), CLR));

 listasemrepetidos = lista.Distinct().ToList<XYZr>();


text:
Q: Why isnt the text showing up in pygame? I am trying to make a player counter to where if the player presses the up arrow on the keyboard i want players to go up by one and display the counter going up and the same with down. But the counter isn't showing
import pygame
pygame.init()
pygame.display.set_mode()
pygame.font.init()
Red = (247, 12, 12)
White = (255,255,255)
Blue = (0, 157, 255)
Black=(0,0,0)
X = 1400
Y = 1000
players = 0
display_surface = pygame.display.set_mode((X, Y))
font = pygame.font.Font('freesansbold.ttf', 20)
text = font.render("Player one is:", True, Black, White)
textRect = text.get_rect()
textRect.center = (X // 4.4, Y // 3.6)
str(players)
while True:
    display_surface.fill(White)
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); #sys.exit() if sys is imported
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_0:
                print("Hey, you pressed the key, '0'!")
            if event.key == pygame.K_1:
                print("Doing whatever")
            if event.key == pygame.K_UP:
                int(players)
                players = players+1
                str(players)
                text1 = font.render(players, True, Black, White)
                text1Rect = text1.get_rect()
                text1Rect.center = (X // 4.4, Y // 3)
                display_surface.blit(text, textRect)
                int(players)
pygame.display.update()

A: The str(x) converts x and returns a string:
str(players)
str(players)

However, you don't need it at all. You have to render the text after clearing the display and before updating the display. Initialize text1 before the application loop:
while True:
    # [...]

    # clear display
    display_surface.fill(White)

    # render secene
    display_surface.blit(text, textRect)
    display_surface.blit(text1, text1Rect)

    # [...]

    # update display
    pygame.display.update()

Change and rerender the text1 surface when UP is pressed:
if event.key == pygame.K_UP:
    players += 1
    text = font.render("Player one is: " + str(players), True, Black, White)
    textRect = text.get_rect(center = (X // 4.4, Y // 3))

Complete example:
import pygame
pygame.init()
pygame.font.init()
Red = (247, 12, 12)
White = (255,255,255)
Blue = (0, 157, 255)
Black=(0,0,0)
X = 1400
Y = 1000
players = 0
display_surface = pygame.display.set_mode((X, Y))
font = pygame.font.Font('freesansbold.ttf', 20)

text = font.render("Player one is:", True, Black, White)
textRect = text.get_rect(center = (X // 4.4, Y // 3.6))
text1 = font.render(str(players), True, Black, White)
text1Rect = text.get_rect(center = (X // 4.4, Y // 3))

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_0:
                print("Hey, you pressed the key, '0'!")
            if event.key == pygame.K_1:
                print("Doing whatever")
            if event.key == pygame.K_UP:
                players += 1
                text1 = font.render(str(players), True, Black, White)
                text1Rect = text.get_rect(center = (X // 4.4, Y // 3))

    display_surface.fill(White)
    display_surface.blit(text, textRect)
    display_surface.blit(text1, text1Rect)
    pygame.display.update()

pygame.quit()
exit()


text:
Q: Filling a layout dynamically crashes the application without errors When I try to open this new activity through a button on a previous layout the app crashes with no apparent reason.
My code is this :
public class Main3Activity extends AppCompatActivity {

private   int limitsImages[] = {R.drawable.onelimits, R.drawable.twolimits, R.drawable.threelimits, R.drawable.fourlimits, R.drawable.fivelimits, R.drawable.sixlimits,
        R.drawable.sevenlimits, R.drawable.eightlimits, R.drawable.ninelimits, R.drawable.tenlimits};

private   String answersLimits[] = {"-9", "2", "1/10", "1/6", "1/2", "12", "1", "2/3", "5/6", "1/4"};

private String choicesLimits[][] = {{"-19", "19", "-9", "2"},{"0", "-2", "Does not exist", "2"}, {"Does not exist","1/5","0","1/10"},{"1/6","1/5","1/4","1"}
,{"1","1/2","0","Does not exist"},{"0","4","12","10"},{"0","1","1/2","2/3"},{"2/3","1","3/2","0"},{"1","2/6","5/6","4"},{"1/4","1"
        ,"Does not exist","4"}};

private  TextView questionNum;
private  TextView questionTxt;
private  ImageView questionImage;
private  CheckBox choiceOne;
private  CheckBox choiceTwo;
private  CheckBox choiceThree;
private  CheckBox choiceFour;

private static int testIdentifier=0;

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

    questionNum = (TextView) findViewById(R.id.questionNumber);
    questionTxt = (TextView) findViewById(R.id.questionText);
    questionImage = (ImageView) findViewById(R.id.questionImage);
    choiceOne = (CheckBox) findViewById(R.id.choice1);
    choiceTwo = (CheckBox) findViewById(R.id.choice2);
    choiceThree = (CheckBox) findViewById(R.id.choice3);
    choiceFour = (CheckBox) findViewById(R.id.choice4);

    //choicesLimits[4][3]=getString(R.string.doesntexist);
    //choicesLimits[9][2]=getString(R.string.doesntexist);

    startLimitsQuestion(testIdentifier);

}

public void startLimitsQuestion( int questionNum) {
    this.questionNum.setText(questionNum+1+"/10");
    questionTxt.setText(getString(R.string.limitsQ));
    questionImage.setImageResource(limitsImages[questionNum]);
    choiceOne.setText(choicesLimits[questionNum][1]);
    choiceTwo.setText(choicesLimits[questionNum][2]);
    choiceThree.setText(choicesLimits[questionNum][3]);
    choiceFour.setText(choicesLimits[questionNum][4]);

}

Sub Question:I have been troubled a bit if my initialization and declaration before the onCreate() method is correct.
edit: Layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/colorPrimaryDark"
    tools:context="com.example.learnmath.Main2Activity"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button4"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/black"
        android:layout_marginTop="27dp"
        android:layout_below="@+id/textView3"
        android:layout_alignLeft="@+id/button5"
        android:layout_alignStart="@+id/button5"
        android:text="@string/quadratics" />

    <Button
        android:text="@string/derivatives"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button6"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/black"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="18dp"
        android:layout_marginEnd="18dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/timetostart"
        android:id="@+id/imageView"
        android:layout_alignTop="@+id/button4"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="22dp"
        android:layout_above="@+id/button6" />

    <Button
        android:text="@string/limits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button5"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/black"
        android:layout_marginTop="35dp"
        android:layout_below="@+id/button4"
        android:layout_alignLeft="@+id/button6"
        android:layout_alignStart="@+id/button6"
        android:elevation="0dp"
        android:onClick="limitsQuiz" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:srcCompat="@drawable/mathtest"
        android:id="@+id/imageView2"
        android:layout_marginRight="46dp"
        android:layout_marginEnd="46dp"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/button6"
        android:layout_alignEnd="@+id/button6" />

    <TextView
        android:text="@string/tests"
        android:typeface="monospace"
        android:textStyle="italic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/holo_orange_light"
        android:id="@+id/textView3"
        android:textSize="35sp"
        android:shadowColor="@android:color/background_light"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/imageView2"
        android:layout_alignStart="@+id/imageView2" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/index"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/imageView3"
        android:onClick="homePage" />

</RelativeLayout>

A: You said that you clicked and then it crashed. So some problem will be there in the onclick. We need to follow your code from onclick. The above snippet is just showing the first question display and these are correct except the test identifier is not incremented.
Please do post  full class code of that snippet. Also do give logcat error
What i could guess is some where the error should be in registering activity to manifest or error durimg onclick where your accessing arrays. May be arrayoutofbounds too.

A: I have resolved your problem. The app theme you declared in your AndroidManifest.xml is not appropriate. As you are extending the AppCompatActivity in your activity, you need to use the Appcompat theme for your particular activity or application.
Change your current app theme to android:theme="@style/Theme.AppCompat.Light" in AndroidManifest.xml file will resolve your problem.
Note:: Your initialisation and declaration is perfect and your onClick method is not the issue. This AppTheme is the only issue. Tell me if you didn't get me.

A: Use Firebase crash library to report Crash to detect crash if you are not able to crash in logcate
https://firebase.google.com/docs/crash/


text:
Q: Не выдается питание от USB OTG отладочных плат Discovery и nucleo Есть две платы: stm32f407 Discovery и stm32f767 Nucleo. У обоих есть 2 разъёма: 1 для прошивки через ST Link, второй USB OTG, для работы МК в качестве USB устройства. Проблема вот в чём, платы не берут питание непосредственно с USB OTG при подключении через провод к компу и, соответственно, не включаются. Для включения приходиться заводить питание другим способом. Всю инициализацию провожу в CubeMX. Дык вопрос вот в чём: у меня обе платы сломаные, я неправильно инициализацию в cubemx выполнил, если да, то на что надо обратить внимание, или же это норма, что питание нужно ещё каким-то "макаром" заводить?

A: Это особенность данных устройств. Они должны брать питание только от основного USB-разъёма, через который они прошиваются. Если объединить цепи питания этих двух USB-разъёмов, может возникнуть ошибка на хосте.
Вот фрагмент принципиальной схемы платы stm32f407 Discovery. Вот основной разъём USB программатора:

Вот разъём USB OTG:

Как видите, их цепи питания не совмещены. Это сделано потому, что нет OTG предполагает функционирование платы как в режиме USB Device, где оно получает питание от внешнего устройства, так и USB Host, в котором сама плата Discovery должна выдавать напряжение для подключения устройств USB.


text:
Q: intuitive set theory / empty set intersection question Let's say A=empty set and every element of A also a set, what is the intersection of all elements of A?
real answer:?
possible answer: universal set (I found it via using  Russel paradox. And then I thought backward.)

A: Every element of the empty set is a set, no need to assume that. But the intersection of the elements of the empty set is undefined; the definition of intersections applies only to non-empty families of sets.
(Why is it undefined? If we try to apply the definition, with $I$ being the intersection of the elements of the empty set, we get $$x\in I\iff\forall y\in \emptyset\,\,\,\, x\in y.$$But that says that every $x$ is in $I$, and there is no "universal set" in modern set theory)

A: Proof of $\forall i, X_i\subseteq X$, then
$\bigcap_{i\in\emptyset}X_i=X$ is like this. However, to avoid Russell's paradox, it must first be implicitly assumed that all actions take place under a particular set(in this case, $X$).
For all $x\in X$, $i\in\emptyset \Rightarrow\bigcap_{i\in\emptyset} x\in X_i$ holds, because it is vacuous truth, since antecedent $i\in\emptyset$ is false.


text:
Q: watchOS Complication – reload more than daily budget? I am developing a watchOS Complication with type graphicRectangular. Something like the apple activity or heart rate complication. These updates often and display some graph data.
My graph works – showing calendar events in timeline.
I cannot update it "every minute". That would be nice to set a marker for the actual time (check screenshot) in the timeline graph. But that idea is mostly gone since I can only force to update the timeline 50 times a day (as I have read). Apple just says

If your complication has already exceeded its allotted daily budget
  for execution time, calls to this method do nothing.

So there is nothing I can do, right? Not even when my goal is not submitting it to the AppStore and getting it reviewed?

Now I have developed a function that checks if the text needs to get updated (in screenshot above 13:00 Lorem Ipsum) or the graph has changed and if so triggering the reloadTimeline() method. So not just reloading it every time but only when necessary. But how should I call this function? I've tried in background Task but that only check "when it wants" – I also build a repeatable 30 sec Timer in ExtensionDelegate. That also works – but seems only to work when XCode runs the app – If I stop in XCode then the graph nearly gets only updated every 15 minutes or something (background Task maybe).
Also I have included EventKit observer for storeChanged(). So I can reload the graph if something changed in calendar. That also work well and quote fast when running the app with XCode active. Stopping the app and using it on the watch "outside XCode" seems to have a heavy delay – sometimes it do never work.
When opening the app (tap on complication) the storeChanged() event gets triggered immediately (I think it is this function – I can't really debug that since connected to XCode every works well super fast) and after closing the app the complication is refreshed.

Is there a reason why the storeChanged() event get triggered super fast then running via XCode but is extremely laggy / slow / only triggering when opening the app when not running via XCode?
Is there a reason why my Timer do not run when not running through XCode? When running with XCode I can see debug prints in console from these timed 30 sec "checks". But these seems nothing to do when running outside XCode. Just rarely updating the complication.

Another example: This morning when I put on my watch the graph from yesterday was still visible. So background Task or Timer did not work over night. When opening the app (tap complication) then the graph get refreshed immediately.

Where is the correct place for the EventKit observer or the Timer?
ExtensionDelegate or ComplicationController?

A: The reason everything runs fast in Xcode is that when the App is attached to the Debugger the system won't stop executing the background queues. So having an App attached to the debugger will keep all your background queues alive.
The timer runs on the main queue. The main queue is running all the time when the app is attached to the Xcode debugger. When running your app without the debugger the main queue gets suspended when the app enters the background.
To refresh your complication as often as possible you can:

*

*Use the complication controller datasource

*Background task handler

*Refresh you complications 50 times a day (you can trigger this from the iOS App too using the WatchConnectivity framework)

*If your app matches an use case for extended runtime sessions you can try them too

Sadly you can't do more than this. When your complication exceeds Apples limits it won't be refreshed anymore. So it might be better to refresh it every 30 min or something.

A: I used getTimelineEndDate() and getTimelineEntries(for: after date:) to produce all the other planned complications "views" at initial/refresh time. So I do not need to refresh the complication just to change the "planned content".
I just need to refresh it to fetch changes from EventKit.


text:
Q: Validar ancho imagen inputfile file-input bootstrap Estimados tengo el siguiente problema, estoy usando el plugin File-Input para cargar archivos a mi sistema. En este caso lo estoy usando para cargar imagenes las cuales proceso posteriomente mediante PHP. Mi duda es como puedo restringir un ancho minimo de imagenes a cargar. Para mi sistema mi resolucion ideal es de 1200x675, quiero que el input no me permita cargar imagenes con un ancho menor al ideal, pero no logro dar con el resultado usando dicho plugin.

$("#imagenes").fileinput({
  language: 'es',
  previewFileType: "image",
  browseClass: "btn btn-success",
  browseLabel: "Elegir Imagen",
  browseIcon: " ",
  removeClass: "btn btn-danger",
  removeLabel: "Eliminar",
  removeIcon: " ",
  showUpload: false,
  dropZoneTitle: 'Arrastre aquí las imagenes a subir',
  maxFileSize: 200,
  maxFileCount: 5,
  showDelete: true,
  showRemove: true
});

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

  <input type="file" accept=".jpg,.jpeg" name="imagenes[]" id="imagenes" multiple>

A: Supuestamente según su documentación se logra agregando las opciones:
maxImageWidth: 250,
maxImageHeight: 250

Pero al probarlo en firefox no me funcionó, por lo que ya levaté el issue, en cuanto lo corrijan ya debería de funcionar.

$("#imagenes").fileinput({
  language: 'es',
  previewFileType: "image",
  browseClass: "btn btn-success",
  browseLabel: "Elegir Imagen",
  browseIcon: " ",
  removeClass: "btn btn-danger",
  removeLabel: "Eliminar",
  removeIcon: " ",
  showUpload: false,
  dropZoneTitle: 'Arrastre aquí las imagenes a subir',
  showPreview: true,
  maxFileCount: 5,
  //  maxFileSize: 200,
  showDelete: true,
  showRemove: true,
  maxImageWidth: 5,
  maxImageHeight: 5
});

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

  <input type="file" accept=".jpg,.jpeg" name="imagenes[]" id="imagenes" multiple>


text:
Q: HQL select vs delete. Why delete with cross join doesn't work? Why this is working:
@Query("from Ban b where b.banned.uuid = :uuid")

but this cause SQL syntax error:
@Query("delete Ban b where b.banned.uuid = :uuid")

Error message is: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'cross join user user1_ where uuid=x'53......'' at line 1

A: Neither HQL nor, usually—at least as far as I know—SQL, supports joins in delete statements. However, you can emulate it with a subquery, something like:
delete Ban b where b.bannedid = (select bb.id from Banned bb where bb.uuid = :uuid)


text:
Q: performing an segue doesn't works I want to the app to segue if the codes matches with the defined code inside .
So if I enter the code in the textfield nothing happens .
Do any of you maybe have some solutions for me ?
that is what I've got so far in the .m file of the ViewController
    @interface mainViewController ()
@property (weak, nonatomic) IBOutlet UITextField *zahlencode;
@property (weak, nonatomic) IBOutlet UIButton *done;
@property NSMutableArray *codes;

@end

@implementation mainViewController
- (void)loadInitialData {
    Code *item1 = [[Code alloc] init];
    item1.Code = @"1";
    [self.codes addObject:item1];
}
int a,b,c,zz;
a=1;
b=2;
c=3;

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if (sender != self.done)
        return;
    if (self.zahlencode.text.length > 0)
    {
        zz =[self.zahlencode.text intValue];
        if(zz == a)
        {

            [self performSegueWithIdentifier:@"1"];        }
    }
}

A: Do you have a segue in your storyboard with the identifier "1"?
If not then add it to the segue.
Does your code reach the performSegueWithIdentifier (did you do a NSLog() to ensure that the code is executed)?
UPDATE:
You should try this:
Add an action from your UIButton and inside that you write the code to perform the segue.
(Add the action from the storyboard, like an outlet)
- (void) ButtonPressed: (id) sender
{
    if (sender != self.done)
        return;
    if (self.zahlencode.text.length > 0)
    {
        zz =[self.zahlencode.text intValue];
        if(zz == a)
        {

            [self performSegueWithIdentifier:@"1" sender:self];
        }
    }
}


text:
Q: Spark job location in kubernetes cluster - No such file error I am trying to submit the Spark application to Kubernetes cluster, the job file is at : /opt/spark/applications/ path, submitting spark using below command:
${SPARK_PATH}/bin/spark-submit \
--master <K8S_MASTER> \
--deploy-mode cluster \
--name spark-py-driver \
--conf spark.executor.instances=5 \
--conf spark.kubernetes.container.image=spark-py:2.4.0-rc3 \
--conf spark.kubernetes.driver.pod.name=spark-py-driver \
--conf spark.executor.memory=2g \
--conf spark.driver.memory=2g \
local:///opt/spark/applications/spark_submit_test_job.py

Am getting 'No such file or directory' error, though the job file is there at the path on the node.
python: can't open file '/opt/spark/applications/spark_submit_test_job.py': [Errno 2] No such file or directory

A: As the instruction on spark running on Kubernetes states:

Finally, notice that in the above example we specify a jar with a specific URI with a scheme of local://. This URI is the location of the example jar that is already in the Docker image.

You need to create a correct Dockerfile with the script already present in the image.
A better solution would be using a repository that can be loaded when you are running the image, or instead you can use Remote Dependencies


text:
Q: Hosting images on Lambda + API gateway I got NodeJS application running on AWS Lambda + API gateway environment.
I am deploying my app via serverless app (https://www.npmjs.com/package/serverless). My assets (including images) are packed together to zip format, sent to S3 storage and deployed via cloudfront (regular serverless flow).
Requests to images responses with 200 OK status. The problem is that they are not displaying. I have no idea where should I start to look for an issue.
I enabled binary media types in my API Gateway, and provided following types: image/gif, image/jpeg.
For example I am trying to display this image:
http://www.top13.net/wp-content/uploads/2015/10/perfectly-timed-funny-cat-pictures-5.jpg
Here is URL to it in my app:
http://angular-universal-serverless.maciejtreder.com/assets/img/cat.jpg
Is it even possible to display images this way? Maybe I should upload them to S3 storage?
Here are some entries from logs (before enabling binary media types):
http://www.heypasteit.com/clip/0IILRO
and after enabling:
http://www.heypasteit.com/clip/0IILS2

A: I have solved problem, by my own.
Here is boilerplate repository: https://github.com/maciejtreder/angular-universal-serverless
The point was to encode files on Lambda side, and send it in encoded form to API GW with proper headers.

A: I had this problem on Angular 12.0.5 using regular angular-universal (ng add @nguniversal/express-engine), serverless and @vendia/serverless-express.
The solution was:
1 - Add the media types in the API Gateway:

2 - Add apiGateway.binaryMediaTypes on my serverless.yml file:
provider:
  ...
  apiGateway:
    binaryMediaTypes:
      - '*/*'


text:
Q: Haskell -- get TypeRep from concrete type instance I want to write a function with this type signature:
getTypeRep :: Typeable a => t a -> TypeRep

where the TypeRep will be the type representation for a, not for t a. That is, the compiler should automatically return the correct type representation at any call sites [to getTypeRep], which will have concrete types for a.
To add some context, I want to create a "Dynamic type" data type, with the twist that it will remember the top-level type, but not its parameter. For example, I want to turn MyClass a into Dynamic MyClass, and the above function will be used to create instances of Dynamic MyClass that store a representation of the type parameter a.

A: Well, how about using scoped type variables to select the inner component:
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Data.Dynamic
import Data.Typeable

getTypeRep :: forall t a . Typeable a => t a -> TypeRep
getTypeRep _ = typeOf (undefined :: a)

Works for me:
*Main> getTypeRep (Just ())
()
*Main> getTypeRep (Just 7)
Integer
*Main> getTypeRep ([True])
Bool

Interesting design.

A: On a tangential note to Don's solution, notice that code rarely require ScopedTypeVariables.  It just makes the solution cleaner (but less portable).  The solution without scoped types is:
{-# LANGUAGE ExplicitForAll #-}
import Data.Typeable

helper :: t a -> a
helper _ = undefined

getTypeRep :: forall t a. Typeable a => t a -> TypeRep
getTypeRep = typeOf . helper

A: This function (now) exists in Data.Typeable typeRep


text:
Q: WebBrowser control: Navigation to the webpage was canceled Setup

*

*Windows 8 (full) tablet

*.NET 2.0 application

I'm working on a project in which 4 WebBrowser controls are navigating to some webpage simultaneously when the application is loaded. The webpages have the same HTML, but are coming from different web servers.
The problem is that some of those pages display a "Navigation to the webpage was canceled" message in the WebBrowser control. This only happens when the application starts. I have implemented the solution described here to get the status code returned and weirdly enough, it is a 200 = OK status.
When I then refresh the page, it suddenly works correctly. I have suspicions that the problem might be caused by the simultaneous navigations, but I have no idea how I could verify that.
Any ideas?

A: Alright, so I ended up firing a navigation and waiting for it to complete before doing the next one and I haven't encountered the problem since. It was a problem that didn't need a fancy solution, and we didn't have time to dig deeper, so we went with that.

A: A case of Facebook Login using OAuth:
It worked for me navigating from WPF WebBrowser to:
https://graph.facebook.com/oauth/authorize?client_id=zzzzzzzzzzzzzzzz&redirect_uri=https://www.facebook.com/connect/login_success.html&type=user_agent&display=popup

Than something changed and I get: Navigation to the webpage was cancelled
From Chrome I can see the reason:
{
   "error": {
      "message": "Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.",
      "type": "OAuthException",
      "code": 191,
      "fbtrace_id": "GuhAfeO/85U"
   }
}

Why happened?
The link above works only for empty "Valid OAuth Redirect URIs". When a URL was added to support a website login, the app stopped working.
I went to my settings and removed the url. Works now!
https://developers.facebook.com/apps/zzzzzzzzzzzzzz/fb-login/settings/


text:
Q: Only update MySQL row if columns equal I am running this script with PDO:
UPDATE orders SET status=:status WHERE id=:id AND depot=:depot;

I want it to only update if status = "Open" - so if status is anything but open, I don't want it to update.
How can I do that?

A: If you want to update orders when status is Open
UPDATE orders SET status=:status WHERE id=:id AND depot=:depot AND status='Open';

If you want to update orders when status is not Open
UPDATE orders SET status=:status WHERE id=:id AND depot=:depot AND status!='Open';

Hope this works for you!!


text:
Q: VBA Excel : Compile Error when using .activate on a sheet I encounter the following error within my Excel macro when I tried to execute it :
Compilation Error : Function or Variable expected.
Here is my code :
            'On split le libellé afin de récupérer la chaîne de caractère source1 à rechercher dans la colonne B du PSR
            TabSrcDoubleEntree = Split(PtoutPar(j).Nom, "/")
            ' on récupère la ligne du PSR (colonne B) dans laquelle la chaîne source 1 (=TabSrcDoubleEntree(0)) est renseignée
            Set sheet = Workbooks(PFile).Sheets(ParMap(j).Parametrage.SrcFeuille)
            **With sheet.Activate**
                Set celluleRowRange = .Range("B", .Range("B").End(xlUp))
                Set celluleFind = celluleRowRange.Find(TabSrcDoubleEntree(0), LookIn:=xlValues, lookat:=xlWhole)
                celluleRowFind = celluleFind.Row
            End With
            'on initialise la ligne à partir de laquelle on fait la recherche à "c.Row"
            ThisWorkbook.Sheets(PFeuilleDest).Cells(iDest, ParMap(j).Parametrage.DestCol).Value = Workbooks(PFile).Sheets(ParMap(j).Parametrage.SrcFeuille).Cells(celluleFind.Row + ParMap(j).Parametrage.SrcPremiereLigne, ParMap(j).Parametrage.SrcCol).Value

=> Does anyone know why the instruction sheet.Activate is not correct ??
THanks a lot
Simon

A: The With "this" statement is used to perform the following block from the context of "this". In your case you are performing the block from the context of the Activate function, rather than the sheet itself, which is throwing a compile error. I would recommend changing it to the following
' Perform the following from the context of sheet
With sheet
    .Activate
    Set celluleRowRange = .Range("B", .Range("B").End(xlUp))
    ' ...
End With


text:
Q: How to enable AG in vim + fzf I am new to vim. I read online that one of the best fuzzy finder in vim is fzf. I have started using it. But whenever I write the command :Ag I get ag is not found. I don't know what it means and I don't know how to fix it.

A: To have a preview window for the file under cursor during search, you can add below to the .vimrc or init.vim
command! -bang -nargs=* Ag
  \ call fzf#vim#grep(
  \   'ag --column --numbers --noheading --color --smart-case '.shellescape(<q-args>), 1,
  \   fzf#vim#with_preview(), <bang>0)

Then use :Ag mySearchTerm to see the result with a preview on the right side.
You can also map ctrl-g to it for convenience:

map <C-g> :Ag

A: You need to install ag, in case you are on a mac:
brew install the_silver_searcher

As another option for testing fzf you could also use ctrl p to call :Files by using this map:
nnoremap <c-p> :Files<CR>

And you could  use ripgrep when calling :Files, for this you will need to modify the default FZF_DEFAULT_COMMAND:
export FZF_DEFAULT_COMMAND='rg --files --no-ignore --hidden --follow --glob "!.git/*"'

You can find more information here: https://github.com/junegunn/fzf#usage

A: *

*By default, fzf uses the system's "find" command. You can change that by altering the env variable $FZF_DEFAULT_COMMAND to a third-party utility. The advantage to using these tools is that they observe ignore files. Using silver searcher (i.e. ag), you're default command would look something like the following:
$echo $FZF_DEFAULT_COMMAND
ag -l --path-to-ignore ~/.ignore --nocolor --hidden -g ""
Regardless of the FZF command used, at the shell you're gathering up file   names that match your criteria.

*FZF+Vim, an extra plugin in addition to fzf, provides an :Ag command to use in (g)vim. The :Ag command lets you search the contents of files, opposed to its :Files command, which only searches file names.
There is some .vimrc customization one might want when using FZF+Vim. For example, the tweak I like is the option to run :Ag with a full screen search and preview window (use :Ag! instead of :Ag):
command! -bang -nargs=* Ag
\ call fzf#vim#ag(<q-args>,
\                 <bang>0 ? fzf#vim#with_preview('up:60%')
\                         : fzf#vim#with_preview('right:50%:hidden', '?'),
\                 <bang>0)


text:
Q: Doctrine2 and database-side triggers for denormalized fields Let's say I have two tables: Category and Product, and Product links to Category with a foreign key Production.categoryId == Category.id. I would like my database server to take care of counting number of products within a category using a denormalized field Category.productCount - the triggers will update this count on any update/delete/insert, so I don't have to worry about it. Is there a way to synchronize database-side triggers with Doctrine2 entities somehow? I really don't want to recalculate those counters on PHP side, as we are going to run it on multiple servers.

A: If I understand the question you want to be able to add a new product to a category, persist it then have Category.productCount update itself from the database?  You can use
$entityManager->refresh($category);

To reload an entity from the database.  I have not done it myself but I would expect that you could use the life cycle functionality to automate this.
But I do kind of wonder if it might not be better to just increment the counter locally without persisting it to the database.  Let your trigger do the database operation but, within the request, update the count locally.


text:
Q: Vue.js v-if conditional not properly work in v-for loop. Why? This is stupid question, but i am still beating on it a few hours..
Simple Repro:
 **https://codepen.io/sergio1c/pen/eYZRQJW**

Could anyone answer to me, why the text 'Step_2 text' is shown when the particaular conditional on template level is false? What am missing?
Thanks in advance...

A: It because I've wrote not right logic in my conditional expression. In this case it have to be as: n == step && step == 1 where 1 is current step on form (stepper)


text:
Q: The set of measurable rectangles is an algebra I'm reading section 7.1 The Product Measure Theorem from this lecture note.

Problem 7.1.1. Let $(X, \mathcal{A})$ and $(Y, \mathcal{B})$ be measurable spaces. Is there a natural way to define a measure on the space $X \times Y$ which reflects the structure of the original measure space?
Definition 7.1.2. Let $(X, \mathcal{A})$ and $(Y, \mathcal{B})$ be measurable spaces. A measurable rectangle is a set of the form $A \times B$, where $A \in \mathcal{A}$ and $B \in \mathcal{B}$. Let $Z=X \times Y$ and
$$
\mathcal{Z}_0=\left\{\coprod_{i=1}^n A_i \times B_i \mid A_i \in \mathcal{A}, B_i \in \mathcal{B}\right\}.
$$
Lemma 7.1.3. $\mathcal{Z}_0$ is an algebra in $\mathcal{P}(Z)$.

My understanding It seems from this answer that $\mathcal{Z}_0$ is not generally an algebra and thus Lemma 7.1.3. is not correct. That's why the construction of product measure is usually not by Hahn–Kolmogorov theorem.

Could you confirm if my understanding is fine?

Update Below is a direct construction of product measure I have found.
Theorem 7.9 (Product measure) Let $\left(\Omega_1, \mathcal{F}_1, \mu_1\right)$ and $\left(\Omega_2, \mathcal{F}_2, \mu_2\right)$ be two measurable spaces where $\mu_1$ and $\mu_2$ are $\sigma$-finite measures. There exists a unique measure $\mu$ on $\left(\Omega_1 \times \Omega_2, \mathcal{F}_1 \otimes \mathcal{F}_2\right)$ that satisfies $\mu\left(A_1 \times\right.$ $\left.A_2\right)=\mu_1\left(A_1\right) \mu_2\left(A_2\right)$ for all $A_1 \in \mathcal{F}_1$ and $A_2 \in \mathcal{F}_2$. This measure is called the product measure, written as $\mu=\mu_1 \times \mu_2$.
Proof

*

*Uniqueness:

First we show that any such measure must be $\sigma$-finite. Since $\mu_1$ and $\mu_2$ are $\sigma$-finite there exist $\left\{A_n\right\}_{n=1}^{\infty} \in \mathcal{F}_1$ and $\left\{B_n\right\}_{n=1}^{\infty} \in F_2$ such that $\bigcup_{n=1}^{\infty} A_n=\Omega_1, \bigcup_{n=1}^{\infty} B_n=\Omega_2, \mu_1\left(A_n\right)$ and $\mu_2\left(B_n\right)$ are finite for all $n$. Consider $\bigcup_{(i, j) \in \mathbb{N}^2} A_i \times B_j$. For and $\left(\omega_1, \omega_2\right) \in \Omega_1 \times \Omega_2$ there exists $i, j$ such that $\omega_1 \in A_i$ and $\omega_2 \in B_j$, which means $\left(\omega_1, \omega_2\right) \in A_i \times b_j$. Hence $\bigcup_{(i, j) \in \mathbb{N}^2} A_i \times B_j=\Omega_1 \times \Omega_2$. For any $(i, j) \in \mathbb{N}^2$ we have $\mu\left(A_i \times B_j\right)=$ $\mu_1\left(A_i\right) \mu_2\left(B_j\right)<\infty$. Since $\mathbb{N}^2$ is a countable set we can conclude that $\mu$ is $\sigma$-finite.
Suppose there are two measures $\mu$ and $\mu^{\prime}$ satisfying the condition in the theorem. Recall that the collection of measurable rectangles $\left\{A_1 \times A_2: A_1 \in \mathcal{F}_1, A_2 \in \mathcal{F}_2\right\}$ is a $\pi$-system. $\mu$ and $\mu^{\prime}$ are both $\sigma$-finite and agree on this $\pi$-system. By Uniqueness theorem they agree on the generated $\sigma$-field $\mathcal{F}_1 \otimes \mathcal{F}_2$, i.e., $\mu=\mu^{\prime}$, which means such measure must be unique.

*Existence:

For any $B \in \mathcal{F}_1 \otimes \mathcal{F}_2$ let $\mu(B)=\int_{\Omega_1} \mu_2\left(B_{\omega_1}\right) d \mu_1\left(\omega_1\right)$ where $B_{\omega_1}=\left\{\omega_2 \in \Omega_2:\left(\omega_1, \omega_2\right) \in \Omega_1 \times \Omega_2\right\}$ as introduced previously. Then $\mu$ is a measure.
For any $A_1 \in \mathcal{F}_1, A_2 \in \mathcal{F}_2$,
$$
\mu\left(A_1 \times A_2\right)=\int_{\Omega_1} \mu_2\left(\left(A_1 \times A_2\right)_{\omega_1}\right) d \mu_1\left(\omega_1\right)=\int_{\Omega_1} \mathbb{1}_{A_1} \mu_2\left(A_2\right) d \mu_1\left(\omega_1\right)=\mu_2\left(A_2\right) \int_{\Omega_1} \mathbb{1}_{A_1} d \mu_1\left(\omega_1\right)=\mu_1\left(A_1\right) \mu_2\left(A_2\right)
$$
Hence such measure exists.

A: @Snoop It seems from Theorem 7.1.4 that $\coprod_{i=1}^n A_i \times B_i$ in Definition 7.1.2. means $\bigcup_{i=1}^n A_i \times B_i$. Then my above understanding is not correct.

Theorem 7.1.4 [Product Measure Theorem]. Let $(X, \mathcal{A}, \mu)$ and $(Y, \mathcal{B}, \lambda)$ be measure spaces. Then there exists a measure $\pi$ on $(X \times Y, \mathcal{A} \times \mathcal{B})$ such that $\pi(A \times B)=\mu(A) \lambda(B)$. Moreover, if $\mu$ and $\lambda$ are $\sigma$-finite, then $\pi$ is unique and $\sigma$-finite.
In the case where $\mu$ and $\lambda$ are $\sigma$-finite, we denote the uniquely obtained measure by
$$
\pi=\mu \times \lambda
$$
and call the measure the product of $\mu$ and $\lambda$.
Proof. Suppose that $A \times B$ can be written as $\sum_{i=1}^{\infty} A_i \times B_i$, where each of the measurable rectangles $A_i \times B_i$ are disjoint. Then
$$
\chi_A(x) \chi_B(y)=\chi_{A \times B}(x, y)=\sum_{i=1}^{\infty} \chi_{A_i}(x) \chi_{B_i}(y)
$$
for all $x \in X$ and $y \in Y$. Fix $x$ and integrate with respect to $\lambda$. By MCT,
$$
\begin{aligned}
\int_Y \chi_{A \times B}(x, y) d \lambda(y) & =\int_Y \sum_{i=1}^{\infty} \chi_{A_i}(x) \chi_{B_i}(y) d \lambda(y) \\
\int_Y \chi_A(x) \chi_B(y) d \lambda(y) & =\sum_{i=1}^{\infty} \chi_{A_i}(x) \int_Y \chi_{B_i}(y) d \lambda(y) \\
\chi_A(x) \lambda(B) & =\sum_{i=1}^{\infty} \chi_{A_i}(x) \lambda\left(B_i\right)
\end{aligned}
$$
Further integrating with respect to $\mu$ yields (again by MCT)
$$
\mu(A) \lambda(B)=\sum_{i=1}^{\infty} \mu\left(A_i\right) \lambda\left(B_i\right) \quad(*).
$$
Define $\pi_0$ on $\mathcal{Z}_0$ by $\pi_0\left(\cup_{i=1}^n A_i \times B_i\right)=\sum_{i=1}^n \mu\left(A_i\right) \lambda\left(B_i\right)$. Then $\pi_0$ is a measure on $\mathcal{Z}$ by $(*)$ (the only nontrivial issue to check was countable additivity). Caratheodory's Extension Theorem gives us a measure $\pi$ defined on at least $\mathcal{Z}$ that extends $\pi_0$. If $\mu$ and $\lambda$ are $\sigma$-finite, then $\pi_0$ is $\sigma$-finite, so Hahn's Extension Theorem tells us that $\pi$ is unique.


text:
Q: How to fix stripe payment in flutter i have the issue on flutter_stripe_payment i am getting this error MissingPluginException (MissingPluginException(No implementation found for method setPublishableKey on channel stripe_payment))

*

*i have trid on MainActivity extend from FlutterActivity to FlutterFragmentActivity.

*i changing from minSdkVersion 16 to minSdkVersion 21 inside build.gradle in android > app

*i added ext.kotlin_version = '1.2.71' inside build.gradle in Android folder

    import 'package:app/UiHelper/AppBarHelper.dart';
    import 'package:app/UiHelper/ColorHelper.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:stripe_payment/stripe_payment.dart';

    class MenuBookingScreen extends StatelessWidget {
       @override
       Widget build(BuildContext context) {
        return DrawWidget();
      }
    }

    class _ViewState extends State<DrawWidget> {
      @override
      void initState() {
        super.initState();
        initAction();
        // this part throw error while hot reload
        StripeSource.setPublishableKey("mykey");
      }

      initAction() async {}

      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBarHelper().appBarGenerator(context),
            backgroundColor: ColorHelper().appBackground,
            body: Material(
                color: ColorHelper().appBody, child: uIDomElement(context)));
      }

      Widget uIDomElement(BuildContext context) {
        var _size = MediaQuery.of(context).size;
        return Container(
          width: _size.width,
          child: RaisedButton(
            color: Colors.indigo,
            textColor: Colors.white,
            disabledColor: Colors.grey,
            disabledTextColor: Colors.black,
            padding: EdgeInsets.all(13),
            splashColor: Colors.blueAccent,
            shape: RoundedRectangleBorder(borderRadius:BorderRadius.circular(5.0)),
            onPressed: () {
              // Add Card
            },
            child: Row(
              children: <Widget>[
                Icon(Icons.credit_card),
                SizedBox(
                  width: 15,
                ),
                Text("Add Card")
              ],
            ),
          ),
        );
      }
    }

    class DrawWidget extends StatefulWidget {
      @override
      _ViewState createState() => _ViewState();
    }

A: Probably too late, but in case someone else bumps into this problem. 'flutter clean' did the trick for me..

A: Your Error Clearly tells that,
MissingPluginException (MissingPluginException(No implementation found for method setPublishableKey on channel stripe_payment).
Which means "flutter_stripe_payment" package don't have the "setPublishableKey" method. Please try to update / downgrade the version, It may help you.

A: Update the minimum SDK version to 19.
Additionally, make sure that you are using AndroidX - if not, then migrate to AndroidX first.


text:
Q: Getting the value from Swift class to Objective-C class I'm to use Swift class in my Objective-C Application. And I successfully integrate the swift class in my app and I can access the class also, But Swift class didn't return a value
Am using this library
https://github.com/ytakzk/Fusuma
the problem while selecting image from the gallery it should return the image but it didn't
here is a code :
   @IBAction func doneButtonPressed(sender: UIButton) {

    let view = albumView.imageCropView

    UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0)
    let context = UIGraphicsGetCurrentContext()
    CGContextTranslateCTM(context, -albumView.imageCropView.contentOffset.x, -albumView.imageCropView.contentOffset.y)
    view.layer.renderInContext(context!)
    let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    print(image)

    delegate?.fusumaImageSelected(image)
    self.dismissViewControllerAnimated(true, completion: {
    self.delegate?.fusumaDismissedWithImage?(image)
    })
}

The same code is working good in Swift application.

A: Ok Then lets first explain why its not working with Objective-C and its only working with Swift, the issue is the framework is build to be compatible with Swift only and not so far for Objective-C use, meaning the delegate is not exposed in the headers of the framework for Objective-C for example.
There is a work around for your app lets start with adding the library as a pod, set the Swift Language to 4.1 in Build settings (for the framework), using Xcode 9.4.1:
use_frameworks!
pod 'Fusuma', :git => 'https://github.com/ytakzk/Fusuma.git', :branch => 'master'

Now Create a Swift file called FusumaExtention.swift and add the following code in it, Note that if its the first time you are adding a Swift file it will ask you to Create a header in Xcode then Say YES, the ViewController is your Objective-C class:
import UIKit
import Fusuma

extension ViewController:FusumaDelegate {

    public func fusumaImageSelected(_ image: UIImage, source: FusumaMode) {
        // pass the selected image to your view controller method
        self.fusumaImageSelected(image)

    }

    public func fusumaMultipleImageSelected(_ images: [UIImage], source: FusumaMode) {

    }

    public func fusumaVideoCompleted(withFileURL fileURL: URL) {

    }

    public func fusumaCameraRollUnauthorized() {

    }

    func setDelegateToSelf(FusumaVC:FusumaViewController){

        FusumaVC.delegate = self

    }

}

Now you may find a complier error to say that it cant find the ViewController which is your Objective-C class, you will need to import it into the ProjectName-Bridging-Header.h file as the following :
#import "ViewController.h"

Now Finally we can go back to the Objective-C class "ViewController.h" and import the following lines:
#import <Fusuma/Fusuma-Swift.h>
#import <Fusuma/Fusuma-umbrella.h>

Then add the following method inside the interface as the following, this method will be called when the image is selected:
@interface ViewController : UIViewController

-(void)fusumaImageSelected:(UIImage *)image;

@end

Now go back to your ViewController.m and import the following line which makes the extension that we created earlier available to objective-c to be able to set the delegate for fusuma:
#import <ProjectName-Swift.h>

Then lets say you use the following method to present from your Objective-C Class:
- (IBAction)showController:(id)sender {

    FusumaViewController *fusuma = [[FusumaViewController alloc] init];
    [self setDelegateToSelfWithFusumaVC:fusuma];
    [self presentViewController:fusuma animated:true completion:nil];

}

Then implement the function that we defined in the header class below it, this method will be called after the image is selected :
-(void)fusumaImageSelected:(UIImage *)image{

    // do what ever you want with selected image.

}

This should work, its already tested.
Sample project


text:
Q: How to extract all integers from a string and store them in an int array in java I want to take a string and isolate all integer numbers in it then store them up in an array.
The input string will only ever contain letters a-z(both upper and lower case), digits 0-9 and "-" (read as minus sign).
So far I've written:
String str = readString();

String[] arr = str.split("[^0-9-]+");

if my input string is for example "15abc-59abc31abc100" the code above works fine and I just need to convert each element from the string array into int, however if my input string has no letters between the numbers to seperate them it won't work properly. example: abc59-12abc56-10abc10 will produce an array that only has 3 elements: 59-12, 56-10, 10 how do I make it recognize the minus sign as a start of a new element in the array without losing the sign itself?
Ideally I want the input "abc59-12abc56-10abc10" to look like this after the split:
String[] arr = {"59","-12","56","-10","10");

readString(); method will always provide the type of string I described above btw.

A: What you really want here is that - is a valid 'number symbol', but only at the start of any given number block.
However, by attempting to match the negative space in between them, you've made it hard on yourself: That is tricky to put in terms of regexes.
But, had you gone the positive route (write a regexp that describes a number), that'd be trivial: Pattern.compile("-?\\d+") describes it perfectly: An optional minus sign followed by 1 or more digits. Simple enough. That'll even 'work' if your input is "aa----5", which has one matching sequence (-5).
So.. do that, then. You're abusing split here. Don't abuse systems, it tends to go badly once you make things even a tiny little bit more complicated.
private static final Pattern NUMBER = Pattern.compile("-?\\d+");

public List<Integer> getNumbers(String in) {
  Matcher m = NUMBER.matcher(in);
  var out = new ArrayList<Integer>();
  while (m.find()) out.add(Integer.parseInt(m.group(0)));
  return out;
}

A few tricks are being used here:

*

*m.find() finds the next subsequence in the input string that matches the provided regexp.

*Regexps are 'greedy' by default. meaning, the string "1234" can be interpreted equally legally in many ways: Is that a single item (1234)? Is that Just the '1' also matches "-?\d+", after all. "Greedy" means that regexpes will match the longest sequence they can. Which is exactly what you want, no doubt.

*m.group(0) gets you the match. 0 is a special group comprising the entire found sequence. If you use parentheses in regexes, you make groups, and you can get those too, e.g. if you want to exclude the minus sign you could have done "-?(\\d+)" - note the parentheses. Now you can do m.group(1).

*Note that if you must have an int[], converting a list of integers to int[] requires a loop. toArray can't do it (Integer is not int, but List<int> is, for now, as yet illegal java).

A: It's a one-liner: Strip leading and trailing non-digits, then split on non-digit/minus, convert to int then collecting to an array:
int[] numbers = Arrays.stream(str.replaceAll("^\\D+|\\D+$", "").split("(?=-\\d)|[^-\\d]+"))
  .mapToInt(Integer::parseInt).toArray();

The key here is the split, which does a zero-width spit when the following characters are a minus then a digit, or on chars that are neither minus nor digits.


text:
Q: Python perfect number calculation I am having issues with calculating perfect numbers in python. Apparently the code is working in VBA so I am sure I am making some mistake in syntax / indentation. Please help!
Here is my code:
Mynum=int(input("How many perfect numbers do you want?: "))

counter=0
k=0
j=2
i=1

while counter<Mynum:
    for i in range (1,j-1):
        if (j%i)==0:
            k=k+1
    if k==j:
        counter=counter+1
        print(i)
    k=0
    j=j+1

A: Your screenshot code, which is the better of the two, is broken in a couple of ways: your k = k + 1 expression should be k = k + i as you want to sum the factors, not count them; you print(i) when your should print j or k:
Mynum = int(input("How many perfect numbers do you want?: "))

counter = 0
j = 2

while counter < Mynum:
    k = 0

    for i in range (1, j):

        if (j % i) == 0:
            k += i

    if k == j:
        counter += 1

        print(j)

    j += 1

However, in the bigger picture, this is the wrong approach for looking for perfect numbers -- using this method you're not likely to find more than the first four:
How many perfect numbers do you want?: 5
6
28
496
8128

so you might as well just go for those and forget about asking how many the user wants.
An example better approach would be to search for Mersenne primes using a Lucas-Lehmer primality test and when you find one, compute the companion perfect number from that.  This doesn't take too much code and will leap frog your current approach.

A: Here's another solution to the perfect number:
import itertools as it

def perfect():
    for n in it.count(1):
        if sum(i for i in range(1, n+1) if n%i == 0) == 2*n:
            yield n

>>> list(it.islice(perfect(), 3))
[6, 28, 496]
100 loops, best of 3: 12.6 ms per loop

Or you can use factors (for a slightly faster solution):
def factors(n):
    for a in range(1, int(n**0.5)+1):
        if n % a:
            continue
        x = n // a
        yield a
        if a != x:
            yield x

def perfect():
    for n in it.count(1):
        if sum(factors(n))==2*n:
            yield n

>>> list(it.islice(perfect(), 3))
[6, 28, 496]
1000 loops, best of 3: 1.43 ms per loop

You can improve this even further using a fast prime number version.
Taking a simple prime generator from How to implement an efficient infinite generator of prime numbers in Python?)
import itertools as it
import functools as ft

def primegen():
    yield 2
    D = {}
    for q in it.count(3, 2):
        p = D.pop(q, None)
        if p is None:
            D[q*q] = q
            yield q
        else:
            x = q + 2*p
            while x in D:
                x += 2*p
            D[x] = p

def ll(p):   # Lucas-Lehmer
    if p == 2:
        return True
    m = 2**p - 1
    return ft.reduce(lambda s, _: (s**2 - 2) % m, range(3, p+1), 4) == 0

def perfect():
    for p in primegen():
        if ll(p):
            yield (2**p-1)*(2**(p-1))

>>> list(it.islice(perfect(), 3))
[6, 28, 496]
100000 loops, best of 3: 7.94 µs per loop
>>> list(it.islice(perfect(), 10))
[6,
 28,
 496,
 8128,
 33550336,
 8589869056,
 137438691328,
 2305843008139952128,
 2658455991569831744654692615953842176,
 191561942608236107294793378084303638130997321548169216]
1000 loops, best of 3: 613 µs per loop

These get very big very quickly, e.g. the 20th perfect number has 2663 digits.


text:
Q: Convert android project to java project I've just finished developing an application for android. I want to have a desktop version that is based on java, too.
I have to convert all layouts to swing and what other conflicts I may face, god knows.
Is there a tool for converting android apps to jar standalone? What is the easiest way to do this?

A: There is no tool to do this, as Android and Normal Java apps are very different.
The best you could do is move the non platform specific code into a library project, and reference it from both the Java and Android applications. So all code that doesn't use any import with android in it should be movable into the library, while all your swing/android specific code will go into the referencing projects.


text:
Q: ASP.Net Web Forms - How to set properties of MasterPage from page and user controls I have two master pages which are used by different content pages.
I want to set master page properties from content page, so that master page can show some changes based on those values. And then I also need to access those master page properties in user controls added in master page to reflect some changes. How to achieve that?
I have found a way how to set master page properties from content page by adding <%@ MasterType VirtualPath="/Site.master" %> and then using **Master.property=value** but not sure about how to access user control. Any ideas?

A: You can create a base class form which your master pages inherit from that includes the properties you're looking to store:
abstract public class MasterPageBase : System.Web.UI.MasterPage
{
    public string Prop1
    {
        get { return "Some Value"; }
    }
}

From your UserControl, you can then access the properties as follows:
MasterPageBase masterPage = (MasterPageBase)this.Page.Master;
string strTest = masterPage.Prop1; // "Some Value"

A: I couldn't get the above answers to work, so here is what worked for me:
You want to reference a master page property from a user control.
Firstly, your master page will have a public property like so :
public string BodyClass
{
    set
    {
        this.masterBody.Attributes.Add("class", value);
    }
}

Now add a reference to the master page in the user control ASCX file like so :
<%@ Register Src="~/Source/MasterPages/Main.master" TagPrefix="MSTR" TagName="MasterPage" %>

Then in the code behind (C# in my case) you have this code :
Main masterPage = (Main)this.Page.Master;
masterPage.BodyClass = "container";

Without the reference to the master page above your user control will not be able to find the master page class.

A: I guess you can access user control defined in your master page in two ways:
By using FindControl method, in order to use this you have to add the server tags for user control in content page too, in .aspx page add this:
<%@ Register Src="~/myControl.ascx" TagName="myControl" TagPrefix"uc" %>

then in code behind:
myControl = (myControl)this.Page.Master.FindControl("userControl_Id");

or you can create a public property in your masterpage that returns your usercontrol:
public myControl UserControl { get; set; }

and in code behind of your content page you can access this user control simply through UserControl property:
myControl ctrl = (myControl)this.Page.Master.UserControl;

A: The controls is defined in Master.designer.cs with access modifier "protected." Cut and paste its definition to code-behind (Master.cs) and change the access modifier to "public."
Then you can access the Master Page control as in the answer given by Derek Hunziker:
MasterPageBase masterPage = (MasterPageBase)this.Page.Master;
string strTest = masterPage.Prop1; // "Some Value"


text:
Q: Pycharm Pickle cant install so i cannot figure out how to install the pickle package to pycharm as i need it to call on other levels for my game i just cannot find the package on pycharm if anyone can help me or steer me to another thing like pycharm if anyone can help me with this it would be much appreciated i want to call on another level like you would call on a picture i have the right code for it just not the pickle package i have tried to research this problem but have not been able to get a solid answer so i turned to stack overflow as a last option

A: If you want to check if pickle present in pycharm or not by executing in cmd after entering into python in cmd.
help("modules")

check pickle module in it, If not try installing by
pip install pickle5
from pickle5 import pickle

If you still gets error please let me know


text:
Q: Html+css+javascript responsive design I want to create a html page that display a speedometer.
So, I have a background image (the speedometer), and inside of it I have some buttons that are other images. Every button is made with an  tag with the img inside:

</div

So, it's easy to style every element using fixed position, in order for every object to be positioned well.
But my purpose is to have a dynamically resizeable speedometer.
So, the first thing I thought is to dynamically set the "speedometer" size to 100% of the width of the screen, and then to find the right percentage for the position of the three button inside. I think this should work, but I'm not sure if this is the best way to do that!
Since I'm not so skilled in html/css/javascript, I would like some suggestion on how to achieve this behaviour!
Thanks!

A: Two ways to approach this.

*

*Use media queries.  They're basically a way of declaring your CSS rules based on the current device width.  So you would have to go through and define a CSS rule for each width you'd like to support.  This is part of CSS3 and may require including a couple js libraries to enable support for older browsers.  Also a good idea to include a css reset if you go this route.

*Use a framework like Twitter Bootstrap.  This is basically a framework which does exactly what I laid out in #1.  They provide a lot of very useful pre-defined css classes and minimal javascript to enable the type of rendering you're describing.


text:
Q: Netbeans does not add new server after upgrade of Tomcat 7 to 8 I upgraded my Tomcat from version 7.0.47 to version 8.0.0-RC5 (x86) and it was fine (I did the tests).
When I was do a new configuration onto NetBeans 7.4 to handle with Tomcat 8.0.0-RC5 it showed: The LocationServer Folder(CatalinaHome)specified is not valid.
I tried C:\Program Files\Apache-tomcat-8.0.0-RC5 or C:\Program Files\Apache-tomcat-8.0.0-RC5/conf and I haven't sucess.
I know the file tomcat-users.xml exist and my user and password is there.
I read some posts talking about to downgrade the Tomcat, but I'd like to execute some tasks before it. maybe setting some files... Could you please help me?
Marcos

A: I have added tomcat 8 to netbeans 7.4 with a seperate catalina base(netbeans catalina base) from my semi production environment (original installation).
Consequence of my solution:

*

*Project creation will allow you to use JavaEE 6 only (JavaWeb Projects)

*You only use JavaEE 7 if you are working with (JavaWeb)Marven projects but you will need Glassfish4 or later integrated with your netbeans installation. You use glassfish during project creation and then change server after project creation.

Steps (Option 1):

*

*Install both tomcat 7 and tomcat 8 into one folder (Folder where you want tomcat 8 to be installed or is installed), suppose these folders are tomcat7 and tomcat8 respectively.

*Change tomcat8 to tomcat8_ and tomcat7 to tomcat8 install the tomcat8 folder as one of your servers and name it appropriately (something like tomcat 8.0.1).

*Rename the folders to their original names after installation, this will allow you to do normal tomcat7 functions using tomcat 8 installation

Option 2:

*

*Follow steps 1 and 2 above

*Create folder in (C:\Users\Bonron\AppData\Roaming\NetBeans\7.4\apache-tomcat-8.0.1.0_base) this will be used as your netbeans catalina base

*Install server as in Option 1 but specify private Catalina base as created folder

*Do step 3 of Option 1

*Copy all folders in tomcat8 and paste into your private base (exclude bin and lib - unecessary)

*Do not replace the newly created tomcat-users.xml but you need to replace server.xml, otherwise contact me if you prefer to edit it (invloves just commenting out one line)

A: Try a dev build of NB 8.0. Regarding http://wiki.netbeans.org/NetBeans_80_NewAndNoteworthy Tomcat 8 will be supported.
If you encounter an bug in this feature, please file an issue at https://netbeans.org/bugzilla/


text:
Q: Function file() reads only part of contents in PHP 7.4.27 We have a complex web interface on our dedicated server (Windows Server) which has few console processes with PHP applications running in background and doing various data processing. Some of them write to log files
@ file_put_contents( $logsFileNamePath, $fileContents, FILE_APPEND | LOCK_EX );

and there is one console process that analyzes these log files and seeks potential problems, it executes the code below (it can happen in the same time when other console processes write to the log file):
$logContent = file( $filePath );
$logContent = array_reverse( $logContent );
//... analyze the content

and this has been working fine for years untill recent PHP upgrade from 7.4.20 to 7.4.27 and suddenly sometimes the process that analyzes log files gets contents from a log file which is truncated in the middle of some line. My suspicion is that there is some internal error in this newer version of PHP that causes this... maybe locking of a file no longer works ? It looks like!
Has anyone of you seen similar problem recently? Do you have any ideas what to do with this? Thanks.

A: A patch update from .20 to .27 should not include any backward compatibility breaks, so your experience here is almost certainly just perceptionary.
LOCK_EX is advisory, it does not have to be respected, and file() does not look at it. It seems pretty clear that your reader is reading before the writer has finished. If you want the reader to respect the lock, you'll have to use identical locking mechanisms (i.e., fopen() and flock()) in the reader as well:
$fp = fopen('/path/to/file', 'r');
flock($fp, LOCK_EX); // this will block until the writer is done
while ($line = fgets($fp)) {
    // process $line
}
fclose($fp);

You might also simply update the writer so that it writes to a temp file and then renames it when it's done:
file_put_contents('/path/to/file.temp', $contents);
rename('/path/to/file.temp', '/path/to/file');

And then update your reader to expect the file to occasionally be missing:
if (!file_exists('/path/to/file')) {
    throw new Exception('Nothing to do.');
}


text:
Q: MySQL find only different in 2 table I have 2 table in mysql. table1 and table2.
In table1 is number, email and phone number.
In table 2 same, but sometime different email or phone number.
i want to list of records where number is same and email or phone number different.
sometime both email and phone number is different.
tnx.

A: You can join your tables, then filter accordingly:
SELECT *
FROM   table1 JOIN table2 USING (number)
WHERE  table1.email <> table2.email
    OR table1.phonenumber <> table2.phonenumber