text:
Q: $ax+by$ when a,b are relatively prime and $x,y\geq 0$ I was solving below question in Automaton theory
$$L=\{a^m|m=3x+5y; x,y\geq 0\}$$ then the number of states in minimal dfa is?
What I observed is that $3x+5y$ generated every number after $7(8,9,10,11,12 ------)$
and is there any property that I can use to see why this is so or at least could someone provide source from which I can learn more about this
I put the title "$ax+by$ when a,b are relatively prime" because I thought this might be due to 3,5 are relatively prime (correct me if I am wrong) , I don't know anything about this except that it might be related to number theory.

A: You are asking about The coin problem, which is reasonably well-studied. I encourage you to check out the Wiki article I linked there.
The "Frobenius" of a set of numbers is the smallest one that you can't make as a sum of the numbers in the set - in a land with 3-penny pieces and 5-penny pieces only, you can't pay 7 pennies, but you can pay any amount larger than that.
The Frobenius of a two number set $\{m,n\}$ is given by the formula $F=mn-m-n$. In this case, $15-3-5=7$.
How do we know that every number greater than $7$ is accessible? Here's a not-too-technical proof: If you have enough $5$'s, you can "add $1$" to your total by getting rid of a $5$ and replacing it with two $3$'s $(1=-5+6)$. If you have enough $3$'s, you can add $1$ to your total by getting rid of three of them and replacing them with two $5$'s $(1=-9+10)$.
Thus, if you have at least one $5$ or at least three $3$'s in your sum expressing $n$, then you can also express $n+1$. For numbers over $7$, there is always at least one $5$ or at least three $3$'s in its composition. This is particularly clear for numbers $\ge 15$, and it can be seen with a little more work, for the numbers $8,9,\ldots,14$.

A: This is a consequence of Bezout's Identity, which implies that for $a,b$ relatively prime, there are $\hat{x},\hat{y}$ such that $a\hat{x} + b\hat{y} = 1$. Then for any integer $n$, we choose $x = n\hat{x}$ and $y= n\hat{y}$ and we have $ax + by = n$.
These $x,y$ aren't necessarily $\geq 0$. However, we can determine a lower bound for which we can find a solution with $x,y  \geq 0$. We can always adjust a solution by changing $x$ to $x \pm b$ and $y$ to $y \mp a$. If we can guarantee that some value $x = n\hat{x} \pm mb$ satisfies $0 \leq x\leq \frac{n}{a}$, the corresponding value of $y$ will be nonnegative. This is possible if $\frac{n}{a} \geq b-1$. Similarly, we can guarantee a nonnegative solution if $\frac{n}{b} \geq a -1$. So If $n \geq ab - \max\{a,b\}$, we can guarantee a nonnegative solution.
Clearly this isn't always the best lower bound; in your case this gives $n \geq 10$, while you've showed it possible for $n \geq 8$.
EDIT: As Jyrki Lahtonen pointed out in the comments, robjohn does a much better job doing what I was trying to do (and he actually gets the best bound) in his answer here. For an answer without Bezout's identity, see my other answer to this question, which gets the best bound.

A: Here's an easier way to see this:
Let $b>a$. Consider the sequences of numbers:

*

*$0$, $a$, $2a$, $3a$, $\dots$

*$b$, $b+a$, $b+2a$, $b+3a$, $\dots$

*$2b$, $2b+a$, $2b+2a$, $2b+3a$, $\dots$

*$\dots$

*$(a-1)b$, $(a-1)b+a$, $(a-1)b+2a$, $(a-1)b+3a$, $\dots$

The first row contains integers congruent to $0 \mod a$, the second row congruent to $b \mod a$, etc. Since $b$ and $a$ are coprime, each row represents a different modulus, and the $a$ rows exhaust all moduli $\mod a$.
Now every number has some modulus $\mod a$, and a number appears in some row iff it is $\geq$ the lowest number in that row. Thus all numbers $\geq (a-1)b$ appear somewhere, as I showed in my other answer.
We can now improve on this bound. The number $(a-1)b -a = ab - b - a$ does not appear because it has modulus $-b$ and is less than $(a-1)b$. However, $(a-1)b-a > (a-1)b - b = (a-2)b$, so all numbers greater than $ab - b - a$ with modulus other than $-b$ appear. Since the next number with modulus $-b$ is $(a-1)b$, which appears, all numbers greater than $ab - b - a$ appear.
So if $n \geq ab - b - a + 1 = (a-1)(b-1)$, we can write $n = ax + by$ with $x,y \geq 0$.

A: A slightly magic proof.

Lemma: If $a,b$ are relatively prime positive integers, then for any integer $n$ there is solution to $ax+by=n$ with $x,y$ integers and $0\leq x\leq b-1.$ (So, possibly with $y<0$.)

Proof: We know we can find integers $x_0,y_0$ so that $ax_0+by_0=n.$
By the division algorithm, we can find integers $q,r$ so that $x_0=bq+r$ with $0\leq r\leq b-1.$ Then:
$$ar + b(y_0+aq)=a(r+bq)+by=ax_0+by_0=n$$
So there is a solution $(x,y)=(r,y_0+aq)$ with $0\leq r=x\leq b-1.$

Theorem: If $a,b$ are relatively prime positive integers, then for each integer $n$, there is a non-negative integer solution to at least on of the equations $ax+by=n$ or to $ax+by=ab-a-b-n.$

(There is a stronger statement, which is that for each $n$, exactly one of those two equations has a solution.)
In your case, this would mean for each $n$, one of $3x+5y=n$ and $3x+5y=7-n$ has a non-negative solution.
Proof: Solve $ax_0+by_0=n$ with integers $x_0,y_0$ and $0\leq x_0\leq b-1.$
If $y_0\geq 0$ we are done.
If $y_0<0$ then:
$$ab-a-b-n = a(b-1)-a-b-(ax_0+by_0)=a(b-1-x_0)+b(-1-y_0)$$
Since $0\leq b-1-x_0$ and $0\leq -1-y_0$ we either have non-negative solutions ot $ax+by=n$ or to $ax+b=ab-a-b-n.$
Now, if $N>ab-a-b$, or $N\geq (a-1)(b-1)$, then there there can't be non-negative solutions to $ax+by=ab-a-b-N<0,$ so there must be a solution to $ax+by=N.$

The stronger version of the theorem is that, for any integer $n,$ exactly one of the equations $$\begin{align}ax+by&=n\\ax+by&=ab-a-b-n\end{align}$$
has a non-negative solution.
You can show this by showing that $ax+by=ab-a-b$ has no non-negative integer solution $(x,y)$. This is because if both the equations have non-negative solutions, you could add them to get a non-negative solution for $ax+by=ab-a-b.$
If $ax+by=ab-a-b$ then $a(x+1)+b(y+1)=ab.$ So $b\mid a(x+1)$ and $a\mid b(y+1).$ But since $a,b$ are relatively prime, we get that $b\mid x+1$ and $a\mid y+1.$
But if $x,y\geq 0,$ $x\geq b-1$ and $y\geq a-1$, and thus $ax+by\geq 2ab-a-b>ab-a-b,$ reaching a contradiction.
This lets us count the number of non-negative integers $n$ for which there is no solution:
$$\frac{(a-1)(b-1)}{2}$$

A generating function approach is to ask which coefficients of:
$$f(x)=\frac{1}{1-x^a}\frac{1}{1-x^b}$$
are $0$. We can write:
$$f(x)=\frac{\left(1+x^a+\cdots+x^{a(b-1)}\right)\left(1+x^b+\cdots+x^{b(a-1)}\right)}{\left(1-x^{ab}\right)^2}$$
The denominator contributes only additional multiples of $ab$ to the exponents, and since we know that all sufficiently large values have a solution, this means that the exponents in the numerator must cover all the values modulo $ab$, which means that they must all have coefficient $1$. If $S$ is the set of positive values $n$ for which no $ax+by=n$, we can write the numerator as:
$$\sum_{k=0}^{ab-1} x^k -\left(1-x^{ab}\right)\sum_{k\in S} x^k$$
So, one way to enumerate the numbers in $S$ is:
$$S=\{ax+by-ab\mid 1\leq x\leq b-1, 1\leq y\leq a-1, ax+by\geq ab\}$$
We can see exactly half the pairs $x,y$ have $ax+by>ab$ beacuse if $ax+by>ab$ then $a(b-x)+b(a-y)=2ab-(ax+by)<ab$. (Not that there is no $x,y$ with $ax+by=ab$ since $x\leq b-1,y\leq a-1$.) So again we get that there must be $\frac{(a-1)(b-1)}{2}$ elements of $S$.
We can count $S$ another way and get the result: $$\sum_{x=1}^{b-1}\left\lfloor \frac{ax}{b}\right\rfloor=\frac{(a-1)(b-1)}{2}.$$
Now, our generating function is:
$$f(x)=\frac{\frac{x^{ab}-1}{x-1}+\left(x^{ab}-1\right)\sum_{k\in S} x^k}{(1-x^{ab})^2}=\frac{1}{(x-1)(x^{ab}-1)}-\frac{\sum_{k\in S} x^k}{1-x^{ab}}$$
The coefficient of $x^n$ in the left part is $1+\left\lfloor \frac{n}{ab}\right\rfloor$ the coefficient of $x^n$ in the right term is $1$ if $n$ is congruent to some $s\in S$ modulo $ab$. So the number of non-negative solutions to $ax+by=n$ is:
$$\left\lfloor \frac{n}{ab}\right\rfloor+\begin{cases}0&n\equiv s\pmod{ab} \text{ for some } s\in S\\
1&\text{otherwise}\end{cases}$$

The case when $b=2a-1$ gives us an easy way to list $S$:
$$S=\{i+aj\mid 1\leq i\leq a-1, 0\leq j\leq 2(a-i-1)\}$$
This gives, for $a=3,b=5$ that $S=\{1,4,7,2\}.$
For $a=5,b=9$ this gives $S=\{1,6,11,16,21,26,31,2,7,12,17,22,3,8,13,4\}.$
More generally, if $a<b$, we can list, for each $i\in\{1,\dots,a-1\}$ the values $i+aj$ until we get one divisible by $b$.
For example, $a=3,b=10$ gives:
$$\{1,1+3,1+6,2,2+3,2+6,2+9,2+12,2+15\}$$
If $a<b$ and $ax\equiv -1\pmod {b}$ for $1\leq x\leq b-1$, then you get:
$$S=\{i+bj\mid 1\leq i\leq a-1, 0\leq j<(ix\bmod b)\}$$
If $b=ax+1$ then $0\leq j< xi$. For example, when $a=4,b=13,x=3,$ you get:
$$S=\{1,1+4,1+4\cdot 2,\\
2,2+4,\dots,2+4\cdot 5,\\
3,3+4,\dots,3+4\cdot 8\}$$
If $b=ay-1$ for $y>1,$ then $x = b-y$ and for $i$ you get $0\leq j< b-iy.$
This formula also lets you count $S$ again, since the number of elements for $i$ is $ix\bmod b$ and the number of elements for $a-i$ is $(a-i)x\bmod b$, and $xi+(a-i)x=ax\equiv -1\pmod b$. Since $(xi\bmod b)+((a-i)x\bmod b)\leq 2b-2$, we must have the total for these $i,a-i$ to be $b-1$, so the average over all $i$ must be $\frac{b-1}{2}$, and we get, again, that $|S|=(a-1)\frac{(b-1)}{2}.$

A: Indeed, as you write, since $3$ and $5$ are relatively prime, there are integers $x, y$ such that $3x + 5y = 1$ (this is Bézout's identity).
In particular, this means that, to generate an integer $k$, you have the pair $(kx, ky)$, so that
$$3kx + 5ky = k.$$


text:
Q: Expected method to read dictionary element not found on object of type 'id I am trying to upgrade my app to Xcode 9.3.1 from 8 and have these errors:

Expected method to read dictionary element not found on object of type 'id<NSCopying>'

My code is:
// Normalize the blending mode to use for the key.
// *** Error on next three lines ***
id src = (options[CCBlendFuncSrcColor] ?: @(GL_ONE));
id dst = (options[CCBlendFuncDstColor] ?: @(GL_ZERO));
id equation = (options[CCBlendEquationColor] ?: @(GL_FUNC_ADD));

NSDictionary *normalized = @{
    CCBlendFuncSrcColor: src,
    CCBlendFuncDstColor: dst,
    CCBlendEquationColor: equation,

    // Assume they meant non-separate blending if they didn't fill in the keys.
    // *** Error on next line ***
    CCBlendFuncSrcAlpha: (options[CCBlendFuncSrcAlpha] ?: src),
    CCBlendFuncDstAlpha: (options[CCBlendFuncDstAlpha] ?: dst),
    CCBlendEquationAlpha: (options[CCBlendEquationAlpha] ?: equation),
};

Can anyone point me in the right direction? I have bolded the errors in the code.

A: The compiler thinks that options is of type id<NSCopying>, not an NSDictionary *, which is required to use the dictionary[key] syntax. Your code snippet does not include where that is declared, which is where the error would be.

A: You must cast your object options
    // Normalize the blending mode to use for the key.
id src = (((NSDictionary *)options)[CCBlendFuncSrcColor] ?: @(GL_ONE));
id dst = (((NSDictionary *)options)[CCBlendFuncDstColor] ?: @(GL_ZERO));
id equation = (((NSDictionary *)options)[CCBlendEquationColor] ?: @(GL_FUNC_ADD));

NSDictionary *normalized = @{
    CCBlendFuncSrcColor: src,
    CCBlendFuncDstColor: dst,
    CCBlendEquationColor: equation,

    // Assume they meant non-separate blending if they didn't fill in the keys.
    CCBlendFuncSrcAlpha: (((NSDictionary *)options)[CCBlendFuncSrcAlpha] ?: src),
    CCBlendFuncDstAlpha: (((NSDictionary *)options)[CCBlendFuncDstAlpha] ?: dst),
    CCBlendEquationAlpha: (((NSDictionary *)options)[CCBlendEquationAlpha] ?: equation),
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: stuck on a stored procedure I have a query that works just fine in the latest mysql.
select Title, Link
from PlaylistItem
where PlaylistId = 1;

which returns:
+---------------------------+---------------------------------------------+
| Title                     | Link                                        |
+---------------------------+---------------------------------------------+
| Regina Spektor - Fidelity | https://www.youtube.com/watch?v=wigqKfLWjvM |
+---------------------------+---------------------------------------------+

But when I write a stored procedure, I get an empty result set.
The stored procedure looks like this:
/* Fetch all playlist items for a playlist */
delimiter //
create procedure MixtapeDating.GetPlaylist
(
    in Id int
)
begin
    select Id, Title, Link
    from PlaylistItem
    where PlaylistId = @Id;
end //
delimiter ;

I run the procedure like thus:
call GetPlaylist(1);

A: In mysql variables prefixed by @ are session variables, not stored procedure level variables, so @id is not the same as id. Moreover, id is also a fieldname, so you must rename your parameter.
delimiter //
create procedure MixtapeDating.GetPlaylist
(
    in var_Id int
)
begin
    select Id, Title, Link
    from PlaylistItem
    where PlaylistId = var_Id;
end //
delimiter ;


text:
Q: macro `AM_PATH_CPPUNIT' not found in library I am trying to build libtorrent on shared hosting. So built CPPUnit(1.12.1) with --prefix=$HOME. After that my $HOME/lib and $HOME/include contains CPPUnit libraries and headers.
The I exported LD_ paths
export LD_LIBRARY_PATH=$HOME/lib:$LD_LIBRARY_PATH
export LD_INCLUDE_PATH=$HOME/include:$LD_INCLUDE_PATH

Then I run libtorrent/autogen.sh --prefix=$HOME and getting the following warning, which prevents me to run configure:
aclocal...
aclocal:configure.ac:20: warning: macro `AM_PATH_CPPUNIT' not found in library

cppunit.m4 file is located in $HOME/share/aclocal. I guess libtorrent can't find that dir for some reason.

A: You installed CPPUnit in a non-system place that's not searched by default, so oddly enough when running aclocal within the libtorrent build, it didn't know to look there.  You can tell aclocal where to look with -I and I'm sure you can find a way to do that with autogen.sh in the middle.

A: You need to do an apt-get install libcppunit-dev

A: I stumbled across this page trying to follow the default cppunit Money tutorial. As @Carlo Wood specified

This no longer works. cppunit.m4 was removed from libcppunit-dev.

Which is true, I followed the next answer to no avail, there is no cppunit.m4, the error is that you don't even need AM_PATH_CPPUNIT, just use
ProgramName_LDADD = -lcppunit

instead of ProgramName_LDFLAGS = $(CPPUNIT_LIBS)
Furthermore, I don't know if the rest of the Makefile.am is actually necessary, this is the Makefile I ended up using
Makefile.am
TESTS = MoneyApp
bin_PROGRAMS = $(TESTS)
MoneyApp_SOURCES = ...
MoneyApp_CXXFLAGS = $(CPPUNIT_CFLAGS)
MoneyApp_LDADD = -lcppunit

And config.ac
AC_INIT([MoneyApp], 1.0)
AM_INIT_AUTOMAKE
AC_PROG_CC
AC_PROG_CXX
AC_CONFIG_FILES(Makefile)
AC_OUTPUT

Hopefully this helps somebody in the future.

A: I try everymethod that I found in the internet. But fix it at last only when get know the root cause.
1.The AM_PATH_CPPUNIT is declared in cppunit.m4. The errors happens because the cppunit.m4 is not found.
2.command "aclocal --version" to find out the version. i.e. aclocal-1.15.
3.command "find / | grep aclocal-1.15" to find out the lib place. i.e. /usr/local/share/aclocal-1.15
4.command "find / | grep cppunit.m4" to make sure you have a cppunit.m4. if not, command "yum list *cppunit*" and install the package listed.an repeat current step.
5.copy that cppunit.m4 to the mentioned aclocal lib path.
6.run again and the error disappear.

A: I had the same problem when building libtorrent with MSYS2 in Windows.
Installed cppunit package and the autogen.sh step completed error free.
pacman -S mingw-w64-x86_64-cppunit
or for 32bit:
pacman -S mingw-w64-i686-cppunit
.
Also for building libtorrent Windows MSYS run configure with --disable-mincore:
./configure --disable-mincore
https://rtwi.jmk.hu/wiki/rTorrentOnWindows

A: At Ubuntu 18.04/bionic the @iggy12345 's solution worked perfectly.
Only had to add "touch stdafx.h" and remove -I option from aclocal (on Ubuntu it is installed in /usr/share, not in /usr/local/share).


text:
Q: Sending json through api post request I'm currently struggling to send a JSON via post request into my controller to use it further by calling a stored procedure.
Here is the post request using axios:
async returnJSON(model) {
      this.info = await axios.post(
          "https://localhost:44349/api/items/AddItem/",model)
        .then((response) => response.data);

Here is the structure of model:
{
  "arrayAutori": [
    {
      "dinUniversitate": true,
      "creatorType": 4,
      "creatorID": 3
    }
  ],
  "itemID": "",
  "itemTypeID": 6,
  "drepturiDeAutor": {
    "valueID": "",
    "fieldID": 15
  },
  "isbn": {
    "valueID": "",
    "fieldID": 25
  },
  "limba": {
    "valueID": "",
    "fieldID": 7
  },
  "numarPagini": {
    "valueID": "",
    "fieldID": 43
  },
  "data": {
    "valueID": "",
    "fieldID": 6
  },
  "editura": {
    "valueID": "",
    "fieldID": 23
  },
  "editie": {
    "valueID": "",
    "fieldID": 42
  },
  "volum": {
    "valueID": "",
    "fieldID": 19
  },
  "numarColectie": {
    "valueID": "",
    "fieldID": 41
  },
  "titlu": {
    "valueID": "",
    "fieldID": 1
  }
}

And here is my controller:
 public string AddItem( JObject jsonString)
        {
            db.Database.ExecuteSqlCommand("exec zotero.PublicationsMerge " + jsonString);
            db.SaveChanges();
            return "1";
        }

I can not make a model class to use it, because that JSON may vary depending on the publications.
Also, when I'm debugging this controller, jsonString looks like this:
{{
  "arrayAutori": [
    {
      "dinUniversitate": true,
      "creatorType": 4,
      "creatorID": 3
    }
  ],
  "itemID": "",
  "itemTypeID": 6,
  "drepturiDeAutor": {
    "valueID": "",
    "fieldID": 15
  },
  "isbn": {
    "valueID": "",
    "fieldID": 25
  },
  "limba": {
    "valueID": "",
    "fieldID": 7
  },
  "numarPagini": {
    "valueID": "",
    "fieldID": 43
  },
  "data": {
    "valueID": "",
    "fieldID": 6
  },
  "editura": {
    "valueID": "",
    "fieldID": 23
  },
  "editie": {
    "valueID": "",
    "fieldID": 42
  },
  "volum": {
    "valueID": "",
    "fieldID": 19
  },
  "numarColectie": {
    "valueID": "",
    "fieldID": 41
  },
  "titlu": {
    "valueID": "",
    "fieldID": 1
  }
}}

I don't know why, but it adds another pair of {}. What am I doing wrong?

A: Well, it seems like there's a visual bug that adds another pair of curly brackets in debugging mode and it's caused by JObject. Nothing serious


text:
Q: How to replace the xml text to use Python I'm making xml editor, and want to replace the text in the xml file
data.xml
...
<country name="Singapore">
        <gdppc>text<bold>text</bold>this</gdppc>
</country>
...

I want to change "this" to "text", use to python 2.X

A: You can use replace() method.
xml_code = """data.xml
...
<country name="Singapore">
        <gdppc>text<bold>text</bold>this</gdppc>
</country>
..."""

edited_xml_code = xml_code.replace("this", "text")

print(edited_xml_code)


text:
Q: How can I decode a Laravel encrypted String in VB.Net I can't seem to find a valid answer to this issue...
I am encrypting a password in Laravel using the built in Crypt::encrypt() helper function and passing in a simple string value (let's say 'abcde' for the purpose of this example)
I don't want to install any 3rd party libraries in Laravel if I can help it. I also have my Laravel APP_KEY which is a string value starting with Base64:, but I'm not sure where this comes into it.
This generates me an encrypted string to which I pass down to a VB.Net application.
I cannot workout how to simply decode the encrypted string in my application to pluck out the raw password of 'abcde'.
I have tried many examples that I can find online, but I keep getting errors about "Not a valid key" or "Not a valid Base64 string", etc.
Does someone have an example of a code snippet that will decode a Laravel encrypted string in .Net?
The best I can get to is breaking the encrypted string down into iv, value and mac, but I can't seem to get any further.
Any help would be appreciated.

A:
docs
Encrypting A Value You may encrypt a value using the encrypt helper.
All encrypted values are encrypted using OpenSSL and the
AES-256-CBC cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC) to detect any modifications
to the encrypted string

to begin let's look 'inside' Crypt facade in file vendor/laravel/framework/src/Illuminate /Encryption/Encrypter.php
class Encrypter implements EncrypterContract, StringEncrypter
{
     /**
     * The encryption key.
     *
     * @var string
     */
    protected $key;

    /**
     * The algorithm used for encryption.
     *
     * @var string
     */
    protected $cipher;
     /**
     * Create a new encrypter instance.
     *
     * @param  string  $key
     * @param  string  $cipher
     * @return void
     *
     * @throws \RuntimeException
     */
    public function __construct($key, $cipher = 'aes-128-cbc')
    {
        $key = (string) $key;

        if (! static::supported($key, $cipher)) {
            $ciphers = implode(', ', array_keys(self::$supportedCiphers));

            throw new RuntimeException("Unsupported cipher or incorrect key length. Supported ciphers are: {$ciphers}.");
        }

        $this->key = $key;
        $this->cipher = $cipher;
    }
...
}

param key in __construct method is base64 decoded value (somewhere deeper in calls) of APP_KEY from .env file after :
//APP_KEY=base64:uk1lwVRJIWHaMkiGRcFIzAcTzzGaauYtMSy4L+0ViDk=
$key = base64decode('uk1lwVRJIWHaMkiGRcFIzAcTzzGaauYtMSy4L+0ViDk=');
// and then it passes into __construct method

cipher also somewhere deeper is set to AES-256-CBC as mentioned in the docs (need to mention that this part stays the same across all existing versions of laravel including v9 at the moment)
next looking for encryption to get actions order
/**
     * Encrypt the given value.
     *
     * @param  mixed  $value
     * @param  bool  $serialize
     * @return string
     *
     * @throws \Illuminate\Contracts\Encryption\EncryptException
     */
    public function encrypt($value, $serialize = true)
    {
        // openssl_cipher_iv_length for initialization vector (IV) is 16 bytes for AES-256-CBC
        $iv = random_bytes(openssl_cipher_iv_length(strtolower($this->cipher)));
        // not used in our case
        $tag = '';

        $value = self::$supportedCiphers[strtolower($this->cipher)]['aead']
            ? \openssl_encrypt(
                $serialize ? serialize($value) : $value,
                strtolower($this->cipher), $this->key, 0, $iv, $tag
            )
            : \openssl_encrypt(
                $serialize ? serialize($value) : $value,
                strtolower($this->cipher), $this->key, 0, $iv
            );

        if ($value === false) {
            throw new EncryptException('Could not encrypt the data.');
        }

        $iv = base64_encode($iv);
        $tag = base64_encode($tag);
        // not used in our case
        $mac = self::$supportedCiphers[strtolower($this->cipher)]['aead']
            ? '' // For AEAD-algoritms, the tag / MAC is returned by openssl_encrypt...
            : $this->hash($iv, $value);
        // here is a tricky part, pay attention that we didn't encode $value in base64
        $json = json_encode(compact('iv', 'value', 'mac', 'tag'), JSON_UNESCAPED_SLASHES);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new EncryptException('Could not encrypt the data.');
        }

        return base64_encode($json);
    }

here we have base64 encoded json array with base64 encoded iv and not encoded manually value

c# part (to parse json newtonsoft json, .net472)
from microsoft docs (this part stays 'as is' because php uses same pkcs7 padding by default)
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Mode = CipherMode.CBC; // this is defaul value
                aesAlg.Padding = PaddingMode.PKCS7; // this is default value

                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {

                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }

and our working parse method to tie all this stuff
        /// <summary>
        ///
        /// </summary>
        /// <param name="key">app_key from .env after :</param>
        /// <param name="encodedText">result of Crypt::encrypt($value) or Crypt::encryptString($value) methods</param>
        /// <returns>decoded string</returns>
        private string parse(string key, string encodedText)
        {
            // getting bytes from app_key same as in laravel
            byte[] keyBytes = Convert.FromBase64String(key);

            // going back step by step
            // getting from base64 json and getting array of values
            byte[] dataBytes = Convert.FromBase64String(encodedText);
            string base64decodedData = Encoding.UTF8.GetString(dataBytes);

            var parts = JsonConvert.DeserializeObject<Dictionary<string, string>>(base64decodedData);
            // iv in laravel was encoded with base64 before packing, so undo
            byte[] iv = Convert.FromBase64String(parts["iv"]);

            // and here is the tricky part i've mentioned in encryption method
            // in laravel docs - there were no manual encoding $value to base64
            // but to get valid bytes for decryption we need to treat parts["value"] as
            // it was encoded
            byte[] valueBytes = Convert.FromBase64String(parts["value"]);

            return DecryptStringFromBytes_Aes(valueBytes, keyBytes, iv);

        }

need to say that i didn't dig very hard into varians of encryption algos and didn't even try this code can deal with algos that uses $mac param, so if someone wants to add more info - you are welcome


text:
Q: UITableViewCellAccessoryDetailDisclosureButton not shown in cell I am using tableView grouped Style. my DisclosureButton is not shown in my table cell.what I am missing?
THANKS
- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";

NSArray *listData =[self.tableContents objectForKey:[self.sortedKeys objectAtIndex:[indexPath section]]];

UITableViewCell * cell = [tableView
                          dequeueReusableCellWithIdentifier:SimpleTableIdentifier];

if(cell == nil) {

     cell = [[[UITableViewCell alloc]
     initWithStyle:UITableViewCellStyleDefault
     reuseIdentifier:SimpleTableIdentifier] autorelease];

}

NSUInteger row = [indexPath row];

cell.textLabel.text = [listData objectAtIndex:row];

   // cell.backgroundColor=[UIColor brownColor];

   cell.accessoryType =UITableViewCellAccessoryDetailDisclosureButton;

return cell;
}

A: Your table seems to be in editing state. You should set the accessoryType in editing mode.
cell.editingAccessoryType=UITableViewCellAccessoryDetailDisclosureButton;

A: UITableView hide the accessory button in editing mode.
So if you want to display it, you will need to customize the UITableViewCell.
Or you can do it like the answer given by
Vito Limandibhrata


text:
Q: Topological order using bfs The following question was found in Sedgewick and Wayne book about algorithms in java:
4.2.19 Topological sort and BFS. Explain why the following algorithm does not necessarily produce a topological order: Run BFS, and label the vertices by increasing distance to their respective source.
I was trying to prove it finding a counter example. But, everytime I try, I get a topological order.
I mean, I don't understand why this not work: If the source of a vertex comes before it, why don't we have a topological order?
I think to prove it, we need to find a vertex that its source comes before, but I couldn't.
Anyone have a counterexample? Thanks in advance!
PS: this is not homework
@Edit: I've tried an hamiltonian path like 1 <- 2 <- 0 <- 3 <- 4, which gives 0 3 4 2 1, but changing the positions of 0 3 and 4 gives me a topological order (but, in the order that I obtained, it is not). I am not sure this is or not a topological order, then.

A: You cannot use BFS, because a node with a higher rank may have an incident edge with a lower rank. Here's an example:
Let's say you start BFS at the source (A).
With the algorithm you proposed, node D would come before node C, which is clearly not a topological order. You really have to use DFS.

A: Counter-example:
A -> B
A -> C
B -> C

BFS starting at A could find the nodes in order A-B-C or A-C-B, but only one of those is a topological sort.

A: Yes, you can do topological sorting using BFS. Actually I remembered once my teacher told me that if the problem can be solved by BFS, never choose to solve it by DFS. Because the logic for BFS is simpler than DFS, most of the time you will always want a straightforward solution to a problem.
You need to start with nodes of which the indegree is 0, meaning no other nodes direct to them. Be sure to add these nodes to your result first.You can use a HashMap to map every node with its indegree, and a queue which is very commonly seen in BFS to assist your traversal. When you poll a node from the queue, the indegree of its neighbors need to be decreased by 1, this is like delete the node from the graph and delete the edge between the node and its neighbors. Every time you come across nodes with 0 indegree, offer them to the queue for checking their neighbors later and add them to the result.
  public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {

  ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() == 0) {
      return result;
    }
  Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
  Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();

//mapping node to its indegree to the HashMap, however these nodes
//have to be directed to by one other node, nodes whose indegree == 0
//would not be mapped.
  for (DirectedGraphNode DAGNode : graph){
      for (DirectedGraphNode nei : DAGNode.neighbors){
          if(indegree.containsKey(nei)){
              indegree.put(nei, indegree.get(nei) + 1);
          } else {
              indegree.put(nei, 1);
          }
      }
  }

//find all nodes with indegree == 0. They should be at starting positon in the result
  for (DirectedGraphNode GraphNode : graph) {
      if (!indegree.containsKey(GraphNode)){
          queue.offer(GraphNode);
          result.add(GraphNode);
      }
  }

//everytime we poll out a node from the queue, it means we delete it from the
//graph, we will minus its neighbors indegree by one, this is the same meaning
//as we delete the edge from the node to its neighbors.
  while (!queue.isEmpty()) {
      DirectedGraphNode temp = queue.poll();
      for (DirectedGraphNode neighbor : temp.neighbors){
          indegree.put(neighbor, indegree.get(neighbor) - 1);
          if (indegree.get(neighbor) == 0){
              result.add(neighbor);
              queue.offer(neighbor);
          }
      }
  }
  return result;
}


text:
Q: How to create a ClassBreakRenderer without data coming from Feature Layer? I would like to create a ClassBreakRenderer to represent integer values. The symbols I am using are defined as PictureMarkerSymbols with JSON and they are just a filled blue circle with different sizes that were created with ArcMap 10.1 and published into ArcGIS Server. This is just to introduce the thing.
The problem is that in all the examples I see on the ArcGIS Javascript API about Rendering, the examples do always get the data from a particular column of a Feature Layer, but my data do NOT come from this data source: they come from an array of integers in client side. Just the symbol comes from the server-side, but not the integer value.
Is there any way of "tricking" the constructor of ClassBreakRenderer in order to accept an array (or collection, dictionary, set, whatever) of integers to be classified in symbols? There should be "life" a part of Feature Layers, isn't it?
Thanks for your help!

EDIT
The thing is that my data source is an array of integers like this:
var myArray = [15, 37, 47, 12, 125, 87, 36, 66, 10, 4, 18, 19, 23]

AND NOT:
var featureLayer = new esri.layers.FeatureLayer("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/3", {
          mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
          outFields: ["*"],

And in principle, the ClassBreakRenderer receives a column of that Feature Layer as:
var renderer = new esri.renderer.ClassBreaksRenderer(symbol, "POP07_SQMI");

But I do NOT have that column "POP07_SQMI" I have an array called "myArray" and my question is that if it is possible to use the array instead of the column name that I don't have. Because world should not be limited to the existence of feature layers to retrieve data from them.... :S

A: In the newest versions of ArcGIS for JavaScript, you can use the ClassBreaksRenderer to render data coming from an array.  Instead of referencing a FeatureLayer column in the call to the classBreaksRenderer like this:
var renderer = new esri.renderer.ClassBreaksRenderer(symbol, "POP07_SQMI");

reference a call to a function, like this:
var renderer = new esri.renderer.ClassBreaksRenderer(null, myFunction());

You need to have the myFunction() function return a distinct number for each key value that you input into the myFunction() as an input parameter.  Basically you feed myFunction() an input parameter and return the number you want to classify that key to.

A: Create your own class breaks renderer, specify your breaks using addBreak, then apply your renderer to the feature layer using setRenderer. You'll probably want to create your feature layer with visible: false then call show() once you apply the renderer.


text:
Q: Numpy max over only the first element of an array of pairs I have a multidimensional numpy array consisting of tuples like below:
[[(0.56, 1),(0.25, 4), ...],[(0.11, 9), ...], ...]

The second element of each tuple is an index reference. I want to extract the tuple with the highest first value per row. Is there a way to achieve this with numpy max?
One thing I tried is playing around with the axis parameter like below:
np.max(my_array, axis=0)

But this shuffles around the pairs with the index reference not preserved. E.g. the first row in the above example would show something like [(0.56,4), ...] whereas I want it to show [(0.56,1), ...]

A: Don't use tuples in numpy arrays. Convert it all to a numpy array with the last dimension being 2:
>>> a = np.array([[(0.56, 1), (0.25, 4)],[(0.11, 9), (0.19, 5)]])
>>> a.shape
(2, 2, 2)

Then:
>>> highest_val_per_row = np.argmax(a[:,:,0], axis=1)
>>> a[np.arange(a.shape[0]), highest_val_per_row]
array([[0.56, 1.  ],
       [0.19, 5.  ]])

A: In plain python, you could use :
[max(row, key=lambda row: row[0]) for row in array]

A: You can try something linke this:
lst = [[(0.56, 1),(0.25, 4)],[(0.11, 9), (0.25, 4)]]

for e in lst:
    print(max(e))

However, i think there are more efficient ways of doing it.


text:
Q: When does AWS Elastic Load Balancer returns response with an empty header? When does AWS Elastic Load Balancer returns response with an empty header ?
I am getting empty response headers from ELB, and requests not reaching backend targets.

A: @marianogg9 yes by directly hitting the target I am able to get headers in response, though sometimes due to some race condition in elb requests are not even routed to backend targets hence generating null headers in response.


text:
Q: Capturar Scroll de PDF dentro de um embed Opa,
Tenho que manipular o scroll de um documento PDF, dentro de uma tag EMBED.
Seria da seguinte forma, ao abrir o documento, o botão de ACEITAR, ficaria desabilitado e somente quando o usuário, rolasse o documento 100% o botão seria liberado.
Porém, não estou conseguindo esse resultado final.
Segue os códigos abaixo, que estou utilizando.

Termos e condições

            <embed class="frame-termo" id="termo"
              src="https:soulpay.com.br/wp-content/uploads/2018/11/Contrato-de-Adesao-e-Credenciamento-SoulPay-alteracoes-novembro18-merged.pdf"
              type="application/pdf"/>

          <button type="button" class="btn btn-default" id="btn-fechar" data-dismiss="modal">Cancelar</button>
          <button id="botaoAceitar" type="button" class="btn btn-primary" value="Accept" data-dismiss="modal"
            disabled>Aceitar</button>

Abaixo segue o script que estou utilizando.


text:
Q: Running JAXB/XJC in Dockerfile yields in GConf Error I'm using docker in combination with a Java project
that is compiled during the build process.
Now I'm trying to generate Java code based on Collada
XML schema version 1.5 by calling following shell script
inside the Dockerfile:
BASEDIR=$(dirname $0)
xjc $BASEDIR/schema/collada/collada-schema-1.5.xsd \
    -d $BASEDIR/knowrob_vis/src/main/java \
    -p org.knowrob.vis.collada \
    -extension $BASEDIR/schema/simpleMode.xsd

Unfortunately, this yields in following error:
(process:4093): GConf-WARNING **: Client failed to connect to the D-BUS daemon:
Unable to autolaunch a dbus-daemon without a $DISPLAY for X11
GConf Error: No D-BUS daemon running

On my host machine it works fine to generate the Java code.
You can find the Dockerfile here: https://raw.githubusercontent.com/knowrob/docker/master/hydro-knowrob/hydro-knowrob-daemon_local/Dockerfile
EDIT1:
It seems xjc has some strange XServer dependencies.
That does not make sense to me.
Howto avoid that problem?

A: I solved the issue.
In fact the DBus error can be ignored.
The problem was having no write permissions on the directory where xjc
tries to generate the files.
Fixed it by switching ownership to user that is used in the Dockerfile.


text: Q: Chrome Extension for Console - select frame I'm developing a Chrome extension to help debugging. I can't see any API for editing the console panel. What I mainly want to do is to automatically select the frame to a given one. Any suggestions welcome!


text:
Q: How to merge strings from 3 different objects in a list? What I want to do is merging 3 strings according to the sequence in both the lists.
For example, in an array I have these 3 items which have their data in string form:
1: {
    permissionIDList: "1,2,3"
    permissionNameList: "Admin Role,Admin Role,Bulletin Board"
    permissionTypeList: "view,edit,view"
}

I want to merge the lists and map it into both value and label so that it will become:
0: {value: 1, label: Admin Role - view}
1: {value: 2, label: Admin Role - edit}
2: {value: 3, label: Bulletin Board - view}

A: Array.reduce implementation

const data = {
    permissionIDList: "1,2,3",
    permissionNameList: "Admin Role,Admin Role,Bulletin Board",
    permissionTypeList: "view,edit,view",
};
const [permissionIDList, permissionNameList, permissionTypeList] = [data.permissionIDList.split(','), data.permissionNameList.split(','), data.permissionTypeList.split(',')];
const merger = permissionIDList.reduce((acc, curr, index) => {
  acc[curr] = {
    value: curr,
    label: `${permissionNameList[index]} - ${permissionTypeList[index]}`
  }
  return acc;
}, {});
console.log(merger);

If your final data response is an array, you can make use of Array.map

const data = {
    permissionIDList: "1,2,3",
    permissionNameList: "Admin Role,Admin Role,Bulletin Board",
    permissionTypeList: "view,edit,view",
};
const [permissionIDList, permissionNameList, permissionTypeList] = [data.permissionIDList.split(','), data.permissionNameList.split(','), data.permissionTypeList.split(',')]
const merger = permissionIDList.map((node, index) => ({
  value: node,
  label: `${permissionNameList[index]} - ${permissionTypeList[index]}`
}));
console.log(merger);

A: This code gives what you need:
const strings = {
    permissionIDList: "1,2,3",
    permissionNameList: "Admin Role,Admin Role,Bulletin Board",
    permissionTypeList: "view,edit,view"
}
const permissionIDList = strings.permissionIDList.split(',');
const permissionNameList = strings.permissionNameList.split(',');
const permissionTypeList = strings.permissionTypeList.split(',');

const result = [];

for(let i = 0; i < permissionIDList.length; i++){
  result.push({
    value: permissionIDList[i],
    label: permissionNameList[i] + " - " + permissionTypeList[i]
  });
}

console.log(result);

A: Another implementation could be:
const value = {
    permissionIDList: "1,2,3",
    permissionNameList: "Admin Role,Admin Role,Bulletin Board",
    permissionTypeList: "view,edit,view",
}

Object.entries(value).map((item,i) => {
    const permissionNameList = value['permissionNameList'].split(','[i];
    const permissionTypeList = value['permissionTypeList'].split(','[i];
    const permissionIDList = value['permissionIDList'].split(',')[i];

return {
    value: permissionIDList,
    label: `${permissionNameList} - ${permissionTypeList}`
  }

})


text:
Q: Как сохранить временные данные глобально? WordPress Я использую WordPress и мне требуеться сохранить данные куда-нибудь что бы извлекать их в нескольких разных скриптах (т.е. человек выполнил несколько переходов по разным страницам).
Если можно - приведите пожалуйста пример как сохранить данные в какой либо структуре и извлечь их. Спасибо!

A: В WordPress стартовать и уничтожать сессию нужно во время события init. Такой подход обеспечивает возможность ее использования в теме и плагинах, а также в коде ajax. Добавьте такой код в functions.php:
add_action( 'init', 'my_start_session', 1 );
add_action( 'wp_logout', 'my_end_session' );
add_action( 'wp_login', 'my_end_session' );

function my_start_session() {
    if ( ! session_id() ) {
        session_start();
    }
}

function my_end_session() {
    session_destroy();
}

В первой строке указан приоритет = 1 для того, чтобы сессия была запущена ранее всех остальных хуков, выполняющихся по событию init.
Строки 2 и 3 добавляют хуки,уничтожающие сессию, если пользователь вышел из учётной записи WordPress или пытается войти в учётную запись (возможно, под новым именем).
Проверка if ( ! session_id() ) нужна для того, чтобы php не выдал предупреждение E_NOTICE. Но и без этой проверки код будет работать, потому что session_start() создаёт новую сессию или возобновляет текущую.
Использование.
Записать данные в сессию можно таким образом:
$_SESSION['my_key'] = "Информация о пользователе, которую нужно сохранить";

А извлечь - таким образом:
if ( isset( $_SESSION['my_key'] ) ) {
    $value = $_SESSION['my_key'];
} else {
    $value = '';
}


text:
Q: Shoud disposing the same instance multiple times be possible Should it be possible, to call .Dispose for the same instance of IDisposable multiple times without throwing an exception? Is there some definition for this?
For example:
public class Test : IDisposable
{
    public void Dispose()
    {
        // What ever
    }
}

var t = Test();
t.Dispose();
t.Dispose(); // Should this work in any case?

The reason why I'm asking this:
I've created some mechanism, which search in the VisualTree for elements, which inherit from IDisposable, but i can not be sure, that one of these elements gets disposed before.
Some code snipped from a window class
/// <summary>
/// Dispose
/// </summary>
public void DisposeAll()
{
    foreach (var obj in WPFVisualTreeHelper.FindChildren<IDisposable>(this))
    {
        if (!disposables.Contains(obj))
        {
            disposables.Add(obj);
        }
    }
    foreach (IDisposable disposable in disposables)
    {
        disposable.Dispose();
    }
}

Thank you!

A:
If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

Source

A: MSDN says:

The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

The last part is also important: make sure to set a disposed boolean flag to ensure resources aren't used after Dispose is called. You can also use that for the second call to Dispose to just ignore it.


text:
Q: Servicestack GlobalRequestFilters populating additional user auth data into Jwt tokens I want to add additional properties to the response when a user logs in.
When calling https://Servicestackservice/auth/credentials?userName=****&password=****  I get the below response. I want to add 2 additional values.  DateFormat & TimeZone
{
    "userId": "21",
    "sessionId": "****",
    "userName": "SystemAdmin",
    "displayName": "System Admin",
    "referrerUrl": null,
    "bearerToken": "****",
    "refreshToken": *",
    "profileUrl": *",
    "roles": [ View
    ],
    "permissions": [ View
    ],
    "responseStatus": {
        "errorCode": null,
        "message": null,
        "stackTrace": null,
        "errors": null,
        "meta": null
    },
    "meta": null
}
I found an example from the SS forums. I had to modify it some to make it run.
From the SS docs
Modifying the Payload

Whilst only limited info is embedded in the payload by default, all matching AuthUserSession properties embedded in the token will also be populated on the Session, which you can add to the payload using the CreatePayloadFilter delegate. So if you also want to have access to when the user was registered you can add it to the payload with:
I am hoping this is how i get them into the "matching AuthUserSession"
          this.GlobalRequestFilters.Add(async (req, res, requestDto) =>
            {
                AuthFilter.AuthResponse(req, res, requestDto);
            });

        public static void AuthResponse(IRequest req, IResponse res, object response)
    {
        var authRes = response as Authenticate;
        if (authRes == null || authRes.UserName == null)
        {
            return;
        }
        var session = (CustomUserSession)req.GetSession();
        if (session != null && session.UserAuthId != null)
        {
            //General Format for US
            string dformat = "g";
            using (var db = HostContext.TryResolve<IDbConnectionFactory>().Open())
            {
                var userAuthExt = db.Single<UserAuthExtension>(ext => ext.UserAuthId == int.Parse(session.UserAuthId));
                if (userAuthExt != null)
                {
                    dformat = userAuthExt.DateTimeFormat;
                }
            }

            authRes.Meta = new Dictionary<string, string> {{"TimeZone", session.TimeZone}, {"DateFormat", dformat}};
        }
    }

Adding this to try to get the JWT tokens to hold the new data. Examining the payload i can see the 2 new values are added to the list.
   new JwtAuthProvider(AppSettings)
                    {
                        CreatePayloadFilter = (payload, session) =>
                        {

                            if (session != null && session.UserAuthId != null)
                            {
                                //General Format for US
                                string dformat = "g";
                                using (var db = HostContext.TryResolve<IDbConnectionFactory>().Open())
                                {
                                    var userAuthExt = db.Single<UserAuthExtension>(ext => ext.UserAuthId == int.Parse(session.UserAuthId));
                                    if (userAuthExt != null)
                                    {
                                        dformat = userAuthExt.DateTimeFormat;
                                    }
                                }

                                payload["TimeZone"] = ((AuthUserSession) session).TimeZone;
                                payload["DateFormat"] = dformat;
                            }
                        },

A: You should link to the docs you're referring to, which I believe is ServiceStack's JWT Modifying the Payload docs. Although it's not clear which example in the Customer Forums you're referring to.
It's also not clear what the question is, I'm assuming it's this statement:

When calling /auth/credentials?userName=****&password=**** I do not see the new values.

Where exactly are you expecting these values? If you're authenticating by credentials you're not Authenticating by JWT so you will not have these additional properties populated on your User Session. If they're embedded in your JWT's body payload then as TimeZone is a AuthUserSession property, it should be populated if it was contained within the JWT payload:
case "TimeZone":
    authSession.TimeZone = entry.Value;
    break;

But DateFormat is not an AuthUserSession property so you will need to populate it manually by providing an implementation for PopulateSessionFilter, e.g:
new JwtAuthProvider(AppSettings)
{
    PopulateSessionFilter = (session,payload,req) =>
        session.Meta["DateFormat"] = payload["DateFormat"];
}

But these properties are only going populated in the Users Session when authenticating via JWT.
To help diagnose any issues you should but a breakpoint in your CreatePayloadFilter to see what you've populated the JWT payload with and conversely put a breakpoint in your PopulateSessionFilter to inspect what's contained in the payload and resulting populated session.


text:
Q: Capybara InfiniteRedirectError I am getting the same behavior whether it's in the browser or running rspec... How can this issue get resolved?
I have tried removing the before_filter :authenticate_user! within application_controller.rb and the result remains the same. The failing example is the very first one within spec/features/subdomain_feature_spec.rb

Failures:

1) subdomains redirects invalid accounts
 Failure/Error: visit root_url(subdomain: 'random-subdomain')

 Capybara::InfiniteRedirectError:
   redirected more than 5 times, check for infinite redirects.
 # /home/benny/.rvm/gems/ruby-2.3.3/gems/capybara-2.13.0/lib/capybara/rack_test/browser.rb:41:in `process_and_follow_redirects'
 # /home/benny/.rvm/gems/ruby-2.3.3/gems/capybara-2.13.0/lib/capybara/rack_test/browser.rb:22:in `visit'
 # /home/benny/.rvm/gems/ruby-2.3.3/gems/capybara-2.13.0/lib/capybara/rack_test/driver.rb:43:in `visit'
 # /home/benny/.rvm/gems/ruby-2.3.3/gems/capybara-2.13.0/lib/capybara/session.rb:254:in `visit'
 # /home/benny/.rvm/gems/ruby-2.3.3/gems/capybara-2.13.0/lib/capybara/dsl.rb:52:in `block (2 levels) in <module:DSL>'
 # ./spec/features/subdomain_feature_spec.rb:7:in `block (2 levels) in <top (required)>'

...
Failed examples:

rspec ./spec/features/subdomain_feature_spec.rb:6 # subdomains redirects invalid accounts

Relevant Files

spec/features/subdomain_feature_spec.rb

require 'rails_helper'

describe 'subdomains' do
  let!(:account) { create(:account_with_schema) }

  it 'redirects invalid accounts' do
    visit root_url(subdomain: 'random-subdomain')
    expect(page.current_url).to_not include('random-subdomain')
  end

  it 'allows valid accounts' do
    visit root_url(subdomain: account.subdomain)
    expect(page.current_url).to include(account.subdomain)
  end

  it 'forces user to login before accessing subdomain content' do
    visit root_url(subdomain: account.subdomain)
    expect(page).to have_content 'sign in or sign up before continuing'
  end
end

config/routes.rb

class SubdomainPresent
  def self.matches?(request)
    request.subdomain.present?
  end
end

class SubdomainBlank
  def self.matches?(request)
    request.subdomain.blank?
  end
end

Rails.application.routes.draw do
  constraints(SubdomainPresent) do
    root 'projects#index', as: :subdomain_root
    devise_for :users
  end

  # only allow certain routes when there isn't a subdomain
  constraints(SubdomainBlank) do
    root 'welcome#index'
    resources :accounts, only: [:new, :create]
  end
end

controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_filter :load_schema, :authenticate_user!

  private

  def load_schema
    Apartment::Tenant.switch!('public')
    return unless request.subdomain.present?

    account = Account.find_by(subdomain: request.subdomain)
    if account
      Apartment::Tenant.switch!(request.subdomain)
    else
      redirect_to root_url(subdomain: :false)
    end
  end

  def after_sign_out_path_for(resource_or_scope)
    new_user_session_path
  end
end

controllers/welcome_controller.rb

class WelcomeController < ApplicationController
  skip_before_filter :authenticate_user!, only: :index

  def index
  end
end

spec/factories/accounts.rb

FactoryGirl.define do
  sequence(:subdomain) { |n| "subdomain#{n}" }

  factory :account do
    sequence(:subdomain) { |n| "subdomain#{n}" }
    association :owner, factory: :user

    factory :account_with_schema do
      after(:build) do |account|
        Apartment::Tenant.create(account.subdomain)
        Apartment::Tenant.switch!(account.subdomain)
      end
      after(:create) do |account|
        Apartment::Tenant.reset
      end
    end
  end
end

spec/rails_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?

# Add additional requires below this line. Rails is not loaded until this point!
require 'spec_helper'
require 'rspec/rails'
require 'capybara/poltergeist'

Capybara.javascript_driver = :poltergeist

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  config.use_transactional_fixtures = false

  config.infer_spec_type_from_file_location!

  config.include FactoryGirl::Syntax::Methods

  # Filter lines from Rails gems in backtraces.
  config.filter_rails_from_backtrace!
  # arbitrary gems may also be filtered via:
  # config.filter_gems_from_backtrace("gem name")
end

# Capybara.register_driver :poltergeist do |app|
#   Capybara::Poltergeist::Driver.new(app, options)
# end

A: The Capybara rack_test driver ignores hostnames so you're not going to be able to test subdomain behavior with it, you'll need to run those tests with one of the drivers that utilizes/mimics a full browser (selenium, poltergeist, capybara-webkit).
Additionally you want to write and url/path check using the Capybara have_current_path matcher rather than eq with `current_url'
expect(page).not_to have_current_path(/random-subdomain/, url: true)


text:
Q: Laravel Scheduler Skipping certain Jobs but Dispatching another on Server but Works perfectly fine on Localhost I have created 2 jobs, namely "DailySalesSummaryAmazon" and "AmazonAccountHealthSummary". I am trying to dispatch these jobs everyday at 9:30 AM. Somehow, the first job is not getting dispatched but the second one "AmazonAccountHealthSummary" gets dispatched and executed perfectly on server.
On the other hands when I test the same code on my localhost, every job is being dispatched and being processed well. I am unable to fix this issue. I tried restarting the supervisor workers on the server but to no avail.
`
<?php

namespace App\Console;

use Carbon\Carbon;
use App\Models\Channel;
use App\Models\Subscription;
use Illuminate\Support\Facades\Log;
use App\Jobs\SyncLastDayAmazonOrders;
use App\Jobs\SyncLastDayFlipkartOrders;
use App\Jobs\SyncLastHourFlipkartOrders;
use App\Models\WhatsAppNotificationModel;
use App\Jobs\FetchAmazonAccountPerformance;
use Illuminate\Console\Scheduling\Schedule;
use App\Jobs\inventory\CheckAmazonInventoryLevel;
use App\Jobs\WhatsappNotification\DailySalesSummaryAmazon;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Jobs\WhatsappNotification\DailySalesSummaryFlipkart;
use App\Jobs\WhatsappNotification\AmazonAccountHealthSummary;

class Kernel extends ConsoleKernel
{

protected function schedule(Schedule $schedule)
    {
        $schedule->call(function(){
            $allChannels=Channel::all();
            foreach( $allChannels as $channel){

                $sub=Subscription::where('user_id','=',$channel->user_id)->orderBy('id','DESC')->first();

                $subExpiryDate=$sub->expiry_date;
                $validSubscription=($subExpiryDate >= Carbon::now())?1:0;
                Log::channel('scheduledjobslog')->info("User subscription expiry date for channel ID: $channel->user_id is : $subExpiryDate");
                if($validSubscription){
                    Log::channel('scheduledjobslog')->info("Subscription is valid for channel ID: $channel->id");
                    $whatsappSubscription=WhatsAppNotificationModel::where('user_id','=',$channel->user_id)->first();
                    if(!is_null($whatsappSubscription))
                    {
                        Log::channel('scheduledjobslog')->info("Found a whatsapp no. for the channel ID: $channel->id");
                        if($channel->order_sync_status){
                            Log::channel('scheduledjobslog')->info("Order sync is enabled for the given channel; Trying to dispatch job for whatsapp; ");
                            Log::channel('scheduledjobslog')->info("Channel details are as given below: Channel ID: $channel->id; $channel->channel_name; Store Name: $channel->store_name");

                            if($channel->channel_name=='amazon')
                                {
                                    Log::channel('scheduledjobslog')->info('Dispatching Daily Sales Summary Job for : Amazon Channel='.$channel->id);
                                    DailySalesSummaryAmazon::dispatch($channel->id);
                                    AmazonAccountHealthSummary::dispatch($channel->id);
                                    Log::channel('scheduledjobslog')->info('Dispatching Daily Account Health Summary Job for : Amazon Channel='.$channel->id);

                                }
                        }
                    }
                }
            }
        })->dailyAt('9:30');
    }

}

`
Tried restarting the supervisor workers: sudo supervisorctl restart saral-queue:*
Cleared compiled services and package files using php artisan clear-compiled


text:
Q: Open and List files/folders in a zip archive in PHP Well,
What I need is:
PHP script which can open and the echo out all top level files and folder included in a zip archive saved at location:
/submittions/projects/zip/file_name.zip

So, if a zip archive contains 3 folders and 2 files at top level where all of these three top level folders have sub folder in them as well, I should get result as:
folder_name_1
folder_name_2
folder_name_3
file_name_1
file_name_2

I tried searching here but still with nothing.
There is a tutorial for extracting but it doesn't tell clearly about listing each file:
http://net.tutsplus.com/articles/news/how-to-open-zip-files-with-php/
I tried zip_open($path_to_zip)
While using this function, I am getting output as 5. I believe it is an error number.
All those ZIP files are set to CHMOD 777
One more thing, on applying zip_open(), if I test if file is open or not, I am getting two different cases like this:
$zip  =  zip_open($path);

// CHECK ONE
if($zip) {
 echo "Opened";
} else {
 echo "Failed";
}

// CHECK TWO
if(is_resource($zip)) {
 echo "Opened";
} else {
 echo "Failed";
}

Check ONE returns Opened, check TWO returns Failed.
I just want the file and folder names in a zip archive and it would be great if you get me a simple and straightforward solution without any part of extraction and all, if its possible?
My server's PHP configuration is here: http://academicadda.com/info.php
Below is simple code where zip.zip is in same directory:
<?php
$zip    =   zip_open('zip.zip');
if(is_resource($zip)) {
echo "open";
} else {
echo "failed";
}

?>

OUTPUT: open
What should be code to read each top level file and folder? zip_read() ?

A: if($zip)returns true because its a positive value, in your case 5. And an error code 5 references to an "can't read" problem. I suggest you to check your path and permissions.

A: Thank you guys for addressing me.
It was path and permission problem.
Here is the solution I have finally got after a workaround:
<?php
$zip    =   zip_open('zip.zip');

if(is_resource($zip)) {

   while (($zip_entry = zip_read($zip)))
        {
            echo $path = zip_entry_name($zip_entry);
        }

} else {
   echo "failed";
}

?>


text:
Q: Another Algorithm Job-Interview So here is the question:

Suppose you have 100 thousand integers which ranges from 1 to 1 million. Please sort out the integers. The time complexity should be O(n).

Anybody who shares his or her ideas is well appreciated.

A: The hint should be that they range from 1 to 1 million.
See pigeonhole sort

A: Since the problem has fixed size and includes a finite set of instances, any sorting algorithm will terminate in O(1). You should tell the tester to go back to algorithm analysis school. One possible way to generalize this problem to an infinite set is: you have an array of size n with numbers ranging in [0, 10n]. Can you sort it in O(n)? That makes sense to me. Or you could parametrize the problem with the size of the array and the range of the integers and come up with some O(f(n,k)) bound. The problem is when you get a question like this in an interview, what do you do? Do you try to guess what the interviewer would like to hear or do you say something like "let me rephrase your question"? Or you just scoot towards the exit with a big smile?

A: Sounds like a straightforward counting sort.

*

*Reserve memory for an array a of size 1 million

*Initialize all array values to 0

*Loop through the integers. For each integer i increment a[i] by one.

*Output sorted sequence by walking through the array and printing each number i for a[i] times.

Space is constant. Runtime is O(n).

A: Use count sort. Just count all of them ( O(n) ), and then create fill the result array ( O(n), again).

A: You have to use any known sorting algorithms with complexity O(n)
Is there an O(n) integer sorting algorithm?


text:
Q: I need to pass multiple check boxes from jquery to php and GET is as an array in php i need to pass a get variable via jquery, one of the form fields is a multiple check box. so i want to be able to pass it so that from php i can use GET and collect it then use IMPLODE to get such a value but its not working
JQUERY CODE HERE
    $(document).ready(function(){

                $.get('actionfilter.php', function(data){
                             $('.disFilter').html(data).fadeIn("2000");

                        });

          $("#FilterForm :input").change(function() {
          $(this).closest('form').data('changed', true);

                var FilterByOrder = $("#FilterByOrder").val();

                var location = $("#location").val();
                var sortFilter = $("#sortFilter").val();
                var Highlights = $("#Highlights").val();

                if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
                {

                   $.get('actionfilter.php', function(data){
                             $('.disFilter').html(data).fadeIn("2000");

                        });
                }
                else
                {
                   $.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, Highlights: Highlights}, function(data){
                             $('.disFilter').html(data).fadeIn("2000");

                        });
                }
    });
});

THE PHP VERSON
 <?php
if(isset($_GET['FilterByOrder'])){
  echo 'filter '. $FilterByOrder=$_GET['FilterByOrder'].'
';
  echo  'location '.$location=$_GET['location'].'
';
   echo 'sort '.$sortFilter=$_GET['sortFilter'].'
';
   echo 'highlits '.$Highlights=$_GET['Highlights'].'
';

   echo 'here is the one!';
}else
{
  echo'lets run it';
}

?>

THE HTML FORM FIELD
<input type="checkbox" name="Highlights[]" value="<?php echo $DisplayedHighlightID; ?>" id="Highlights">

A:

                    <form method="post" name="search" action="<?php echo base_url();?>search">

Search by Industry :

                        Select All: <input type="checkbox" name="industry_id[]" id="check-buton" value="" onclick="toggle()">

                        <?php
                        if($Industries)
                        {?>
                            <?php
                        foreach($Industries as $Industry)
                        {
                            ?>

    <input type="checkbox" name="industry_id[]" class="chkall" value="<?php echo $Industry['id'];?>"> <?php echo $Industry['industry_name'];?>

 <?php
                        } }
                        ?>

                        <input type="submit" name="submit" value="Search">

                    </form>
<?php
if(_inputPost('industry_id'))
            {
                $ind=implode(',', _inputPost('industry_id'));
                //print($ind);die;
                $ind=ltrim($ind,',');
                $industry_id = $ind;
                $flag = true;
                $condition = ' and sector in ('.$ind.')';
                $extraparams = '?industry_id='.$industry_id;

            }else if(_inputGet('industry_id'))
                {
                    $ind= _inputGet('industry_id');
                    //print($ind);die;
                     $ind=ltrim($ind,',');
                    $industry_id = $ind;
                    $flag = true;
                    $condition = ' and sector in ('.$ind.')';
                    $extraparams = '?industry_id='.$industry_id;

                }
        else if(trim(_inputGet('s')))
            {
                $s = trim(_inputGet('s'));
                $flag = true;
                $condition = ' and (name LIKE '.$this->db->escape('%'.$s.'%').' or mobile_office LIKE '.$this->db->escape('%'.$s.'%').' or mobile2 LIKE '.$this->db->escape('%'.$s.'%').' or email2 LIKE '.$this->db->escape('%'.$s.'%').")";
                $extraparams = '?s='.$s;
            }

A: $(document).ready(function(){

            var searchValue = $("#searchValue").val();
            $.get('actionfilter.php', {searchValue: searchValue}function(data){
                         $('.disFilter').html(data).fadeIn("2000");

                    });

      $("#FilterForm :input").change(function() {
      $(this).closest('form').data('changed', true);

          if($("#FilterByOrder").prop("checked") == true){
            var FilterByOrder = 'on';
          }
          else
          {
            var FilterByOrder = 'of';
           }

            var location = $("#location").val();
            var sortFilter = $("#sortFilter").val();

            /* declare an checkbox array */
            var HighlightsArrays = [];

            /* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
            $(".Highlights:checked").each(function() {
                HighlightsArrays.push($(this).val());
            });
                /* we join the array separated by the comma */
                var selectedHighlights;
                selectedHighlights = HighlightsArrays.join(',') + ",";

            if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
            {

               $.get('actionfilter.php', function(data){
                         $('.disFilter').html(data).fadeIn("2000");

                    });
            }
            else
            {
               $.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, selectedHighlights: selectedHighlights}, function(data){
                         $('.disFilter').html(data).fadeIn("2000");

                    });
            }
});

});


text:
Q: Split string (path of Uri) based on "/" Wonder if someone could point me in the right direction. What I'd like to achieve is to split a string based upon it having a '/' in it. For example if I had: www.site.com/course/123456/216 in code (c#) I'd like to be able to split the string in code so that 123456 could be assigned to variable param1 and 216 be assigned to param2 (course is the 'friendly' name of the page). If I was to add a third '/' on the string I'd like this to become param3, etc, etc.
Ideally I'd like to be able to put this code somewhere that I could include it on whichever usercontrols I'd need it to work.

A: Why not just use split?
var valueArray = "www.site.com/course/123456/216".Split('/');

The array will have the entire string broken up
index 0 would be "www.site.com" and so forth.

A: Uri.Segments maybe what you are looking for:
new Uri("http://www.contoso.com/foo/bar/index.htm#search").Segments

Results in [ "/", "foo/", "bar/", "index.html" ]

A: Well, making the assumption that the values would not have / in them:
var splitVals = queryString.Split('/');
var vals = new Dictionary<string, string>();
for (int i = 2; i <= splitVals.Count; i++)
{
    vals.Add(string.Format("param{0}", i), vals[i]);
}

That would get you started. Now, if you're looking to set them to real variables then you'd need to do some casting and leverage reflection, but your question isn't near clear enough to make any real assumptions there.
EDIT
To make this code reusable I would build an extension method:
namespace System
{
    public static class StringExtensions
    {
        public static Dictionary<string, string> SplitQueryString(this string queryString)
        {
            var splitVals = queryString.Split('/');
            var vals = new Dictionary<string, string>();
            for (int i = 2; i <= splitVals.Count; i++)
            {
                vals.Add(string.Format("param{0}", i), vals[i]);
            }

            return vals;
        }
    }
}

because then you could do this:
var vals = queryString.SplitQueryString();

A: HttpContext.Current.Request.Url.AbsolutePath.Split('/')

A: http://msdn.microsoft.com/en-us/library/b873y76a.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
string QueryString = "1234/567/890";
string[] QueryArray = QueryString.Split('/');
Now QueryArray[0] = 1234, QueryArray[1] = 567, QueryArray[2] = 890,

A: url: server/func2/SubFunc2
// Get path components. Trailing separators. Returns { "/", "func2/", "sunFunc2" }.
string[] pathsegments = myUri.Segments;


text:
Q: Guessing lucky number assignment Can't seem to get the code to work on if player_guess in player_lucky_list:. It does not check if I had guessed the right number. Also having trouble with the task d.

d. If it is a number, and in the list, but doesn't match
lucky_number then you find out number(s) that has max
difference as is 10, and assign the numbers that has 10
difference into list input_diff and add the lucky_number if
it was not in the list, then write out:
"your number is 10 points more or less from these
numbers : {input_diff}, do you like to try again? (type 'Y'
= yes, 'N' = no)"

from datetime import datetime, date
import random

def age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

player_fname = input("Name: ")
player_age = int(input("Age: "))

running = True
while running:
    player_birthday = datetime.strptime(input("Birthday (format yyyymmdd): "), "%Y%m%d")
    age_player = int(age(player_birthday))
    if age_player == player_age:
        print("Wow your age is right, let's continue!")
        running = False
    else:
        print("Aha, we are in 2022 and your age is not right, kindly enter it again?")

lucky_number = random.randint(1, 200)
tries_count = 0

player_lucky_list = []
n = 10
for i in range(n):
    player_lucky_list.append(random.randint(0, 200))

player_lucky_guess = []
guessing = True
while guessing:
    message = "Hi {}, this is your try # {}".format(player_fname, tries_count)
    print(message)
    player_guess = input("Please enter number from {}: ".format(player_lucky_list))
    if player_guess in player_lucky_list:
        print("Congratulations, your lucky number is {} you got it from try # {}".format(player_guess, tries_count))
    elif str in player_guess:
        print("Sorry, wrong value, Enter a INTEGER NUMBER!!!!")
    else:
        print("Try again")
    tries_count += 1
    player_lucky_guess.append(player_guess)
    print(player_lucky_guess)

A: Your list is storing different int values.  The input function defaults to accepting strings.  So you need to convert the string of "player_guess" into an int.
while guessing:
    message = "Hi {}, this is your try # {}".format(player_fname, tries_count)
    print(message)
    player_guess = input("Please enter number from {}: ".format(player_lucky_list))
    if int(player_guess) in player_lucky_list:
        print("Congratulations, your lucky number is {} you got it from try # {}".format(player_guess, tries_count))
    elif int(player_guess) not in player_lucky_list:
        print("Sorry, wrong value, Enter a INTEGER NUMBER!!!!")
    else:
        print("Try again")
    tries_count += 1
    player_lucky_guess.append(player_guess)
    print(player_lucky_guess)


text:
Q: Ho use $sum (aggregation) for array of object and check greater than for each sum My document structure is as follow :
{
    "_id" : ObjectId("621ccb5ea46a9e41768e0ba8"),
    "cust_name" : "Anuj Kumar",
    "product" : [
        {
            "prod_name" : "Robot",
            "price" : 15000
        },
        {
            "prod_name" : "Keyboard",
            "price" : 65000
        }
    ],
    "order_date" : ISODate("2022-02-22T00:00:00Z"),
    "status" : "processed",
    "invoice" : {
        "invoice_no" : 111,
        "invoice_date" : ISODate("2022-02-22T00:00:00Z")
    }
}

How to do the following query...
List the details of orders with a value >10000.
I want to display only those objects whose sum of prices is greater than 10000
I try this
db.order.aggregate([{$project : {sumOfPrice : {$sum : "$product.price"} }}])

Output
{ "_id" : ObjectId("621ccb5ea46a9e41768e0ba8"), "sumOfPrice" : 80000 }
{ "_id" : ObjectId("621ccba9a46a9e41768e0ba9"), "sumOfPrice" : 16500 }
{ "_id" : ObjectId("621ccbfaa46a9e41768e0baa"), "sumOfPrice" : 5000 }

I want to check this sumOfPrice is greater than 10000 or not and display those order full object.

A: You can just add a $match stage right after that checks for this conditions, like so:
db.collection.aggregate([
  {
    $addFields: {
      sumOfPrice: {
        $sum: "$product.price"
      }
    }
  },
  {
    $match: {
      sumOfPrice: {
        $gt: 10000
      }
    }
  }
])

Mongo Playground

A: You can also use $expr operator with the find query as:
db.order.find({
    $expr: {
        $gt: [ {$sum: '$product.price'}, 10000 ]
    }
})

Mongo Playground


text:
Q: Multiplying 2 numbers, represented by 2 linked lists of digits I need some ideas for a homework assignment that I have.
Consider the following definition:
typedef struct listNode {
    int* dataPtr;
    struct listNode* next;
} ListNode;

typedef struct list {
    ListNode* head;
    ListNode* tail;
} List;

Each list node represents a single digit.
Each number is represented by a list, but in a reversed manner: the last digit of the number is the first list-node of the list, and the first digit of the number is the last list-node of the list.
I've written the function
void addNumbers(List n1, List n2, List *sum);

which returns a new list with the sum of the other two lists.
Now I have to write the function for multiplication:
void multNumbers(List n1, List n2 , List* prod);

And I'm kinda stuck with how to implement it. It's not about the code, it's about how to do it.
Needless to say, we're not allowed to convert the numbers into an integer, multiply and go convert the result to a list.
Any help would be highly appreciated.
Thanks.

A: This will be a good exercise in code reuse. Since you already have created a function that adds two linked list numbers, can you utilize that function to perform (parts of) the multiplication? After all, multiplication can be performed by hand by repeatedly multiplying the first number by one of the digits from the second number, and then adding all of the results. Try something along these lines:

*

*Create a linked list number that will contain the result, and set it to zero

*Loop through the digits of the second number

*

*For each digit, multiply the first number by that digit (you should write a separate function that does this; if you managed to write the addition function, this shouldn't be too hard)

*Append zeroes to the end of the result so that the digits get shifted far enough to the left

*Add the number to the result, using addNumbers()


text:
Q: Flask Python cannot execute method I am trying to run a Flask Server. I also have my ps4 controller connected which is shown in the .listen() function.
For some reason I can't understand this code isn't working. It seems to me that either the server, or the ps4 listener can run, but not both at the same time.
What am I missing?

def run():
    socketio.run(app, host='0.0.0.0', debug=True)
    ps4_controller = ManualController(interface="/dev/input/js0", connecting_using_ds4drv=False, car=Car())

    t1 = threading.Thread( target=ps4_controller.listen(), args=() )
    t1.start()

if __name__ == '__main__':
    run()


text:
Q: Android PWA - how to prevent reloading after switch between apps? If we have cheap Android phone with lack of resources, when several apps are opened and you switch between them - each one is being loaded again (because device doesn't have enough memory to keep them all alive in background).
When using PWA this may be very annoying. For example I fill some fields in my PWA and have to switch to mail app to copy some data. After returning to PWA it's refreshing (and taking some time to become interactive again)...
Is there a way to prevent this behaviour and keep PWA always alive even when switching to other apps?


text:
Q: Transaction for sql query stored in temp table I have a stored procedure build update query and store in temp table each time in loop.
Total query built UNKNOWN (2 to 4)
How can I put multi query in a transaction?
For example, temp table contains following rows in column EXPSQL (nvarchar)
id   EXPSQL
1    Update tableA SET Name = 'Test' WHERE id=1
2    Update tableB SET Name = 'Test2' WHERE id=10

How can I begin a transaction for a loop to exec above query? or is there any other way?
while @id < total
begin
    set @id = @id +1
    select @SQL = EXPSQL FROM #TEMPTABLE WHERE id=@id
    EXEC (@SQL)
end

Thanks

A: If you want to execute all as one:
begin transaction

while @id < total
begin
    set @id = @id +1
    select @SQL = EXPSQL FROM #TEMPTABLE WHERE id=@id
    EXEC (@SQL)

    -- if a error occurs go back to the original state
    if(@@error <> 0)
       rollback transaction
end

commit transaction

If you want to execute each one individually:
while @id < total
begin
    set @id = @id +1
    select @SQL = EXPSQL FROM #TEMPTABLE WHERE id=@id

    begin transaction
    EXEC (@SQL)

    -- if a error occurs go back to the original state
    if(@@error <> 0)
       rollback transaction
    else
       commit transaction
end


text:
Q: Website identify user without cookies and IP at server side I am currently working on an online shop website by ASP.NET MVC 5 framework, but the following is annoying me
Requirement & Approach
One of the requirements is the server should assume the cookies feature is disabled at the client side, thus instead of using cookies/session to identify the user, we decided to generate a GUID for each user (if no valid GUID present), append the GUID to every hyper link and use the retrieved GUID as the UID.
Situation
The system works fine at this point, until we added a verification to it. We would like to avoid Client A steals the GUID from Client B (it would be easy because the GUID is visible in the URL and SSL can do nothing about it), then the Client A add items to the shopping cart with Client B GUID, and wait till Client B pay for it (please ignore if the Client B review the cart or the shipping address).
Problem
What we have done to avoid the above hack is adding some information from the HTTP request header such as user IP, user agent, accepting languages etc... We verify the information on every request, treat the GUID as invalid if any info is changed.
The problem is we found out some of our ISPs in our region will send every request by a different IP, thus the user will gain a different GUID on every page/request.
It seems not so secure without the IP as a part of the identifier, we are looking for some other workaround to secure our clients, I have done on some researches and the followings are some possibly solutions:

*

*Using ETAG, however I am not quite understand but it seems not quite suitable for our project (in the MVC action we can only know if this is the first visit from the client of the requesting page, if a valid client visit a new page such as ConfirmOrder will be treated as invalid)

*Using the basic authorization by including the identity information in the request header, however in order to increase the user experience, we wish not to ask the user to input a username/pwd, but it seems we cannot assign a default identity from server side.

Any solution/suggestion/clues will be welcome, thanks for your time

A: Could you use cookies and only fallback to GUID + hard verification if cookies fail?
Alternatively you could do every request as an AJAX request and just replace the entiere page with the answer and update the URL (minus the GUID) via history.pushState(). This is also known as PJAX. But when cookies aren't allowed JavaScript is probably blocked as well.
I've also seen applications do every request as a POST, thus hiding every parameter. But that also makes page reloads or navigating via the back button harder for the user.


text:
Q: Show variable inside text field label In my Cocoa application I show the result of a calculation in a NSTextView, now I wish you could see the result in a NSextField, I tried in every way but did not succeed.
[textField insertText:[NSString stringWithFormat:@"%i \n", giorni]];

A: How about: (edited for the NS instead of UI textField)
[textField setIntValue:giorni];


text:
Q: Detect which column has the greatest value I have a table like this
id | a | b | c | status
---+---+---+---+--------
1  | 3 |12 |6  |   b
2  | 5 |8  |56 |   c
3  | 99|7  |23 |   a

I would like to detect which column has the greatest value (1,2 or 3) and then record the "status" of that row highest value (I used a,b,c just for the example)
How could I do this?
Thanks!

A: SELECT *,
    CASE GREATEST(a,b,c)
        WHEN a THEN 'a'
        WHEN b THEN 'b'
        WHEN c THEN 'c'
    END AS status
FROM yourtable

See it working online: sqlfiddle
Rewritten as an UPDATE statement:
UPDATE yourtable
SET status =
    CASE GREATEST(a,b,c)
        WHEN a THEN 'a'
        WHEN b THEN 'b'
        WHEN c THEN 'c'
    END


text:
Q: Joomla 3.8 Adding a Custom Registration Check I'm building a website using Joomla 3.8.0.
I'd like to add a custom question to the registration process.  For example, I'd like to ask them the capital city of Canada and then check upon submit if the answer was Ottawa.  I'd like to do this, if possible,using an extension and not modifying php code within Joomla.
Does anyone know of such an extension?  I've looked through the Joomla extensions directory already, but haven't seen one that seems to do what I want.  Seems they all simply allow custom fields, but not fields that can be reviewed for a specific answer as described above.  Preferably it would be free as well.
Thanks!

A: EasyCalcCheck Plus will do this for you. It's free. There are probably others too.


text:
Q: In-app only notifications / interactive toasts Our Android app currently has a large number of dialog and alert boxes.  I'd like to switch these to toasts, but there's a problem - some of them require the user to choose whether to view more info or just dismiss the popup.  It doesn't look like there's a way to do this with toasts.
Is there any existing Android library that supports tappable toasts (i.e., you tap it and it triggers a function call to a listener in the app, sort of like a notification)?  If not, is there a recommended alternative for this "tap-here-to-do-something-otherwise-I'll-just-vanish-in-a-few-seconds" UI pattern, or should I just roll my own fragment class for it?

A: I have to do something similar to my app so I wrote, DropViewNotification, a boiler plate to make it happen by animating the so-called notification into the screen. It doesn't do automatic dismiss as this should only act as a tool.
It accept any kind of view to make it versatile as I need to put at least two or three obvious view into it (TextView, ProgressBar, ImageView). You can switch it's content on the fly if you want to. Animation can also be customized for both showing and dismissing of the notification and the main content.
In real-life you might want to consider adding controller class to handle the display of the content and auto dismissal, etc. Hope it's of some use to you.


text:
Q: html string not being parsed with JSON.parse I am using JSON.parse for a list of products. I am running a regex to replace characters that were breaking the parse:
[\n|\t|\r]

It seems that I am still having issues when the following content is being copied into html.

A soul mate for your aluminum group lounge chair. Rest your weary feet on this matching ottoman - same suspension design, same light weight, same elegant scale as the lounge chair. Polished aluminum 4-star base, black pedestal. Glides.

Not sure which part is breaking the parser, and what I can do to fix it, short of removing the style and span tags.

A: You need to be more clear about exactly what steps you're taking between obtaining that HTML as a string, what you do to make it "JSON", and actually calling JSON.parse. Otherwise you're making it look like you're trying to use a JSON parser to parse HTML, which doesn't make sense.
that said, my guess is that it's the quote marks.

A: You shoudn't load HTML and CSS using JSON, load pure content and then wrap it into container. Maybe it will save a lot of hours of work in future.


text:
Q: What is the fastest way to create a list of directories specified in a file? I have a text file, "foo.txt", that specifies a directory in each line:
data/bar/foo
data/bar/foo/chum
data/bar/chum/foo
...

There could be millions of directories and subdirectories
What is the quickest way to create all the directories in bulk, using a terminal command ?
By quickest, I mean quickest to create all the directories. Since there are millions of directories there are many write operations.
I am using ubuntu 12.04.
EDIT: Keep in mind, the list may not fit in memory, since there are MILLIONS of lines, each representing a directory.
EDIT: My file has 4.5 million lines, each representing a directory, composed of alphanumeric characters, the path separator "/" , and possibly "../"
When I ran xargs -d '\n' mkdir -p < foo.txt after a while it kept printing errors until i did ctrl + c:
mkdir: cannot create directory `../myData/data/a/m/e/d': No space left on device
But running df -h gives the following output:
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda        48G   20G   28G  42% /
devtmpfs        2.0G  4.0K  2.0G   1% /dev
none            401M  164K  401M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            2.0G     0  2.0G   0% /run/shm

free -m
 total       used       free     shared    buffers     cached
Mem:          4002       3743        258          0       2870         13
-/+ buffers/cache:        859       3143
Swap:          255         26        229

EDIT:
df -i
Filesystem      Inodes   IUsed  IFree IUse% Mounted on
/dev/xvda      2872640 1878464 994176   66% /
devtmpfs        512053    1388 510665    1% /dev
none            512347     775 511572    1% /run
none            512347       1 512346    1% /run/lock
none            512347       1 512346    1% /run/shm

df -T
Filesystem     Type     1K-blocks     Used Available Use% Mounted on
/dev/xvda      ext4      49315312 11447636  37350680  24% /
devtmpfs       devtmpfs   2048212        4   2048208   1% /dev
none           tmpfs       409880      164    409716   1% /run
none           tmpfs         5120        0      5120   0% /run/lock
none           tmpfs      2049388        0   2049388   0% /run/shm

EDIT: I increased the number of inodes, and reduced the depth of my directories, and it seemed to work. It took 2m16seconds this time round.

A: With GNU xargs:
xargs -d '\n' mkdir -p -- < foo.txt

xargs will run as few mkdir commands as possible.
With standard syntax:
(export LC_ALL=C
 sed 's/[[:blank:]"\'\'']/\\&/g' < foo.txt | xargs mkdir -p --)

Where it's not efficient is that mkdir -p a/b/c will attempt some mkdir("a") and possibly stat("a") and chdir("a") and same for "a/b" even if "a/b" existed beforehand.
If your foo.txt has:
a
a/b
a/b/c

in that order, that is, if for each path, there have been a line for each of the path components before, then you can omit the -p and it will be significantly more efficient. Or alternatively:
perl -lne 'mkdir $_ or warn "$_: $!\n"' < foo.txt

Which avoids invoking a (many) mkdir command altogether.

A: I know we will get lot of answers for this question.But still you can TRY this :) :D
while read -r line; do mkdir -p "$line" ; done < file.txt

A: Try this one-liner:
for i in $(cat foo.txt) ; do mkdir -p $i ; done
This will create the directory/directory-tree in the current working directory. Not in bulk (as in all-the-directories-getting-created-simulataneously), but the creation will be done one after another.


text:
Q: Liveness and readiness probe return 404 My Spring-Boot Application is running on Kubernetes.
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.12</version>
</parent>

According to Spring-Boot reference, livenessProbe and readinessProbe would be enabled automatically.
https://docs.spring.io/spring-boot/docs/2.5.14/reference/htmlsingle/#actuator.endpoints.kubernetes-probes

These health groups are only enabled automatically if the application is running in a Kubernetes environment.

They will also be exposed as separate HTTP Probes using Health Groups: /actuator/health/liveness and /actuator/health/readiness.

But the endpoints (/actuator/health/liveness and /actuator/health/readiness) in My Spring-Boot Application returns 404, what's wrong here?
The component of livenessState and readinessState is enabled, but the health group is not.

I debug the code and find that the method org.springframework.boot.actuate.autoconfigure.health.HealthEndpointConfiguration.HealthEndpointGroupsBeanPostProcessor#postProcessAfterInitialization doesn't work. Because there's no bean instanceof HealthEndpointGroups, Why?
/**
 * {@link BeanPostProcessor} to invoke {@link HealthEndpointGroupsPostProcessor}
 * beans.
 */
static class HealthEndpointGroupsBeanPostProcessor implements BeanPostProcessor {

    private final ObjectProvider<HealthEndpointGroupsPostProcessor> postProcessors;

    HealthEndpointGroupsBeanPostProcessor(ObjectProvider<HealthEndpointGroupsPostProcessor> postProcessors) {
        this.postProcessors = postProcessors;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        // there's no bean instanceof HealthEndpointGroups here, Why?

        if (bean instanceof HealthEndpointGroups) {
            return applyPostProcessors((HealthEndpointGroups) bean);
        }
        return bean;
    }

    private Object applyPostProcessors(HealthEndpointGroups bean) {
        for (HealthEndpointGroupsPostProcessor postProcessor : this.postProcessors.orderedStream()
                .toArray(HealthEndpointGroupsPostProcessor[]::new)) {
            bean = postProcessor.postProcessHealthEndpointGroups(bean);
        }
        return bean;
    }

}

I try to run the application locally with adding KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_HOST environment variables, to enable probes. But it didn't work as well.
/**
 * {@link SpringBootCondition} to enable or disable probes.
 * <p>
 * Probes are enabled if the dedicated configuration property is enabled or if the
 * Kubernetes cloud environment is detected/enforced.
 */
static class ProbesCondition extends SpringBootCondition {

    private static final String ENABLED_PROPERTY = "management.endpoint.health.probes.enabled";

    private static final String DEPRECATED_ENABLED_PROPERTY = "management.health.probes.enabled";

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        ConditionMessage.Builder message = ConditionMessage.forCondition("Probes availability");
        ConditionOutcome outcome = onProperty(environment, message, ENABLED_PROPERTY);
        if (outcome != null) {
            return outcome;
        }
        outcome = onProperty(environment, message, DEPRECATED_ENABLED_PROPERTY);
        if (outcome != null) {
            return outcome;
        }
        if (CloudPlatform.getActive(environment) == CloudPlatform.KUBERNETES) {
            return ConditionOutcome.match(message.because("running on Kubernetes"));
        }
        return ConditionOutcome.noMatch(message.because("not running on a supported cloud platform"));
    }

    private ConditionOutcome onProperty(Environment environment, ConditionMessage.Builder message,
            String propertyName) {
        String enabled = environment.getProperty(propertyName);
        if (enabled != null) {
            boolean match = !"false".equalsIgnoreCase(enabled);
            return new ConditionOutcome(match, message.because("'" + propertyName + "' set to '" + enabled + "'"));
        }
        return null;
    }

}

I run application on Kubernetes, but it doesn't work for me. I find that removing dependency of Spring Cloud Sleuth, it would run normally. Is there any conflict between SpringBoot and Spring Cloud Sleuth?
Removing the follow dependency
    <!--traceId -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth-zipkin</artifactId>
    </dependency>

yaml:
management:
  server:
    port: 9235
  endpoints:
    web:
      exposure:
        include: ${MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE:*}

k8s:
  readinessProbe:
    httpGet:
      path: /actuator/health/readiness
      port: {{ .Values.deployment.managementPort }}
    failureThreshold: 3
    initialDelaySeconds: 150
    periodSeconds: 10
    successThreshold: 1
    timeoutSeconds: 10
  livenessProbe:
    httpGet:
      path: /actuator/health/liveness
      port: {{ .Values.deployment.managementPort }}
    failureThreshold: 3
    initialDelaySeconds: 180
    periodSeconds: 10
    successThreshold: 1
    timeoutSeconds: 10

A: AFAIK Health groups are automatically enabled only if the application met below 2 conditions:
1)Runs in a Kubernetes deployment environment
Spring Boot auto-detects Kubernetes deployment environments by checking the environment for "*_SERVICE_HOST" and "*_SERVICE_PORT" variables. You can override this detection with the spring.main.cloud-platform configuration property. Spring Boot helps you to manage the state of your application and export it with HTTP Kubernetes Probes using Actuator.
2)The management.health.probes.enabled property is set to true
If the application meets either of the above conditions, then auto-configuration registers.
Refer to Baeldung, Liveness and Readiness Probes in Spring Boot, Auto-Configurations by Mona Mohamadinia, for more information.
Also refer to github link, Kubernetes readiness probe endpoint returning 404 #22562 for more information.